code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* Copyright (c) 2011-2014, Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file
* @brief Misc utilities
*
* Misc utilities usable by the kernel and application code.
*/
#ifndef _UTIL__H_
#define _UTIL__H_
#ifndef _ASMLANGUAGE
#include <ble_types/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Helper to pass a int as a pointer or vice-versa. */
#define POINTER_TO_UINT(x) ((uintptr_t) (x))
#define UINT_TO_POINTER(x) ((void *) (uintptr_t) (x))
#define POINTER_TO_INT(x) ((intptr_t) (x))
#define INT_TO_POINTER(x) ((void *) (intptr_t) (x))
#if !(defined (__CHAR_BIT__) && defined (__SIZEOF_LONG__))
# error Missing required predefined macros for BITS_PER_LONG calculation
#endif
#define BITS_PER_LONG (__CHAR_BIT__ * __SIZEOF_LONG__)
/* Create a contiguous bitmask starting at bit position @l and ending at
* position @h.
*/
#define GENMASK(h, l) \
(((~0UL) - (1UL << (l)) + 1) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
/* Evaluates to 0 if cond is true-ish; compile error otherwise */
#define ZERO_OR_COMPILE_ERROR(cond) ((int) sizeof(char[1 - 2 * !(cond)]) - 1)
/* Evaluates to 0 if array is an array; compile error if not array (e.g.
* pointer)
*/
#define IS_ARRAY(array) \
ZERO_OR_COMPILE_ERROR( \
!__builtin_types_compatible_p(__typeof__(array), \
__typeof__(&(array)[0])))
/* Evaluates to number of elements in an array; compile error if not
* an array (e.g. pointer)
*/
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) \
((unsigned long) (IS_ARRAY(array) + \
(sizeof(array) / sizeof((array)[0]))))
#endif
/* Evaluates to 1 if ptr is part of array, 0 otherwise; compile error if
* "array" argument is not an array (e.g. "ptr" and "array" mixed up)
*/
#define PART_OF_ARRAY(array, ptr) \
((ptr) && ((ptr) >= &array[0] && (ptr) < &array[ARRAY_SIZE(array)]))
#define CONTAINER_OF(ptr, type, field) \
((type *)(((char *)(ptr)) - offsetof(type, field)))
/* round "x" up/down to next multiple of "align" (which must be a power of 2) */
#define ROUND_UP(x, align) \
(((unsigned long)(x) + ((unsigned long)(align) - 1)) & \
~((unsigned long)(align) - 1))
#define ROUND_DOWN(x, align) \
((unsigned long)(x) & ~((unsigned long)(align) - 1))
/* round up/down to the next word boundary */
#define WB_UP(x) ROUND_UP(x, sizeof(void *))
#define WB_DN(x) ROUND_DOWN(x, sizeof(void *))
#define ceiling_fraction(numerator, divider) \
(((numerator) + ((divider) - 1)) / (divider))
/** @brief Return larger value of two provided expressions.
*
* @note Arguments are evaluated twice. See Z_MAX for GCC only, single
* evaluation version.
*/
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
/** @brief Return smaller value of two provided expressions.
*
* @note Arguments are evaluated twice. See Z_MIN for GCC only, single
* evaluation version.
*/
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
static inline bool is_power_of_two(unsigned int x)
{
return (x != 0U) && ((x & (x - 1)) == 0U);
}
static inline s64_t arithmetic_shift_right(s64_t value, u8_t shift)
{
s64_t sign_ext;
if (shift == 0U) {
return value;
}
/* extract sign bit */
sign_ext = (value >> 63) & 1;
/* make all bits of sign_ext be the same as the value's sign bit */
sign_ext = -sign_ext;
/* shift value and fill opened bit positions with sign bit */
return (value >> shift) | (sign_ext << (64 - shift));
}
/**
* @brief Convert a single character into a hexadecimal nibble.
*
* @param[in] c The character to convert
* @param x The address of storage for the converted number.
*
* @return Zero on success or (negative) error code otherwise.
*/
int char2hex(char c, u8_t *x);
/**
* @brief Convert a single hexadecimal nibble into a character.
*
* @param[in] c The number to convert
* @param x The address of storage for the converted character.
*
* @return Zero on success or (negative) error code otherwise.
*/
int hex2char(u8_t x, char *c);
/**
* @brief Convert a binary array into string representation.
*
* @param[in] buf The binary array to convert
* @param[in] buflen The length of the binary array to convert
* @param[out] hex Address of where to store the string representation.
* @param[in] hexlen Size of the storage area for string representation.
*
* @return The length of the converted string, or 0 if an error occurred.
*/
size_t bin2hex(const u8_t *buf, size_t buflen, char *hex, size_t hexlen);
/*
* Convert hex string to byte string
* Return number of bytes written to buf, or 0 on error
* @return The length of the converted array, or 0 if an error occurred.
*/
/**
* @brief Convert a hexadecimal string into a binary array.
*
* @param[in] hex The hexadecimal string to convert
* @param[in] hexlen The length of the hexadecimal string to convert.
* @param[out] buf Address of where to store the binary data
* @param[in] buflen Size of the storage area for binary data
*
* @return The length of the binary array , or 0 if an error occurred.
*/
size_t hex2bin(const char *hex, size_t hexlen, u8_t *buf, size_t buflen);
/**
* @brief Convert a u8_t into decimal string representation.
*
* Convert a u8_t value into ASCII decimal string representation.
* The string is terminated if there is enough space in buf.
*
* @param[out] buf Address of where to store the string representation.
* @param[in] buflen Size of the storage area for string representation.
* @param[in] value The value to convert to decimal string
*
* @return The length of the converted string (excluding terminator if
* any), or 0 if an error occurred.
*/
u8_t u8_to_dec(char *buf, u8_t buflen, u8_t value);
#endif /* !_ASMLANGUAGE */
/* KB, MB, GB */
#define KB(x) ((x) << 10)
#define MB(x) (KB(x) << 10)
#define GB(x) (MB(x) << 10)
/* KHZ, MHZ */
#define KHZ(x) ((x) * 1000)
#define MHZ(x) (KHZ(x) * 1000)
#ifndef BIT
#if defined(_ASMLANGUAGE)
#define BIT(n) (1 << (n))
#else
#define BIT(n) (1UL << (n))
#endif
#endif
/** 64-bit unsigned integer with bit position _n set */
#define BIT64(_n) (1ULL << (_n))
/**
* @brief Macro sets or clears bit depending on boolean value
*
* @param var Variable to be altered
* @param bit Bit number
* @param set Value 0 clears bit, any other value sets bit
*/
#define WRITE_BIT(var, bit, set) \
((var) = (set) ? ((var) | BIT(bit)) : ((var) & ~BIT(bit)))
#define BIT_MASK(n) (BIT(n) - 1)
/**
* @brief Check for macro definition in compiler-visible expressions
*
* This trick was pioneered in Linux as the config_enabled() macro.
* The madness has the effect of taking a macro value that may be
* defined to "1" (e.g. CONFIG_MYFEATURE), or may not be defined at
* all and turning it into a literal expression that can be used at
* "runtime". That is, it works similarly to
* "defined(CONFIG_MYFEATURE)" does except that it is an expansion
* that can exist in a standard expression and be seen by the compiler
* and optimizer. Thus much ifdef usage can be replaced with cleaner
* expressions like:
*
* if (IS_ENABLED(CONFIG_MYFEATURE))
* myfeature_enable();
*
* INTERNAL
* First pass just to expand any existing macros, we need the macro
* value to be e.g. a literal "1" at expansion time in the next macro,
* not "(1)", etc... Standard recursive expansion does not work.
*/
#define IS_ENABLED(config_macro) Z_IS_ENABLED1(config_macro)
/* Now stick on a "_XXXX" prefix, it will now be "_XXXX1" if config_macro
* is "1", or just "_XXXX" if it's undefined.
* ENABLED: Z_IS_ENABLED2(_XXXX1)
* DISABLED Z_IS_ENABLED2(_XXXX)
*/
#define Z_IS_ENABLED1(config_macro) Z_IS_ENABLED2(_XXXX##config_macro)
/* Here's the core trick, we map "_XXXX1" to "_YYYY," (i.e. a string
* with a trailing comma), so it has the effect of making this a
* two-argument tuple to the preprocessor only in the case where the
* value is defined to "1"
* ENABLED: _YYYY, <--- note comma!
* DISABLED: _XXXX
*/
#define _XXXX1 _YYYY,
/* Then we append an extra argument to fool the gcc preprocessor into
* accepting it as a varargs macro.
* arg1 arg2 arg3
* ENABLED: Z_IS_ENABLED3(_YYYY, 1, 0)
* DISABLED Z_IS_ENABLED3(_XXXX 1, 0)
*/
#define Z_IS_ENABLED2(one_or_two_args) Z_IS_ENABLED3(one_or_two_args true, false)
/* And our second argument is thus now cooked to be 1 in the case
* where the value is defined to 1, and 0 if not:
*/
#define Z_IS_ENABLED3(ignore_this, val, ...) val
/**
* @brief Insert code depending on result of flag evaluation.
*
* This is based on same idea as @ref IS_ENABLED macro but as the result of
* flag evaluation provided code is injected. Because preprocessor interprets
* each comma as an argument boundary, code must be provided in the brackets.
* Brackets are stripped away during macro processing.
*
* Usage example:
*
* \#define MACRO(x) COND_CODE_1(CONFIG_FLAG, (bt_u32_t x;), ())
*
* It can be considered as alternative to:
*
* \#if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
* \#define MACRO(x) bt_u32_t x;
* \#else
* \#define MACRO(x)
* \#endif
*
* However, the advantage of that approach is that code is resolved in place
* where it is used while \#if method resolves given macro when header is
* included and product is fixed in the given scope.
*
* @note Flag can also be a result of preprocessor output e.g.
* product of NUM_VA_ARGS_LESS_1(...).
*
* @param _flag Evaluated flag
* @param _if_1_code Code used if flag exists and equal 1. Argument must be
* in brackets.
* @param _else_code Code used if flag doesn't exists or isn't equal 1.
*
*/
#define COND_CODE_1(_flag, _if_1_code, _else_code) \
Z_COND_CODE_1(_flag, _if_1_code, _else_code)
#define Z_COND_CODE_1(_flag, _if_1_code, _else_code) \
__COND_CODE(_XXXX##_flag, _if_1_code, _else_code)
/**
* @brief Insert code if flag is defined and equals 1.
*
* Usage example:
*
* IF_ENABLED(CONFIG_FLAG, (bt_u32_t foo;))
*
* It can be considered as more compact alternative to:
*
* \#if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
* bt_u32_t foo;
* \#endif
*
* @param _flag Evaluated flag
* @param _code Code used if flag exists and equal 1. Argument must be
* in brackets.
*/
#define IF_ENABLED(_flag, _code) \
COND_CODE_1(_flag, _code, ())
/**
* @brief Check if defined name does have replacement string.
*
* If defined macro has value this will return true, otherwise
* it will return false. It only works with defined macros, so additional
* test (if defined) may be needed in some cases.
*
* This macro may be used, with COND_CODE_* macros, while processing
* __VA_ARG__ to avoid processing empty arguments.
*
* Note that this macro is indented to check macro names that evaluate
* to replacement lists being empty or containing numbers or macro name
* like tokens.
*
* Example:
*
* #define EMPTY
* #define NON_EMPTY 1
* #undef UNDEFINED
* IS_EMPTY(EMPTY)
* IS_EMPTY(NON_EMPTY)
* IS_EMPTY(UNDEFINED)
* #if defined(EMPTY) && IS_EMPTY(EMPTY) == true
* ...
* #endif
*
* In above examples, the invocations of IS_EMPTY(...) will return: true,
* false, true and conditional code will be included.
*
* @param a Makro to check
*/
#define IS_EMPTY(a) Z_IS_EMPTY_(a, true, false,)
#define Z_IS_EMPTY_(...) Z_IS_EMPTY__(__VA_ARGS__)
#define Z_IS_EMPTY__(a, ...) Z_IS_EMPTY___(_ZZ##a##ZZ0, __VA_ARGS__)
#define Z_IS_EMPTY___(...) Z_IS_EMPTY____(GET_ARGS_LESS_1(__VA_ARGS__))
#define Z_IS_EMPTY____(...) GET_ARG2(__VA_ARGS__)
/**
* @brief Remove empty arguments from list.
*
* Due to evaluation, __VA_ARGS__ and other preprocessor generated lists
* may contain empty elements, e.g.:
*
* #define LIST ,a,b,,d,
*
* In above example the first, the element between b and d, and the last
* are empty.
* When processing such lists, by for-each type loops, all empty elements
* will be processed, and may require filtering out within a loop.
* To make that process easier, it is enough to invoke LIST_DROP_EMPTY
* which will remove all empty elements from list.
*
* Example:
* LIST_DROP_EMPTY(list)
* will return:
* a,b,d
* Notice that ',' are preceded by space.
*
* @param ... list to be processed
*/
#define LIST_DROP_EMPTY(...) \
Z_LIST_DROP_FIRST(FOR_EACH(Z_LIST_NO_EMPTIES, __VA_ARGS__))
/* Adding ',' after each element would add empty element at the end of
* list, which is hard to remove, so instead precede each element with ',',
* this way first element is empty, and this one is easy to drop.
*/
#define Z_LIST_ADD_ELEM(e) EMPTY, e
#define Z_LIST_DROP_FIRST(...) GET_ARGS_LESS_1(__VA_ARGS__)
#define Z_LIST_NO_EMPTIES(e) \
COND_CODE_1(IS_EMPTY(e), (), (Z_LIST_ADD_ELEM(e)))
/**
* @brief Insert code depending on result of flag evaluation.
*
* See @ref COND_CODE_1 for details.
*
* @param _flag Evaluated flag
* @param _if_0_code Code used if flag exists and equal 0. Argument must be
* in brackets.
* @param _else_code Code used if flag doesn't exists or isn't equal 0.
*
*/
#define COND_CODE_0(_flag, _if_0_code, _else_code) \
Z_COND_CODE_0(_flag, _if_0_code, _else_code)
#define Z_COND_CODE_0(_flag, _if_0_code, _else_code) \
__COND_CODE(_ZZZZ##_flag, _if_0_code, _else_code)
#define _ZZZZ0 _YYYY,
/* Macro used internally by @ref COND_CODE_1 and @ref COND_CODE_0. */
#define __COND_CODE(one_or_two_args, _if_code, _else_code) \
__GET_ARG2_DEBRACKET(one_or_two_args _if_code, _else_code)
/* Macro used internally to remove brackets from argument. */
#define __DEBRACKET(...) __VA_ARGS__
/* Macro used internally for getting second argument and removing brackets
* around that argument. It is expected that parameter is provided in brackets
*/
#define __GET_ARG2_DEBRACKET(ignore_this, val, ...) __DEBRACKET val
/**
* @brief Macro with empty replacement list
*
* This trivial definition is provided to use where macro is expected
* to evaluate to empty replacement string or when it is needed to
* cheat checkpatch.
*
* Examples
*
* #define LIST_ITEM(n) , item##n
*
* would cause error with checkpatch, but:
*
* #define LIST_TIEM(n) EMPTY, item##m
*
* would not.
*/
#define EMPTY
/**
* @brief Get first argument from variable list of arguments
*/
#define GET_ARG1(arg1, ...) arg1
/**
* @brief Get second argument from variable list of arguments
*/
#define GET_ARG2(arg1, arg2, ...) arg2
/**
* @brief Get all arguments except the first one.
*/
#define GET_ARGS_LESS_1(val, ...) __VA_ARGS__
/**
* Macros for doing code-generation with the preprocessor.
*
* Generally it is better to generate code with the preprocessor than
* to copy-paste code or to generate code with the build system /
* python script's etc.
*
* http://stackoverflow.com/a/12540675
*/
#define UTIL_EMPTY(...)
#define UTIL_DEFER(...) __VA_ARGS__ UTIL_EMPTY()
#define UTIL_OBSTRUCT(...) __VA_ARGS__ UTIL_DEFER(UTIL_EMPTY)()
#define UTIL_EXPAND(...) __VA_ARGS__
#define UTIL_EVAL(...) UTIL_EVAL1(UTIL_EVAL1(UTIL_EVAL1(__VA_ARGS__)))
#define UTIL_EVAL1(...) UTIL_EVAL2(UTIL_EVAL2(UTIL_EVAL2(__VA_ARGS__)))
#define UTIL_EVAL2(...) UTIL_EVAL3(UTIL_EVAL3(UTIL_EVAL3(__VA_ARGS__)))
#define UTIL_EVAL3(...) UTIL_EVAL4(UTIL_EVAL4(UTIL_EVAL4(__VA_ARGS__)))
#define UTIL_EVAL4(...) UTIL_EVAL5(UTIL_EVAL5(UTIL_EVAL5(__VA_ARGS__)))
#define UTIL_EVAL5(...) __VA_ARGS__
#define UTIL_CAT(a, ...) UTIL_PRIMITIVE_CAT(a, __VA_ARGS__)
#define UTIL_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__
#define UTIL_INC(x) UTIL_PRIMITIVE_CAT(UTIL_INC_, x)
#define UTIL_INC_0 1
#define UTIL_INC_1 2
#define UTIL_INC_2 3
#define UTIL_INC_3 4
#define UTIL_INC_4 5
#define UTIL_INC_5 6
#define UTIL_INC_6 7
#define UTIL_INC_7 8
#define UTIL_INC_8 9
#define UTIL_INC_9 10
#define UTIL_INC_10 11
#define UTIL_INC_11 12
#define UTIL_INC_12 13
#define UTIL_INC_13 14
#define UTIL_INC_14 15
#define UTIL_INC_15 16
#define UTIL_INC_16 17
#define UTIL_INC_17 18
#define UTIL_INC_18 19
#define UTIL_INC_19 20
#define UTIL_INC_20 21
#define UTIL_INC_21 22
#define UTIL_INC_22 23
#define UTIL_INC_23 24
#define UTIL_INC_24 25
#define UTIL_INC_25 26
#define UTIL_INC_26 27
#define UTIL_INC_27 28
#define UTIL_INC_28 29
#define UTIL_INC_29 30
#define UTIL_INC_30 31
#define UTIL_INC_31 32
#define UTIL_INC_32 33
#define UTIL_INC_33 34
#define UTIL_INC_34 35
#define UTIL_INC_35 36
#define UTIL_INC_36 37
#define UTIL_INC_37 38
#define UTIL_INC_38 39
#define UTIL_INC_39 40
#define UTIL_INC_40 41
#define UTIL_INC_41 42
#define UTIL_INC_42 43
#define UTIL_INC_43 44
#define UTIL_INC_44 45
#define UTIL_INC_45 46
#define UTIL_INC_46 47
#define UTIL_INC_47 48
#define UTIL_INC_48 49
#define UTIL_INC_49 50
#define UTIL_INC_50 51
#define UTIL_INC_51 52
#define UTIL_INC_52 53
#define UTIL_INC_53 54
#define UTIL_INC_54 55
#define UTIL_INC_55 56
#define UTIL_INC_56 57
#define UTIL_INC_57 58
#define UTIL_INC_58 59
#define UTIL_INC_59 60
#define UTIL_INC_50 51
#define UTIL_INC_51 52
#define UTIL_INC_52 53
#define UTIL_INC_53 54
#define UTIL_INC_54 55
#define UTIL_INC_55 56
#define UTIL_INC_56 57
#define UTIL_INC_57 58
#define UTIL_INC_58 59
#define UTIL_INC_59 60
#define UTIL_INC_60 61
#define UTIL_INC_61 62
#define UTIL_INC_62 63
#define UTIL_INC_63 64
#define UTIL_INC_64 65
#define UTIL_INC_65 66
#define UTIL_INC_66 67
#define UTIL_INC_67 68
#define UTIL_INC_68 69
#define UTIL_INC_69 70
#define UTIL_INC_70 71
#define UTIL_INC_71 72
#define UTIL_INC_72 73
#define UTIL_INC_73 74
#define UTIL_INC_74 75
#define UTIL_INC_75 76
#define UTIL_INC_76 77
#define UTIL_INC_77 78
#define UTIL_INC_78 79
#define UTIL_INC_79 80
#define UTIL_INC_80 81
#define UTIL_INC_81 82
#define UTIL_INC_82 83
#define UTIL_INC_83 84
#define UTIL_INC_84 85
#define UTIL_INC_85 86
#define UTIL_INC_86 87
#define UTIL_INC_87 88
#define UTIL_INC_88 89
#define UTIL_INC_89 90
#define UTIL_INC_90 91
#define UTIL_INC_91 92
#define UTIL_INC_92 93
#define UTIL_INC_93 94
#define UTIL_INC_94 95
#define UTIL_INC_95 96
#define UTIL_INC_96 97
#define UTIL_INC_97 98
#define UTIL_INC_98 99
#define UTIL_INC_99 100
#define UTIL_DEC(x) UTIL_PRIMITIVE_CAT(UTIL_DEC_, x)
#define UTIL_DEC_0 0
#define UTIL_DEC_1 0
#define UTIL_DEC_2 1
#define UTIL_DEC_3 2
#define UTIL_DEC_4 3
#define UTIL_DEC_5 4
#define UTIL_DEC_6 5
#define UTIL_DEC_7 6
#define UTIL_DEC_8 7
#define UTIL_DEC_9 8
#define UTIL_DEC_10 9
#define UTIL_DEC_11 10
#define UTIL_DEC_12 11
#define UTIL_DEC_13 12
#define UTIL_DEC_14 13
#define UTIL_DEC_15 14
#define UTIL_DEC_16 15
#define UTIL_DEC_17 16
#define UTIL_DEC_18 17
#define UTIL_DEC_19 18
#define UTIL_DEC_20 19
#define UTIL_DEC_21 20
#define UTIL_DEC_22 21
#define UTIL_DEC_23 22
#define UTIL_DEC_24 23
#define UTIL_DEC_25 24
#define UTIL_DEC_26 25
#define UTIL_DEC_27 26
#define UTIL_DEC_28 27
#define UTIL_DEC_29 28
#define UTIL_DEC_30 29
#define UTIL_DEC_31 30
#define UTIL_DEC_32 31
#define UTIL_DEC_33 32
#define UTIL_DEC_34 33
#define UTIL_DEC_35 34
#define UTIL_DEC_36 35
#define UTIL_DEC_37 36
#define UTIL_DEC_38 37
#define UTIL_DEC_39 38
#define UTIL_DEC_40 39
#define UTIL_DEC_41 40
#define UTIL_DEC_42 41
#define UTIL_DEC_43 42
#define UTIL_DEC_44 43
#define UTIL_DEC_45 44
#define UTIL_DEC_46 45
#define UTIL_DEC_47 46
#define UTIL_DEC_48 47
#define UTIL_DEC_49 48
#define UTIL_DEC_50 49
#define UTIL_DEC_51 50
#define UTIL_DEC_52 51
#define UTIL_DEC_53 52
#define UTIL_DEC_54 53
#define UTIL_DEC_55 54
#define UTIL_DEC_56 55
#define UTIL_DEC_57 56
#define UTIL_DEC_58 57
#define UTIL_DEC_59 58
#define UTIL_DEC_60 59
#define UTIL_DEC_61 60
#define UTIL_DEC_62 61
#define UTIL_DEC_63 62
#define UTIL_DEC_64 63
#define UTIL_DEC_65 64
#define UTIL_DEC_66 65
#define UTIL_DEC_67 66
#define UTIL_DEC_68 67
#define UTIL_DEC_69 68
#define UTIL_DEC_70 69
#define UTIL_DEC_71 70
#define UTIL_DEC_72 71
#define UTIL_DEC_73 72
#define UTIL_DEC_74 73
#define UTIL_DEC_75 74
#define UTIL_DEC_76 75
#define UTIL_DEC_77 76
#define UTIL_DEC_78 77
#define UTIL_DEC_79 78
#define UTIL_DEC_80 79
#define UTIL_DEC_81 80
#define UTIL_DEC_82 81
#define UTIL_DEC_83 82
#define UTIL_DEC_84 83
#define UTIL_DEC_85 84
#define UTIL_DEC_86 85
#define UTIL_DEC_87 86
#define UTIL_DEC_88 87
#define UTIL_DEC_89 88
#define UTIL_DEC_90 89
#define UTIL_DEC_91 90
#define UTIL_DEC_92 91
#define UTIL_DEC_93 92
#define UTIL_DEC_94 93
#define UTIL_DEC_95 94
#define UTIL_DEC_96 95
#define UTIL_DEC_97 96
#define UTIL_DEC_98 97
#define UTIL_DEC_99 98
#define UTIL_DEC_100 99
#define UTIL_DEC_101 100
#define UTIL_DEC_102 101
#define UTIL_DEC_103 102
#define UTIL_DEC_104 103
#define UTIL_DEC_105 104
#define UTIL_DEC_106 105
#define UTIL_DEC_107 106
#define UTIL_DEC_108 107
#define UTIL_DEC_109 108
#define UTIL_DEC_110 109
#define UTIL_DEC_111 110
#define UTIL_DEC_112 111
#define UTIL_DEC_113 112
#define UTIL_DEC_114 113
#define UTIL_DEC_115 114
#define UTIL_DEC_116 115
#define UTIL_DEC_117 116
#define UTIL_DEC_118 117
#define UTIL_DEC_119 118
#define UTIL_DEC_120 119
#define UTIL_DEC_121 120
#define UTIL_DEC_122 121
#define UTIL_DEC_123 122
#define UTIL_DEC_124 123
#define UTIL_DEC_125 124
#define UTIL_DEC_126 125
#define UTIL_DEC_127 126
#define UTIL_DEC_128 127
#define UTIL_DEC_129 128
#define UTIL_DEC_130 129
#define UTIL_DEC_131 130
#define UTIL_DEC_132 131
#define UTIL_DEC_133 132
#define UTIL_DEC_134 133
#define UTIL_DEC_135 134
#define UTIL_DEC_136 135
#define UTIL_DEC_137 136
#define UTIL_DEC_138 137
#define UTIL_DEC_139 138
#define UTIL_DEC_140 139
#define UTIL_DEC_141 140
#define UTIL_DEC_142 141
#define UTIL_DEC_143 142
#define UTIL_DEC_144 143
#define UTIL_DEC_145 144
#define UTIL_DEC_146 145
#define UTIL_DEC_147 146
#define UTIL_DEC_148 147
#define UTIL_DEC_149 148
#define UTIL_DEC_150 149
#define UTIL_DEC_151 150
#define UTIL_DEC_152 151
#define UTIL_DEC_153 152
#define UTIL_DEC_154 153
#define UTIL_DEC_155 154
#define UTIL_DEC_156 155
#define UTIL_DEC_157 156
#define UTIL_DEC_158 157
#define UTIL_DEC_159 158
#define UTIL_DEC_160 159
#define UTIL_DEC_161 160
#define UTIL_DEC_162 161
#define UTIL_DEC_163 162
#define UTIL_DEC_164 163
#define UTIL_DEC_165 164
#define UTIL_DEC_166 165
#define UTIL_DEC_167 166
#define UTIL_DEC_168 167
#define UTIL_DEC_169 168
#define UTIL_DEC_170 169
#define UTIL_DEC_171 170
#define UTIL_DEC_172 171
#define UTIL_DEC_173 172
#define UTIL_DEC_174 173
#define UTIL_DEC_175 174
#define UTIL_DEC_176 175
#define UTIL_DEC_177 176
#define UTIL_DEC_178 177
#define UTIL_DEC_179 178
#define UTIL_DEC_180 179
#define UTIL_DEC_181 180
#define UTIL_DEC_182 181
#define UTIL_DEC_183 182
#define UTIL_DEC_184 183
#define UTIL_DEC_185 184
#define UTIL_DEC_186 185
#define UTIL_DEC_187 186
#define UTIL_DEC_188 187
#define UTIL_DEC_189 188
#define UTIL_DEC_190 189
#define UTIL_DEC_191 190
#define UTIL_DEC_192 191
#define UTIL_DEC_193 192
#define UTIL_DEC_194 193
#define UTIL_DEC_195 194
#define UTIL_DEC_196 195
#define UTIL_DEC_197 196
#define UTIL_DEC_198 197
#define UTIL_DEC_199 198
#define UTIL_DEC_200 199
#define UTIL_DEC_201 200
#define UTIL_DEC_202 201
#define UTIL_DEC_203 202
#define UTIL_DEC_204 203
#define UTIL_DEC_205 204
#define UTIL_DEC_206 205
#define UTIL_DEC_207 206
#define UTIL_DEC_208 207
#define UTIL_DEC_209 208
#define UTIL_DEC_210 209
#define UTIL_DEC_211 210
#define UTIL_DEC_212 211
#define UTIL_DEC_213 212
#define UTIL_DEC_214 213
#define UTIL_DEC_215 214
#define UTIL_DEC_216 215
#define UTIL_DEC_217 216
#define UTIL_DEC_218 217
#define UTIL_DEC_219 218
#define UTIL_DEC_220 219
#define UTIL_DEC_221 220
#define UTIL_DEC_222 221
#define UTIL_DEC_223 222
#define UTIL_DEC_224 223
#define UTIL_DEC_225 224
#define UTIL_DEC_226 225
#define UTIL_DEC_227 226
#define UTIL_DEC_228 227
#define UTIL_DEC_229 228
#define UTIL_DEC_230 229
#define UTIL_DEC_231 230
#define UTIL_DEC_232 231
#define UTIL_DEC_233 232
#define UTIL_DEC_234 233
#define UTIL_DEC_235 234
#define UTIL_DEC_236 235
#define UTIL_DEC_237 236
#define UTIL_DEC_238 237
#define UTIL_DEC_239 238
#define UTIL_DEC_240 239
#define UTIL_DEC_241 240
#define UTIL_DEC_242 241
#define UTIL_DEC_243 242
#define UTIL_DEC_244 243
#define UTIL_DEC_245 244
#define UTIL_DEC_246 245
#define UTIL_DEC_247 246
#define UTIL_DEC_248 247
#define UTIL_DEC_249 248
#define UTIL_DEC_250 249
#define UTIL_DEC_251 250
#define UTIL_DEC_252 251
#define UTIL_DEC_253 252
#define UTIL_DEC_254 253
#define UTIL_DEC_255 254
#define UTIL_DEC_256 255
#define UTIL_CHECK_N(x, n, ...) n
#define UTIL_CHECK(...) UTIL_CHECK_N(__VA_ARGS__, 0,)
#define UTIL_NOT(x) UTIL_CHECK(UTIL_PRIMITIVE_CAT(UTIL_NOT_, x))
#define UTIL_NOT_0 ~, 1,
#define UTIL_COMPL(b) UTIL_PRIMITIVE_CAT(UTIL_COMPL_, b)
#define UTIL_COMPL_0 1
#define UTIL_COMPL_1 0
#define UTIL_BOOL(x) UTIL_COMPL(UTIL_NOT(x))
#define UTIL_IIF(c) UTIL_PRIMITIVE_CAT(UTIL_IIF_, c)
#define UTIL_IIF_0(t, ...) __VA_ARGS__
#define UTIL_IIF_1(t, ...) t
#define UTIL_IF(c) UTIL_IIF(UTIL_BOOL(c))
/*
* These are like || and &&, but they do evaluation and
* short-circuiting at preprocessor time instead of runtime.
*
* UTIL_OR(foo, bar) is sometimes a replacement for (foo || bar)
* when "bar" is an expression that would cause a build
* error when "foo" is true.
*
* UTIL_AND(foo, bar) is sometimes a replacement for (foo && bar)
* when "bar" is an expression that would cause a build
* error when "foo" is false.
*/
#define UTIL_OR(a, b) COND_CODE_1(UTIL_BOOL(a), (a), (b))
#define UTIL_AND(a, b) COND_CODE_1(UTIL_BOOL(a), (b), (0))
#define UTIL_EAT(...)
#define UTIL_EXPAND(...) __VA_ARGS__
#define UTIL_WHEN(c) UTIL_IF(c)(UTIL_EXPAND, UTIL_EAT)
#define UTIL_REPEAT(count, macro, ...) \
UTIL_WHEN(count) \
( \
UTIL_OBSTRUCT(UTIL_REPEAT_INDIRECT) () \
( \
UTIL_DEC(count), macro, __VA_ARGS__ \
) \
UTIL_OBSTRUCT(macro) \
( \
UTIL_DEC(count), __VA_ARGS__ \
) \
)
#define UTIL_REPEAT_INDIRECT() UTIL_REPEAT
/**
* @brief Generates a sequence of code.
*
* Useful for generating code like;
*
* NRF_PWM0, NRF_PWM1, NRF_PWM2,
*
* @arg LEN: The length of the sequence. Must be defined and less than
* 20.
*
* @arg F(i, ...): A macro function that accepts at least two arguments.
* F is called repeatedly, the first argument is the index in the sequence,
* the variable list of arguments passed to UTIL_LISTIFY are passed through
* to F.
*
* Example:
*
* \#define FOO(i, _) NRF_PWM ## i ,
* { UTIL_LISTIFY(PWM_COUNT, FOO) }
* The above two lines will generate the below:
* { NRF_PWM0 , NRF_PWM1 , }
*
* @note Calling UTIL_LISTIFY with undefined arguments has undefined
* behavior.
*/
#define UTIL_LISTIFY(LEN, F, ...) UTIL_EVAL(UTIL_REPEAT(LEN, F, __VA_ARGS__))
/* Set of internal macros used for FOR_EACH series of macros. */
#define Z_FOR_EACH_IDX(count, n, macro, semicolon, fixed_arg0, fixed_arg1, ...)\
UTIL_WHEN(count) \
( \
UTIL_OBSTRUCT(macro) \
( \
fixed_arg0, fixed_arg1, n, GET_ARG1(__VA_ARGS__)\
)semicolon \
UTIL_OBSTRUCT(Z_FOR_EACH_IDX_INDIRECT) () \
( \
UTIL_DEC(count), UTIL_INC(n), macro, semicolon, \
fixed_arg0, fixed_arg1, \
GET_ARGS_LESS_1(__VA_ARGS__) \
) \
)
#define Z_FOR_EACH_IDX_INDIRECT() Z_FOR_EACH_IDX
#define Z_FOR_EACH_IDX2(count, iter, macro, sc, fixed_arg0, fixed_arg1, ...) \
UTIL_EVAL(Z_FOR_EACH_IDX(count, iter, macro, sc,\
fixed_arg0, fixed_arg1, __VA_ARGS__))
#define Z_FOR_EACH_SWALLOW_NOTHING(F, fixed_arg, index, arg) \
F(index, arg, fixed_arg)
#define Z_FOR_EACH_SWALLOW_FIXED_ARG(F, fixed_arg, index, arg) F(index, arg)
#define Z_FOR_EACH_SWALLOW_INDEX_FIXED_ARG(F, fixed_arg, index, arg) F(arg)
#define Z_FOR_EACH_SWALLOW_INDEX(F, fixed_arg, index, arg) F(arg, fixed_arg)
/**
* @brief Calls macro F for each provided argument with index as first argument
* and nth parameter as the second argument.
*
* Example:
*
* #define F(idx, x) int a##idx = x;
* FOR_EACH_IDX(F, 4, 5, 6)
*
* will result in following code:
*
* int a0 = 4;
* int a1 = 5;
* int a2 = 6;
*
* @param F Macro takes index and first argument and nth variable argument as
* the second one.
* @param ... Variable list of argument. For each argument macro F is executed.
*/
#define FOR_EACH_IDX(F, ...) \
Z_FOR_EACH_IDX2(NUM_VA_ARGS_LESS_1(__VA_ARGS__, _), \
0, Z_FOR_EACH_SWALLOW_FIXED_ARG, /*no ;*/, \
F, 0, __VA_ARGS__)
/**
* @brief Calls macro F for each provided argument with index as first argument
* and nth parameter as the second argument and fixed argument as the
* third one.
*
* Example:
*
* #define F(idx, x, fixed_arg) int fixed_arg##idx = x;
* FOR_EACH_IDX_FIXED_ARG(F, a, 4, 5, 6)
*
* will result in following code:
*
* int a0 = 4;
* int a1 = 5;
* int a2 = 6;
*
* @param F Macro takes index and first argument and nth variable argument as
* the second one and fixed argumnet as the third.
* @param fixed_arg Fixed argument passed to F macro.
* @param ... Variable list of argument. For each argument macro F is executed.
*/
#define FOR_EACH_IDX_FIXED_ARG(F, fixed_arg, ...) \
Z_FOR_EACH_IDX2(NUM_VA_ARGS_LESS_1(__VA_ARGS__, _), \
0, Z_FOR_EACH_SWALLOW_NOTHING, /*no ;*/, \
F, fixed_arg, __VA_ARGS__)
/**
* @brief Calls macro F for each provided argument.
*
* Example:
*
* #define F(x) int a##x;
* FOR_EACH(F, 4, 5, 6)
*
* will result in following code:
*
* int a4;
* int a5;
* int a6;
*
* @param F Macro takes nth variable argument as the argument.
* @param ... Variable list of argument. For each argument macro F is executed.
*/
#define FOR_EACH(F, ...) \
Z_FOR_EACH_IDX2(NUM_VA_ARGS_LESS_1(__VA_ARGS__, _), \
0, Z_FOR_EACH_SWALLOW_INDEX_FIXED_ARG, /*no ;*/, \
F, 0, __VA_ARGS__)
/**
* @brief Calls macro F for each provided argument with additional fixed
* argument.
*
* After each iteration semicolon is added.
*
* Example:
*
* static void func(int val, void *dev);
* FOR_EACH_FIXED_ARG(func, dev, 4, 5, 6)
*
* will result in following code:
*
* func(4, dev);
* func(5, dev);
* func(6, dev);
*
* @param F Macro takes nth variable argument as the first parameter and
* fixed argument as the second parameter.
* @param fixed_arg Fixed argument forward to macro execution for each argument.
* @param ... Variable list of argument. For each argument macro F is executed.
*/
#define FOR_EACH_FIXED_ARG(F, fixed_arg, ...) \
Z_FOR_EACH_IDX2(NUM_VA_ARGS_LESS_1(__VA_ARGS__, _), \
0, Z_FOR_EACH_SWALLOW_INDEX, ;, \
F, fixed_arg, __VA_ARGS__)
/**@brief Implementation details for NUM_VAR_ARGS */
#define NUM_VA_ARGS_LESS_1_IMPL( \
_ignored, \
_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \
_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \
_31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \
_51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \
_61, _62, N, ...) N
/**
* @brief Macro to get the number of arguments in a call variadic macro call.
* First argument is not counted.
*
* param[in] ... List of arguments
*
* @retval Number of variadic arguments in the argument list
*/
#define NUM_VA_ARGS_LESS_1(...) \
NUM_VA_ARGS_LESS_1_IMPL(__VA_ARGS__, 63, 62, 61, \
60, 59, 58, 57, 56, 55, 54, 53, 52, 51, \
50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \
40, 39, 38, 37, 36, 35, 34, 33, 32, 31, \
30, 29, 28, 27, 26, 25, 24, 23, 22, 21, \
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ~)
/**
* Macro that process all arguments using given macro
*
* @deprecated Use FOR_EACH instead.
*
* @param ... Macro name to be used for argument processing followed by
* arguments to process. Macro should have following
* form: MACRO(argument).
*
* @return All arguments processed by given macro
*/
#define MACRO_MAP(...) __DEPRECATED_MACRO FOR_EACH(__VA_ARGS__)
/**
* @brief Mapping macro that pastes results together
*
* Like @ref MACRO_MAP(), but pastes the results together into a
* single token by repeated application of @ref UTIL_CAT().
*
* For example, with this macro FOO:
*
* #define FOO(x) item_##x##_
*
* MACRO_MAP_CAT(FOO, a, b, c) expands to the token:
*
* item_a_item_b_item_c_
*
* @param ... Macro to expand on each argument, followed by its
* arguments. (The macro should take exactly one argument.)
* @return The results of expanding the macro on each argument, all pasted
* together
*/
#define MACRO_MAP_CAT(...) MACRO_MAP_CAT_(__VA_ARGS__)
#define MACRO_MAP_CAT_(...) \
/* To make sure it works also for 2 arguments in total */ \
MACRO_MAP_CAT_N(NUM_VA_ARGS_LESS_1(__VA_ARGS__), __VA_ARGS__)
/**
* @brief Mapping macro that pastes a fixed number of results together
*
* Similar to @ref MACRO_MAP_CAT(), but expects a fixed number of
* arguments. If more arguments are given than are expected, the rest
* are ignored.
*
* @param N Number of arguments to map
* @param ... Macro to expand on each argument, followed by its
* arguments. (The macro should take exactly one argument.)
* @return The results of expanding the macro on each argument, all pasted
* together
*/
#define MACRO_MAP_CAT_N(N, ...) MACRO_MAP_CAT_N_(N, __VA_ARGS__)
#define MACRO_MAP_CAT_N_(N, ...) UTIL_CAT(MACRO_MC_, N)(__VA_ARGS__,)
#define MACRO_MC_0(...)
#define MACRO_MC_1(m, a, ...) m(a)
#define MACRO_MC_2(m, a, ...) UTIL_CAT(m(a), MACRO_MC_1(m, __VA_ARGS__,))
#define MACRO_MC_3(m, a, ...) UTIL_CAT(m(a), MACRO_MC_2(m, __VA_ARGS__,))
#define MACRO_MC_4(m, a, ...) UTIL_CAT(m(a), MACRO_MC_3(m, __VA_ARGS__,))
#define MACRO_MC_5(m, a, ...) UTIL_CAT(m(a), MACRO_MC_4(m, __VA_ARGS__,))
#define MACRO_MC_6(m, a, ...) UTIL_CAT(m(a), MACRO_MC_5(m, __VA_ARGS__,))
#define MACRO_MC_7(m, a, ...) UTIL_CAT(m(a), MACRO_MC_6(m, __VA_ARGS__,))
#define MACRO_MC_8(m, a, ...) UTIL_CAT(m(a), MACRO_MC_7(m, __VA_ARGS__,))
#define MACRO_MC_9(m, a, ...) UTIL_CAT(m(a), MACRO_MC_8(m, __VA_ARGS__,))
#define MACRO_MC_10(m, a, ...) UTIL_CAT(m(a), MACRO_MC_9(m, __VA_ARGS__,))
#define MACRO_MC_11(m, a, ...) UTIL_CAT(m(a), MACRO_MC_10(m, __VA_ARGS__,))
#define MACRO_MC_12(m, a, ...) UTIL_CAT(m(a), MACRO_MC_11(m, __VA_ARGS__,))
#define MACRO_MC_13(m, a, ...) UTIL_CAT(m(a), MACRO_MC_12(m, __VA_ARGS__,))
#define MACRO_MC_14(m, a, ...) UTIL_CAT(m(a), MACRO_MC_13(m, __VA_ARGS__,))
#define MACRO_MC_15(m, a, ...) UTIL_CAT(m(a), MACRO_MC_14(m, __VA_ARGS__,))
#ifdef __cplusplus
}
#endif
#endif /* _UTIL__H_ */
| YifuLiu/AliOS-Things | components/ble_host/bt_host/port/include/misc/util.h | C | apache-2.0 | 34,607 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef KPORT_H
#define KPORT_H
#define _POLL_EVENT_OBJ_INIT(obj) \
.poll_events = SYS_DLIST_STATIC_INIT(&obj.poll_events),
#define _POLL_EVENT sys_dlist_t poll_events
#define _K_SEM_INITIALIZER(obj, initial_count, count_limit) \
{}
#define K_SEM_INITIALIZER DEPRECATED_MACRO _K_SEM_INITIALIZER
#define K_SEM_DEFINE(name, initial_count, count_limit) \
struct k_sem name __in_section(_k_sem, static, name) = \
_K_SEM_INITIALIZER(name, initial_count, count_limit)
#define _K_MUTEX_INITIALIZER(obj) \
{ \
0 \
}
#define K_MUTEX_INITIALIZER DEPRECATED_MACRO _K_MUTEX_INITIALIZER
#define K_MUTEX_DEFINE(name) \
struct k_mutex name __in_section(_k_mutex, static, name) = \
_K_MUTEX_INITIALIZER(name)
#ifndef UINT_MAX
#define UINT_MAX (~0U)
#endif
#ifdef CONFIG_OBJECT_TRACING
#define _OBJECT_TRACING_NEXT_PTR(type) struct type *__next
#define _OBJECT_TRACING_INIT .__next = NULL,
#else
#define _OBJECT_TRACING_INIT
#define _OBJECT_TRACING_NEXT_PTR(type)
#endif
typedef int ssize_t;
typedef sys_dlist_t _wait_q_t;
/*attention: this is intialied as zero,the queue variable shoule use
* k_queue_init\k_lifo_init\k_fifo_init again*/
#define _K_QUEUE_INITIALIZER(obj) \
{ \
{ \
{ \
{ \
0 \
} \
} \
} \
}
#define K_QUEUE_INITIALIZER DEPRECATED_MACRO _K_QUEUE_INITIALIZER
#define Z_WORK_INITIALIZER(work_handler) \
{ \
._reserved = NULL, \
.handler = work_handler, \
.flags = { 0 } \
}
#define _K_LIFO_INITIALIZER(obj) \
{ \
._queue = _K_QUEUE_INITIALIZER(obj._queue) \
}
#define K_LIFO_INITIALIZER DEPRECATED_MACRO _K_LIFO_INITIALIZER
#define K_LIFO_DEFINE(name) \
struct k_lifo name __in_section(_k_queue, static, name) = \
_K_LIFO_INITIALIZER(name)
#define _K_FIFO_INITIALIZER(obj) \
{ \
._queue = _K_QUEUE_INITIALIZER(obj._queue) \
}
#define K_FIFO_INITIALIZER DEPRECATED_MACRO _K_FIFO_INITIALIZER
#define K_FIFO_DEFINE(name) \
struct kfifo name __in_section(_k_queue, static, name) = \
_K_FIFO_INITIALIZER(name)
struct k_thread {
_task_t task;
};
typedef _stack_element_t k_thread_stack_t;
#define K_THREAD_STACK_DEFINE(sym, size) _stack_element_t sym[size]
#define K_THREAD_STACK_SIZEOF(sym) (sizeof(sym) / sizeof(_stack_element_t))
typedef void (*k_thread_entry_t)(void *arg);
/**
* @brief Spawn a thread.
*
* This routine initializes a thread, then schedules it for execution.
*
* @param thread Thread data
* @param name Thread name
* @param stack Pointer to the stack space.
* @param stack_size Stack size in bytes.
* @param fn Thread entry function.
* @param arg entry point parameter.
* @param prio Thread priority.
*
* @return 0 success.
*/
int k_thread_spawn(struct k_thread *thread, const char *name, uint32_t *stack, uint32_t stack_size, \
k_thread_entry_t fn, void *arg, int prio);
/**
* @brief Yield the current thread.
*
* This routine causes the current thread to yield execution to another
* thread of the same or higher priority. If there are no other ready threads
* of the same or higher priority, the routine returns immediately.
*
* @return N/A
*/
int k_yield();
/**
* @brief Lock interrupts.
*
* This routine disables all interrupts on the CPU. It returns an unsigned
* integer "lock-out key", which is an architecture-dependent indicator of
* whether interrupts were locked prior to the call. The lock-out key must be
* passed to irq_unlock() to re-enable interrupts.
*
* @return Lock-out key.
*/
unsigned int irq_lock();
/**
* @brief Unlock interrupts.
*
* This routine reverses the effect of a previous call to irq_lock() using
* the associated lock-out key. The caller must call the routine once for
* each time it called irq_lock(), supplying the keys in the reverse order
* they were acquired, before interrupts are enabled.
*
* @param key Lock-out key generated by irq_lock().
*
* @return N/A
*/
void irq_unlock(unsigned int key);
#ifndef BIT
#define BIT(n) (1UL << (n))
#endif
#ifndef CONFIG_NET_BUF_WARN_ALLOC_INTERVAL
#define CONFIG_NET_BUF_WARN_ALLOC_INTERVAL 1
#endif
#ifndef CONFIG_HEAP_MEM_POOL_SIZE
#define CONFIG_HEAP_MEM_POOL_SIZE 1
#endif
#define SYS_TRACING_OBJ_INIT(name, obj) \
do { \
} while ((0))
static inline int k_is_in_isr()
{
//uint32_t vec = (__get_PSR() & PSR_VEC_Msk) >> PSR_VEC_Pos;
return 0;
}
#endif /* KPORT_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_host/port/include/port/kport.h | C | apache-2.0 | 5,040 |
/*
* Copyright (C) 2016 YunOS Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MBOX_H
#define MBOX_H
#if defined(__cplusplus)
extern "C"
{
#endif
#define K_MBOX_SIZE 128
#define SYS_ARCH_TIMEOUT 0xffffffffUL
#define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT
typedef struct k_mbox {
int first, last;
void *msgs[K_MBOX_SIZE];
struct k_sem not_empty;
struct k_sem not_full;
struct k_sem mutex;
int wait_send;
} k_mbox_t;
int k_mbox_new(k_mbox_t **mb, int size);
void k_mbox_free(k_mbox_t *mb);
void k_mbox_post(k_mbox_t *mb, void *msg);
int k_mbox_trypost(k_mbox_t *mb, void *msg);
int k_mbox_fetch(k_mbox_t *mb, void **msg, uint32_t timeout);
int k_mbox_tryfetch(k_mbox_t *mb, void **msg);
#ifdef __cplusplus
}
#endif
#endif /* MBOX_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_host/port/include/port/mbox.h | C | apache-2.0 | 1,309 |
/*
* Copyright (C) 2016 YunOS Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TIMER_H
#define TIMER_H
#if defined(__cplusplus)
extern "C"
{
#endif
typedef void (* timeout_handler)(void *arg);
struct mtimer {
struct mtimer *next;
uint32_t time;
timeout_handler h;
void *arg;
};
struct mtimer *mtimer_start(uint32_t msecs, timeout_handler handler, void *arg);
void mtimer_stop(struct mtimer *t);
void mtimer_mbox_fetch(k_mbox_t *mbox, void **msg);
#ifdef __cplusplus
}
#endif
#endif /* TIMER_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_host/port/include/port/timer.h | C | apache-2.0 | 1,072 |
zephyr_library()
zephyr_library_sources(
bt.c
)
zephyr_library_sources_ifdef(
CONFIG_BT_CONN
gatt.c
)
zephyr_library_sources_ifdef(
CONFIG_BT_CTLR
ll.c
ticker.c
)
zephyr_library_sources_ifdef(
CONFIG_SOC_FLASH_NRF
flash.c
)
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/CMakeLists.txt | CMake | apache-2.0 | 248 |
/** @file
* @brief Bluetooth shell module
*
* Provide some Bluetooth shell commands that can be useful to applications.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <bt_errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <aos/ble.h>
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#include <misc/byteorder.h>
#include <ble_os.h>
#include <ble_types/types.h>
#include <settings/settings.h>
//#include <yoc/partition.h>
#include <bluetooth/hci.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/sdp.h>
#include <common/log.h>
#include <host/conn_internal.h>
/** @brief Callback called when command is entered.
*
* @param argc Number of parameters passed.
* @param argv Array of option strings. First option is always command name.
*
* @return 0 in case of success or negative value in case of error.
*/
typedef int (*shell_cmd_function_t)(int argc, char *argv[]);
// typedef int partition_t;
// static partition_t handle = -1;
// static hal_logic_partition_t *lp;
struct shell_cmd {
const char *cmd_name;
shell_cmd_function_t cb;
const char *help;
const char *desc;
};
#include "bt.h"
#include "gatt.h"
#include "ll.h"
#define DEVICE_NAME CONFIG_BT_DEVICE_NAME
#define DEVICE_NAME_LEN (sizeof(DEVICE_NAME) - 1)
#define CREDITS 15
#define DATA_MTU (23 * CREDITS)
#define DATA_BREDR_MTU 48
static u8_t selected_id = BT_ID_DEFAULT;
#if defined(CONFIG_BT_CONN)
struct bt_conn *default_conn;
int16_t g_bt_conn_handle = -1;
int16_t g_security_level = 0;
uint8_t ble_init_flag = 0;
typedef struct {
dev_addr_t addr;
uint8_t set_flag;
} wl_addr;
#define MAX_WL_SZIE 10
wl_addr wl_list[MAX_WL_SZIE]= {0};
/* Connection context for BR/EDR legacy pairing in sec mode 3 */
static int16_t g_pairing_handle = -1;
#endif /* CONFIG_BT_CONN */
static void device_find(ble_event_en event, void *event_data);
#if defined(CONFIG_BT_SMP)
static void smp_event(ble_event_en event, void *event_data);
#endif
static void conn_param_req(ble_event_en event, void *event_data);
static void conn_param_update(ble_event_en event, void *event_data);
#define L2CAP_DYM_CHANNEL_NUM 2
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
NET_BUF_POOL_DEFINE(data_tx_pool, L2CAP_DYM_CHANNEL_NUM, DATA_MTU, BT_BUF_USER_DATA_MIN, NULL);
NET_BUF_POOL_DEFINE(data_rx_pool, L2CAP_DYM_CHANNEL_NUM, DATA_MTU, BT_BUF_USER_DATA_MIN, NULL);
#endif
#if defined(CONFIG_BT_BREDR)
NET_BUF_POOL_DEFINE(data_bredr_pool, 1, DATA_BREDR_MTU, BT_BUF_USER_DATA_MIN,
NULL);
#define SDP_CLIENT_USER_BUF_LEN 512
NET_BUF_POOL_DEFINE(sdp_client_pool, CONFIG_BT_MAX_CONN,
SDP_CLIENT_USER_BUF_LEN, BT_BUF_USER_DATA_MIN, NULL);
#endif /* CONFIG_BT_BREDR */
#if defined(CONFIG_BT_RFCOMM)
static struct bt_sdp_attribute spp_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_SERIAL_PORT_SVCLASS)
},
)
),
BT_SDP_LIST(
BT_SDP_ATTR_PROTO_DESC_LIST,
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP)
},
)
},
{
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM)
},
{
BT_SDP_TYPE_SIZE(BT_SDP_UINT8),
BT_SDP_ARRAY_8(BT_RFCOMM_CHAN_SPP)
},
)
},
)
),
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_SERIAL_PORT_SVCLASS)
},
{
BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
BT_SDP_ARRAY_16(0x0102)
},
)
},
)
),
BT_SDP_SERVICE_NAME("Serial Port"),
};
static struct bt_sdp_record spp_rec = BT_SDP_RECORD(spp_attrs);
#endif /* CONFIG_BT_RFCOMM */
#define NAME_LEN 30
static char *addr_le_str(const bt_addr_le_t *addr)
{
static char bufs[2][27];
static u8_t cur;
char *str;
str = bufs[cur++];
cur %= ARRAY_SIZE(bufs);
bt_addr_le_to_str(addr, str, sizeof(bufs[cur]));
return str;
}
static uint8_t char2u8(char c)
{
if (c >= '0' && c <= '9') {
return (c - '0');
} else if (c >= 'a' && c <= 'f') {
return (c - 'a' + 10);
} else if (c >= 'A' && c <= 'F') {
return (c - 'A' + 10);
} else {
return 0;
}
}
void str2hex(uint8_t hex[], char *s, uint8_t cnt)
{
uint8_t i;
if (!s) {
return;
}
for (i = 0; (*s != '\0') && (i < cnt); i++, s += 2) {
hex[i] = ((char2u8(*s) & 0x0f) << 4) | ((char2u8(*(s + 1))) & 0x0f);
}
}
static inline int bt_addr2str(const dev_addr_t *addr, char *str,
uint16_t len)
{
char type[10];
switch (addr->type) {
case BT_ADDR_LE_PUBLIC:
strcpy(type, "public");
break;
case BT_ADDR_LE_RANDOM:
strcpy(type, "random");
break;
default:
snprintf(type, sizeof(type), "0x%02x", addr->type);
break;
}
return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)",
addr->val[5], addr->val[4], addr->val[3],
addr->val[2], addr->val[1], addr->val[0], type);
}
#if 0
static int char2hex(const char *c, u8_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 -EINVAL;
}
return 0;
}
#endif
static int str2bt_addr(const char *str, dev_addr_t *addr)
{
int i, j;
u8_t tmp;
if (strlen(str) != 17) {
return -EINVAL;
}
for (i = 5, j = 1; *str != '\0'; str++, j++) {
if (!(j % 3) && (*str != ':')) {
return -EINVAL;
} else if (*str == ':') {
i--;
continue;
}
addr->val[i] = addr->val[i] << 4;
if (char2hex(*str, &tmp) < 0) {
return -EINVAL;
}
addr->val[i] |= tmp;
}
return 0;
}
static int str2bt_addr_le(const char *str, const char *type, dev_addr_t *addr)
{
int err;
err = str2bt_addr(str, addr);
if (err < 0) {
return err;
}
if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
addr->type = DEV_ADDR_LE_PUBLIC;
} else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
addr->type = DEV_ADDR_LE_RANDOM;
} else {
return -EINVAL;
}
return 0;
}
static void conn_change(ble_event_en event, void *event_data)
{
evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data;
connect_info_t info;
ble_stack_connect_info_get(e->conn_handle, &info);
if (e->connected == CONNECTED && e->err == 0) {
printf("Connected (%d): %s\n", e->conn_handle, addr_le_str((bt_addr_le_t *)&info.peer_addr));
if (g_bt_conn_handle == -1) {
g_bt_conn_handle = e->conn_handle;
}
/* clear connection reference for sec mode 3 pairing */
if (g_pairing_handle != -1) {
g_pairing_handle = -1;
}
} else {
printf("Disconected (%d): %s err %d\n", e->conn_handle, addr_le_str((bt_addr_le_t *)&info.peer_addr), e->err);
if (e->err == 31) {
while (1);
}
if (g_bt_conn_handle == e->conn_handle) {
g_bt_conn_handle = -1;
}
g_security_level = 0;
}
}
static void conn_security_change(ble_event_en event, void *event_data)
{
evt_data_gap_security_change_t *e = (evt_data_gap_security_change_t *)event_data;
printf("conn %d security level change to level%d\n", e->conn_handle, e->level);
g_security_level = e->level;
}
static int event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GAP_CONN_CHANGE:
conn_change(event, event_data);
break;
case EVENT_GAP_CONN_SECURITY_CHANGE:
conn_security_change(event, event_data);
break;
case EVENT_GAP_DEV_FIND:
device_find(event, event_data);
break;
case EVENT_GAP_CONN_PARAM_REQ:
conn_param_req(event, event_data);
break;
case EVENT_GAP_CONN_PARAM_UPDATE:
conn_param_update(event, event_data);
break;
#if defined(CONFIG_BT_SMP)
case EVENT_SMP_PASSKEY_DISPLAY:
case EVENT_SMP_PASSKEY_CONFIRM:
case EVENT_SMP_PASSKEY_ENTER:
case EVENT_SMP_PAIRING_CONFIRM:
case EVENT_SMP_PAIRING_COMPLETE:
case EVENT_SMP_CANCEL:
smp_event(event, event_data);
break;
#endif
default:
//printf("Unhandle event %d\n", event);
break;
}
return 0;
}
static ble_event_cb_t ble_cb = {
.callback = event_callback,
};
static int cmd_init(int argc, char *argv[])
{
int err;
dev_addr_t addr;
init_param_t init = {NULL, NULL, 1};
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
NET_BUF_POOL_INIT(data_tx_pool);
NET_BUF_POOL_INIT(data_rx_pool);
#endif
#if defined(CONFIG_BT_BREDR)
NET_BUF_POOL_INIT(data_bredr_pool);
NET_BUF_POOL_INIT(sdp_client_pool);
#endif /* CONFIG_BT_BREDR */
if (argc == 3) {
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid address\n");
return err;
}
init.dev_addr = &addr;
}
err = ble_stack_init(&init);
if (err) {
printf("Bluetooth init failed (err %d)\n", err);
return err;
}
err = ble_stack_event_register(&ble_cb);
if(err) {
printf("Bluetooth stack init fail\n");
return -1;
} else {
printf("Bluetooth stack init success\n");
}
ble_init_flag = 1;
return 0;
}
#if defined(CONFIG_BT_HCI) || defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
void hexdump(const u8_t *data, size_t len)
{
int n = 0;
while (len--) {
if (n % 16 == 0) {
printf("%08X ", n);
}
printf("%02X ", *data++);
n++;
if (n % 8 == 0) {
if (n % 16 == 0) {
printf("\n");
} else {
printf(" ");
}
}
}
if (n % 16) {
printf("\n");
}
}
#endif /* CONFIG_BT_HCI || CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
#if defined(CONFIG_BT_HCI)
static int cmd_hci_cmd(int argc, char *argv[])
{
u8_t ogf;
u16_t ocf;
struct net_buf *buf = NULL, *rsp;
int err;
if (argc < 3) {
return -EINVAL;
}
ogf = strtoul(argv[1], NULL, 16);
ocf = strtoul(argv[2], NULL, 16);
if (argc > 3) {
int i;
buf = bt_hci_cmd_create(BT_OP(ogf, ocf), argc - 3);
for (i = 3; i < argc; i++) {
net_buf_add_u8(buf, strtoul(argv[i], NULL, 16));
}
}
err = bt_hci_cmd_send_sync(BT_OP(ogf, ocf), buf, &rsp);
if (err) {
printf("HCI command failed (err %d)\n", err);
} else {
hexdump(rsp->data, rsp->len);
net_buf_unref(rsp);
}
return 0;
}
#endif /* CONFIG_BT_HCI */
static int cmd_name(int argc, char *argv[])
{
int err;
if (argc < 2) {
printf("Bluetooth Local Name: %s\n", bt_get_name());
return 0;
}
err = bt_set_name(argv[1]);
if (err) {
printf("Unable to set name %s (err %d)", argv[1], err);
}
return 0;
}
static int cmd_id_create(int argc, char *argv[])
{
dev_addr_t addr;
int err;
if (argc > 1) {
err = str2bt_addr_le(argv[1], "random", &addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
bt_addr_le_copy((bt_addr_le_t *)&addr, BT_ADDR_LE_ANY);
}
err = bt_id_create((bt_addr_le_t *)&addr, NULL);
if (err < 0) {
printf("Creating new ID failed (err %d)\n", err);
return 0;
}
printf("New identity (%d) created: %s\n", err, addr_le_str((bt_addr_le_t *)&addr));
return 0;
}
static int cmd_id_reset(int argc, char *argv[])
{
bt_addr_le_t addr;
u8_t id;
int err;
if (argc < 2) {
printf("Identity identifier not specified\n");
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
if (argc > 2) {
err = str2bt_addr_le(argv[2], "random", (dev_addr_t *)&addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
bt_addr_le_copy(&addr, BT_ADDR_LE_ANY);
}
err = bt_id_reset(id, &addr, NULL);
if (err < 0) {
printf("Resetting ID %u failed (err %d)\n", id, err);
return 0;
}
printf("Identity %u reset: %s\n", id, addr_le_str(&addr));
return 0;
}
static int cmd_id_delete(int argc, char *argv[])
{
u8_t id;
int err;
if (argc < 2) {
printf("Identity identifier not specified\n");
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
err = bt_id_delete(id);
if (err < 0) {
printf("Deleting ID %u failed (err %d)\n", id, err);
return 0;
}
printf("Identity %u deleted\n", id);
return 0;
}
static int cmd_id_show(int argc, char *argv[])
{
bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
size_t i, count = CONFIG_BT_ID_MAX;
bt_id_get(addrs, &count);
for (i = 0; i < count; i++) {
printf("%s%zu: %s\n", i == selected_id ? "*" : " ", i,
addr_le_str(&addrs[i]));
}
return 0;
}
static int cmd_id_select(int argc, char *argv[])
{
bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
size_t count = CONFIG_BT_ID_MAX;
u8_t id;
if (argc < 2) {
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
bt_id_get(addrs, &count);
if (count <= id) {
printf("Invalid identity\n");
return 0;
}
//printf("Selected identity: %s\n", addr_le_str(&addrs[id]));
selected_id = id;
return 0;
}
static inline int parse_ad(uint8_t *data, uint16_t len, int (* cb)(ad_data_t *data, void *arg), void *cb_arg)
{
int num = 0;
uint8_t *pdata = data;
ad_data_t ad = {0};
int ret;
while (len) {
if (pdata[0] == 0) {
return num;
}
if (len < pdata[0] + 1) {
return -1;
};
ad.len = pdata[0] - 1;
ad.type = pdata[1];
ad.data = &pdata[2];
if (cb) {
ret = cb(&ad, cb_arg);
if (ret) {
break;
}
}
num++;
len -= (pdata[0] + 1);
pdata += (pdata[0] + 1);
}
return num;
}
uint8_t *pscan_ad = NULL;
uint8_t *pscan_sd = NULL;
static int scan_ad_cmp(ad_data_t *ad, void *arg)
{
ad_data_t *ad2 = arg;
return (ad->type == ad2->type && ad->len == ad2->len
&& 0 == memcmp(ad->data, ad2->data, ad->len));
}
static int scan_ad_callback(ad_data_t *ad, void *arg)
{
evt_data_gap_dev_find_t *e = arg;
int ad_num;
uint8_t *pad = NULL;
int ret;
if (e->adv_len) {
if (e->adv_type == 0x04) {
pad = pscan_sd;
} else {
pad = pscan_ad;
}
ad_num = parse_ad(pad, 31, NULL, NULL);
ret = parse_ad(pad, 31, scan_ad_cmp, (void *)ad);
if (ret < ad_num) {
return 1;
}
}
return 0;
}
static void device_find(ble_event_en event, void *event_data)
{
evt_data_gap_dev_find_t *e = event_data;
int ad_num = parse_ad(e->adv_data, e->adv_len, NULL, NULL);
int ret;
char addr_str[32] = {0};
bt_addr2str(&e->dev_addr, addr_str, sizeof(addr_str));
if (pscan_ad || pscan_sd) {
ret = parse_ad(e->adv_data, e->adv_len, scan_ad_callback, event_data);
if (ret < ad_num) {
printf("[DEVICE]: %s, adv type %d, rssi %d, Raw data:%s\n", addr_str, e->adv_type, e->rssi, bt_hex(e->adv_data, e->adv_len));
}
} else {
printf("[DEVICE]: %s, adv type %d, rssi %d, Raw data:%s\n", addr_str, e->adv_type, e->rssi, bt_hex(e->adv_data, e->adv_len));
}
}
static void conn_param_req(ble_event_en event, void *event_data)
{
evt_data_gap_conn_param_req_t *e = event_data;
printf("LE conn param req: int (0x%04x, 0x%04x) lat %d to %d\n",
e->param.interval_min, e->param.interval_max, e->param.latency,
e->param.timeout);
e->accept = 1;
}
static void conn_param_update(ble_event_en event, void *event_data)
{
evt_data_gap_conn_param_update_t *e = event_data;
printf("LE conn param updated: int 0x%04x lat %d to %d\n", e->interval,
e->latency, e->timeout);
}
static uint8_t scan_filter = 0;
static int cmd_scan_filter(int argc, char *argv[])
{
if (argc < 2) {
return -EINVAL;
}
scan_filter = atoi(argv[1]);
if (scan_filter > SCAN_FILTER_POLICY_WHITE_LIST) {
scan_filter = 0;
return -EINVAL;
}
printf("Set scan filter %s\n", scan_filter == 0 ? "SCAN_FILTER_POLICY_ANY_ADV" : "SCAN_FILTER_POLICY_WHITE_LIST");
return 0;
}
static int cmd_scan(int argc, char *argv[])
{
static uint8_t scan_ad[31] = {0};
static uint8_t scan_sd[31] = {0};
scan_param_t params = {
SCAN_PASSIVE,
SCAN_FILTER_DUP_DISABLE,
SCAN_FAST_INTERVAL,
SCAN_FAST_WINDOW,
};
params.scan_filter = scan_filter;
if (argc < 2) {
return -EINVAL;
}
if (argc >= 2) {
if (!strcmp(argv[1], "active")) {
params.type = SCAN_ACTIVE;
} else if (!strcmp(argv[1], "off")) {
pscan_ad = NULL;
pscan_sd = NULL;
return ble_stack_scan_stop();
} else if (!strcmp(argv[1], "passive")) {
params.type = SCAN_PASSIVE;
} else {
return -EINVAL;
}
}
if (argc >= 3) {
if (!strcmp(argv[2], "dups")) {
params.filter_dup = SCAN_FILTER_DUP_DISABLE;
} else if (!strcmp(argv[2], "nodups")) {
params.filter_dup = SCAN_FILTER_DUP_ENABLE;
} else {
return -EINVAL;
}
}
if (argc >= 4) {
params.interval = strtol(argv[3], NULL, 10);
}
if (argc >= 5) {
params.window = strtol(argv[4], NULL, 10);
}
if (argc >= 6) {
pscan_ad = scan_ad;
memset(scan_ad, 0, sizeof(scan_ad));
str2hex(scan_ad, argv[5], sizeof(scan_ad));
}
if (argc >= 7) {
pscan_sd = scan_sd;
memset(scan_sd, 0, sizeof(scan_sd));
str2hex(scan_sd, argv[6], sizeof(scan_sd));
}
return ble_stack_scan_start(¶ms);
}
static inline int parse_ad_data(uint8_t *data, uint16_t len, ad_data_t *ad, uint8_t *ad_num)
{
uint8_t num = 0;
uint8_t *pdata = data;
while (len) {
if (len < pdata[0] + 1) {
*ad_num = 0;
return -1;
};
num++;
if (ad && num <= *ad_num) {
ad->len = pdata[0] - 1;
ad->type = pdata[1];
ad->data = &pdata[2];
}
len -= (pdata[0] + 1);
pdata += (pdata[0] + 1);
if (ad) {
ad++;
}
}
*ad_num = num;
return 0;
}
static inline int adv_ad_callback(ad_data_t *ad, void *arg)
{
ad_data_t **pad = (ad_data_t **)arg;
(*pad)->type = ad->type;
(*pad)->len = ad->len;
(*pad)->data = ad->data;
(*pad)++;
return 0;
}
static int cmd_advertise(int argc, char *argv[])
{
int err;
adv_param_t param = {0};
uint8_t ad_hex[31] = {0};
uint8_t sd_hex[31] = {0};
ad_data_t ad[10] = {0};
int8_t ad_num = 0;
ad_data_t sd[10] = {0};
int8_t sd_num = 0;
if (argc < 2) {
goto fail;
}
if (!strcmp(argv[1], "stop")) {
if (bt_le_adv_stop() < 0) {
printf("Failed to stop advertising\n");
} else {
printf("Advertising stopped\n");
}
return 0;
}
if (!strcmp(argv[1], "nconn")) {
param.type = ADV_NONCONN_IND;
} else if (!strcmp(argv[1], "conn")) {
param.type = ADV_IND;
}
if (argc > 2) {
if (strlen(argv[2]) > 62) {
printf("max len\n");
goto fail;
}
str2hex(ad_hex, argv[2], sizeof(ad_hex));
ad_data_t *pad = ad;
ad_num = parse_ad(ad_hex, strlen(argv[2]) / 2, adv_ad_callback, (void *)&pad);
}
if (argc > 3) {
if (strlen(argv[3]) > 62) {
printf("max len\n");
goto fail;
}
str2hex(sd_hex, argv[3], sizeof(sd_hex));
ad_data_t *psd = sd;
sd_num = parse_ad(sd_hex, strlen(argv[3]) / 2, adv_ad_callback, (void *)&psd);
}
param.ad = ad_num > 0 ?ad:NULL;
param.sd = sd_num> 0 ?sd:NULL;
param.ad_num = (uint8_t)ad_num;
param.sd_num = (uint8_t)sd_num;
param.interval_min = ADV_FAST_INT_MIN_2;
param.interval_max = ADV_FAST_INT_MAX_2;
err = ble_stack_adv_start(¶m);
if (err < 0) {
printf("Failed to start advertising (err %d)\n", err);
} else {
printf("adv_type:%x;adv_interval_min:%d (*0.625)ms;adv_interval_max:%d (*0.625)ms\n", param.type, (int)param.interval_min, (int)param.interval_max);
printf("Advertising started\n");
}
return 0;
fail:
return -EINVAL;
}
#if defined(CONFIG_BT_CONN)
static int cmd_connect_le(int argc, char *argv[])
{
int err;
dev_addr_t addr;
int16_t conn_handle;
conn_param_t param = {
CONN_INT_MIN_INTERVAL,
CONN_INT_MAX_INTERVAL,
0,
400,
};
if (argc < 3) {
return -EINVAL;
}
if (argc >= 3) {
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid peer address (err %d)\n", err);
return 0;
}
}
if (argc >= 5) {
param.interval_min = strtol(argv[3], NULL, 16);
param.interval_max = strtol(argv[4], NULL, 16);
}
if (argc >= 7) {
param.latency = strtol(argv[5], NULL, 16);
param.timeout = strtol(argv[6], NULL, 16);
}
conn_handle = ble_stack_connect(&addr, ¶m, 0);
if (conn_handle < 0) {
printf("Connection failed\n");
return -EIO;
}
return 0;
}
static int cmd_disconnect(int argc, char *argv[])
{
int16_t conn_handle = 0;
int err;
if (g_bt_conn_handle != -1 && argc < 2) {
conn_handle = g_bt_conn_handle;
} else {
if (argc < 2) {
return -EINVAL;
}
conn_handle = strtol(argv[1], NULL, 10);
}
err = ble_stack_disconnect(conn_handle);
if (err) {
printf("Disconnection failed (err %d)\n", err);
}
return 0;
}
static int cmd_auto_conn(int argc, char *argv[])
{
dev_addr_t addr;
conn_param_t param = {
CONN_INT_MIN_INTERVAL,
CONN_INT_MAX_INTERVAL,
0,
400,
};
int err;
conn_param_t *pparam = NULL;
uint8_t auto_conn = 1;
if (argc < 3) {
return -EINVAL;
}
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid peer address (err %d)\n", err);
return -EINVAL;
}
if (argc > 3) {
if (!strcmp(argv[3], "on")) {
auto_conn = 1;
pparam = ¶m;
} else if (!strcmp(argv[3], "off")) {
auto_conn = 0;
pparam = NULL;
} else {
return -EINVAL;
}
} else {
auto_conn = 1;
pparam = ¶m;
}
err = ble_stack_connect(&addr, pparam, auto_conn);
if (err < 0) {
return err;
}
printf("connect (%d) pending\n", err);
return 0;
}
static int cmd_select(int argc, char *argv[])
{
struct bt_conn *conn;
bt_addr_le_t addr;
int err;
if (argc < 3) {
return -EINVAL;
}
err = str2bt_addr_le(argv[1], argv[2], (dev_addr_t *)&addr);
if (err) {
printf("Invalid peer address (err %d)\n", err);
return 0;
}
conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, &addr);
if (!conn) {
printf("No matching connection found\n");
return 0;
}
if (default_conn) {
bt_conn_unref(default_conn);
}
default_conn = conn;
return 0;
}
static int cmd_conn_update(int argc, char *argv[])
{
conn_param_t param;
int err;
if (argc < 5) {
return -EINVAL;
}
param.interval_min = strtoul(argv[1], NULL, 16);
param.interval_max = strtoul(argv[2], NULL, 16);
param.latency = strtoul(argv[3], NULL, 16);
param.timeout = strtoul(argv[4], NULL, 16);
err = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
if (err) {
printf("conn update failed (err %d).\n", err);
} else {
printf("conn update initiated.\n");
}
return 0;
}
static int cmd_oob(int argc, char *argv[])
{
char addr[BT_ADDR_LE_STR_LEN];
struct bt_le_oob oob;
int err;
err = bt_le_oob_get_local(selected_id, &oob);
if (err) {
printf("OOB data failed\n");
return 0;
}
bt_addr_le_to_str(&oob.addr, addr, sizeof(addr));
printf("OOB data:\n");
printf(" addr %s\n", addr);
return 0;
}
static int cmd_clear(int argc, char *argv[])
{
dev_addr_t addr;
int err;
if (argc < 2) {
printf("Specify remote address or \"all\"\n");
return 0;
}
if (strcmp(argv[1], "all") == 0) {
// err = bt_unpair(selected_id, NULL);
err = ble_stack_dev_unpair(NULL);
if (err) {
printf("Failed to clear pairings (err %d)\n", err);
} else {
printf("Pairings successfully cleared\n");
}
return 0;
}
if (argc < 3) {
#if defined(CONFIG_BT_BREDR)
addr.type = BT_ADDR_LE_PUBLIC;
err = str2bt_addr(argv[1], &addr.a);
#else
printf("Both address and address type needed\n");
return 0;
#endif
} else {
err = str2bt_addr_le(argv[1], argv[2], (dev_addr_t *)&addr);
}
if (err) {
printf("Invalid address\n");
return 0;
}
//err = bt_unpair(selected_id, &addr);
err = ble_stack_dev_unpair(&addr);
if (err) {
printf("Failed to clear pairing (err %d)\n", err);
} else {
printf("Pairing successfully cleared\n");
}
return 0;
}
#endif /* CONFIG_BT_CONN */
#if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
static int cmd_security(int argc, char *argv[])
{
int err, sec;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
sec = *argv[1] - '0';
err = ble_stack_security(g_bt_conn_handle, sec);
if (err) {
printf("Setting security failed (err %d)\n", err);
}
return 0;
}
static void smp_passkey_display(evt_data_smp_passkey_display_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Passkey for %s: %s\n", addr, e->passkey);
}
static void smp_passkey_confirm(evt_data_smp_passkey_confirm_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Pairing passkey for %s: %s\n", addr, e->passkey);
}
static void smp_passkey_entry(evt_data_smp_passkey_enter_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Enter passkey for %s\n", addr);
}
static void smp_cancel(evt_data_smp_cancel_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Pairing cancelled: %s\n", addr);
/* clear connection reference for sec mode 3 pairing */
if (g_pairing_handle) {
g_pairing_handle = -1;
}
}
static void smp_pairing_confirm(evt_data_smp_pairing_confirm_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Confirm pairing for %s\n", addr);
}
static void smp_pairing_complete(evt_data_smp_pairing_complete_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
if (e->err) {
printf("Pairing failed with %s, err %d\n", addr, e->err);
} else {
printf("%s with %s\n", e->bonded ? "Bonded" : "Paired", addr);
}
}
static void smp_event(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_SMP_PASSKEY_DISPLAY:
smp_passkey_display(event_data);
break;
case EVENT_SMP_PASSKEY_CONFIRM:
smp_passkey_confirm(event_data);
break;
case EVENT_SMP_PASSKEY_ENTER:
smp_passkey_entry(event_data);
break;
case EVENT_SMP_PAIRING_CONFIRM:
smp_pairing_confirm(event_data);
break;
case EVENT_SMP_PAIRING_COMPLETE:
smp_pairing_complete(event_data);
break;
case EVENT_SMP_CANCEL:
smp_cancel(event_data);
break;
default:
break;
}
}
static int cmd_iocap_set(int argc, char *argv[])
{
uint8_t io_cap = 0;
if (argc < 3) {
return -EINVAL;
}
if (!strcmp(argv[1], "NONE")) {
io_cap |= IO_CAP_IN_NONE;
} else if (!strcmp(argv[1], "YESNO")) {
io_cap |= IO_CAP_IN_YESNO;
} else if (!strcmp(argv[1], "KEYBOARD")) {
io_cap |= IO_CAP_IN_KEYBOARD;
} else {
return -EINVAL;
}
if (!strcmp(argv[2], "NONE")) {
io_cap |= IO_CAP_OUT_NONE;
} else if (!strcmp(argv[2], "DISPLAY")) {
io_cap |= IO_CAP_OUT_DISPLAY;
} else {
return -EINVAL;
}
return ble_stack_iocapability_set(io_cap);
}
static int cmd_auth_cancel(int argc, char *argv[])
{
int16_t conn_handle;
if (g_bt_conn_handle != -1) {
conn_handle = g_bt_conn_handle;
} else if (g_pairing_handle != -1) {
conn_handle = g_pairing_handle;
} else {
conn_handle = 0;
}
ble_stack_smp_cancel(conn_handle);
return 0;
}
static int cmd_auth_passkey_confirm(int argc, char *argv[])
{
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
ble_stack_smp_passkey_confirm(g_bt_conn_handle);
return 0;
}
static int cmd_auth_pairing_confirm(int argc, char *argv[])
{
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
ble_stack_smp_pairing_confirm(g_bt_conn_handle);
return 0;
}
#if defined(CONFIG_BT_FIXED_PASSKEY)
static int cmd_fixed_passkey(int argc, char *argv[])
{
unsigned int passkey;
int err;
if (argc < 2) {
bt_passkey_set(BT_PASSKEY_INVALID);
printf("Fixed passkey cleared\n");
return 0;
}
passkey = atoi(argv[1]);
if (passkey > 999999) {
printf("Passkey should be between 0-999999\n");
return 0;
}
err = bt_passkey_set(passkey);
if (err) {
printf("Setting fixed passkey failed (err %d)\n", err);
}
return 0;
}
#endif
static int cmd_auth_passkey(int argc, char *argv[])
{
unsigned int passkey;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
passkey = atoi(argv[1]);
if (passkey > 999999) {
printf("Passkey should be between 0-999999\n");
return 0;
}
ble_stack_smp_passkey_entry(g_bt_conn_handle, passkey);
return 0;
}
#endif /* CONFIG_BT_SMP) || CONFIG_BT_BREDR */
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
static bt_u32_t l2cap_rate;
static void l2cap_recv_metrics(struct bt_l2cap_chan *chan, struct net_buf *buf)
{
return;
}
static void l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
{
printf("Incoming data channel %p psm %d len %u\n", chan, chan->psm, buf->len);
if (buf->len) {
hexdump(buf->data, buf->len);
}
}
static void l2cap_connected(struct bt_l2cap_chan *chan)
{
printf("Channel %p psm %d connected\n", chan, chan->psm);
}
static void l2cap_disconnected(struct bt_l2cap_chan *chan)
{
printf("Channel %p psm %d disconnected\n", chan, chan->psm);
}
static struct net_buf *l2cap_alloc_buf(struct bt_l2cap_chan *chan)
{
/* print if metrics is disabled */
if (chan->ops->recv != l2cap_recv_metrics) {
printf("Channel %p requires buffer\n", chan);
}
return net_buf_alloc(&data_rx_pool, K_FOREVER);
}
static struct bt_l2cap_chan_ops l2cap_ops = {
.alloc_buf = l2cap_alloc_buf,
.recv = l2cap_recv,
.connected = l2cap_connected,
.disconnected = l2cap_disconnected,
};
static struct bt_l2cap_le_chan l2cap_chan[L2CAP_DYM_CHANNEL_NUM] = {
0
};
static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
{
printf("Incoming conn %p\n", conn);
int i;
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.conn == NULL) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No channels available\n");
return -ENOMEM;
}
l2cap_chan[i].chan.ops = &l2cap_ops;
l2cap_chan[i].rx.mtu = DATA_MTU;
*chan = &l2cap_chan[i].chan;
return 0;
}
static struct bt_l2cap_server server[L2CAP_DYM_CHANNEL_NUM] = {
0
};
static int cmd_l2cap_register(int argc, char *argv[])
{
int i;
if (argc < 2) {
return -EINVAL;
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (server[i].psm == 0) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No more channel\n");
return 0;
}
server[i].accept = l2cap_accept;
server[i].psm = strtoul(argv[1], NULL, 16);
if (argc > 2) {
server[i].sec_level = strtoul(argv[2], NULL, 10);
}
if (bt_l2cap_server_register(&server[i]) < 0) {
printf("Unable to register psm\n");
server[i].psm = 0;
} else {
printf("L2CAP psm %u sec_level %u registered\n", server[i].psm,
server[i].sec_level);
}
return 0;
}
static int cmd_l2cap_connect(int argc, char *argv[])
{
u16_t psm;
int err;
int i;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.conn == NULL) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No more Channel\n");
return -EINVAL;
}
l2cap_chan[i].chan.ops = &l2cap_ops;
l2cap_chan[i].rx.mtu = DATA_MTU;
psm = strtoul(argv[1], NULL, 16);
err = bt_l2cap_chan_connect(bt_conn_lookup_id(g_bt_conn_handle), &l2cap_chan[i].chan, psm);
if (err < 0) {
printf("Unable to connect to psm %u (err %u)\n", psm, err);
} else {
printf("L2CAP connection pending\n");
}
return 0;
}
static int cmd_l2cap_disconnect(int argc, char *argv[])
{
int err;
u16_t psm;
int i;
psm = strtoul(argv[1], NULL, 16);
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.psm == psm) {
err = bt_l2cap_chan_disconnect(&l2cap_chan[i].chan);
if (err) {
printf("Unable to disconnect: err %u\n", -err);
}
return err;
}
}
return 0;
}
static int cmd_l2cap_send(int argc, char *argv[])
{
static u8_t buf_data[DATA_MTU] = { [0 ...(DATA_MTU - 1)] = 0xff };
int ret, len, count = 1;
struct net_buf *buf;
u16_t psm = 0;
int i;
if (argc > 1) {
psm = strtoul(argv[1], NULL, 16);
} else {
return -EINVAL;
}
if (argc > 2) {
count = strtoul(argv[2], NULL, 10);
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.psm == psm) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("Can't find channel\n");
return -EINVAL;
}
/* when mtu is 23, the max send num is 8, so 6*23 is safe */
len = min(6*23, DATA_MTU - BT_L2CAP_CHAN_SEND_RESERVE);
while (count--) {
buf = net_buf_alloc(&data_tx_pool, K_FOREVER);
net_buf_reserve(buf, BT_L2CAP_CHAN_SEND_RESERVE);
net_buf_add_mem(buf, buf_data, len);
ret = bt_l2cap_chan_send(&l2cap_chan[i].chan, buf);
if (ret < 0) {
printf("Unable to send: %d\n", -ret);
net_buf_unref(buf);
break;
}
}
return 0;
}
static int cmd_l2cap_metrics(int argc, char *argv[])
{
const char *action;
if (argc < 2) {
printf("l2cap rate: %u bps.\n", l2cap_rate);
return 0;
}
action = argv[1];
if (!strcmp(action, "on")) {
l2cap_ops.recv = l2cap_recv_metrics;
} else if (!strcmp(action, "off")) {
l2cap_ops.recv = l2cap_recv;
} else {
return -EINVAL;
}
printf("l2cap metrics %s.\n", action);
return 0;
}
#endif
#if 0
static int write_mac_addr(partition_t handle, const uint8_t *buffer, int length, int offset)
{
// if ((offset % lp->sector_size) == 0) {
// if (partition_erase(handle, offset, (1 + length / lp->sector_size)) < 0) {
// printf("erase addr:%x\r\n", offset);
// return -1;
// }
// }
// if (partition_write(handle, offset, (void *)buffer, length) >= 0) {
// return length;
// }
// printf("write fail addr:%x length:%x\r\n", offset, length);
return -1;
}
static int str2_char(const char *str, uint8_t *addr)
{
int i, j;
u8_t tmp;
if (strlen(str) != 17) {
return -EINVAL;
}
for (i = 0, j = 1; *str != '\0'; str++, j++) {
if (!(j % 3) && (*str != ':')) {
return -EINVAL;
} else if (*str == ':') {
i++;
continue;
}
addr[i] = addr[i] << 4;
if (char2hex(*str, &tmp) < 0) {
return -EINVAL;
}
addr[i] |= tmp;
}
return 0;
}
static int flash_opt_mac(int argc, char *argv[])
{
int err;
uint8_t addr[6] = {0};
uint8_t send_addr[6] = {0};
const char *action;
handle = partition_open("FCDS");
lp = hal_flash_get_info(handle);
action = argv[1];
if ((argc == 3) && (!strcmp(action, "write"))) {
err = str2_char(argv[2], addr);
if (err < 0) {
return err;
}
if (err) {
printf("Invalid address\n");
return err;
}
send_addr[0] = addr[2];
send_addr[1] = addr[3];
send_addr[2] = addr[4];
send_addr[3] = addr[5];
send_addr[4] = addr[0];
send_addr[5] = addr[1];
if (write_mac_addr(handle, send_addr, sizeof(send_addr), 0) < 0) {
return -1;
}
} else if (!strcmp(action, "read")) {
partition_read(handle, 0, addr, sizeof(addr));
printf("mac:%x:%x:%x:%x:%x:%x", addr[4], addr[5], addr[0], addr[1], addr[2], addr[3]);
}
partition_close(handle);
return 0;
}
#endif
#if defined(CONFIG_BT_WHITELIST)
static int get_wl_size()
{
int wl_actal_szie;
wl_actal_szie = ble_stack_white_list_size();
if(wl_actal_szie <= 0) {
return -1;
}
if(wl_actal_szie > MAX_WL_SZIE) {
printf("actual wl size is %d but upper wl list size is %d\n", wl_actal_szie, MAX_WL_SZIE);
}
return wl_actal_szie < MAX_WL_SZIE? wl_actal_szie : MAX_WL_SZIE;
}
bool is_wl_addr_exist(dev_addr_t addr)
{
uint8_t index = 0;
uint8_t size = 0;
size = get_wl_size();
for(index = 0; index < size; index++) {
if(wl_list[index].set_flag) {
if(!memcmp(&wl_list[index].addr,&addr,sizeof(wl_list[index].addr))) {
return 1;
}
}
}
if(index >= size) {
return 0;
}
return 0;
}
int add_addr_to_wl_list(dev_addr_t addr)
{
uint8_t index = 0;
uint8_t size = 0;
size = get_wl_size();
for(index = 0; index < size; index++) {
if(!wl_list[index].set_flag) {
memcpy(&wl_list[index].addr,&addr,sizeof(wl_list[index].addr));
wl_list[index].set_flag = 1;
break;
}
}
if(index >= size) {
printf("wl list is full\r\n");
return -1;
} else {
return 0;
}
}
int remove_addr_form_wl_list(dev_addr_t addr)
{
uint8_t index = 0;
uint8_t size = 0;
size = get_wl_size();
for(index = 0; index < size; index++) {
if(wl_list[index].set_flag) {
if(!memcmp(&wl_list[index].addr, &addr, sizeof(addr))) {
memset(&wl_list[index],0, sizeof(wl_addr));
break;
}
}
}
if(index >= size) {
printf("wl addr not exist\r\n");
return -1;
} else {
return 0;
}
}
int show_wl_list()
{
int found_flag = 0;
uint8_t index = 0;
uint8_t size = 0;
char addr_str[32] = {0};
size = get_wl_size();
for(index = 0; index < size; index++) {
if(wl_list[index].set_flag) {
bt_addr2str(&wl_list[index].addr, addr_str, sizeof(addr_str));
found_flag = 1;
printf("wl %d: %s\r\n",index,addr_str);
}
}
if(!found_flag) {
printf("wl addr not exit\r\n");
return -1;
} else {
return 0;
}
}
int clear_wl_list()
{
memset(wl_list,0,sizeof(wl_list));
return 0;
}
static int cmd_wl_size(int argc, char *argv[])
{
if(!ble_init_flag) {
return -BLE_STACK_ERR_INIT;
}
int ret = ble_stack_white_list_size();
printf("white list size is %d\n", ret);
return 0;
}
static int cmd_wl_add(int argc, char *argv[])
{
dev_addr_t addr;
int err;
if(!ble_init_flag) {
return -BLE_STACK_ERR_INIT;
}
if (argc == 3) {
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
return -EINVAL;
}
if(is_wl_addr_exist(addr)) {
printf("wl addr already exist\r\n");
return 0;
}
err = ble_stack_white_list_add(&addr);
if(!err) {
err = add_addr_to_wl_list(addr);
if(err) {
printf("add to upper wl list faild\r\n");
} else {
printf("Add %s (%s) to white list\n", argv[1], argv[2]);
}
} else {
printf("add wl addr faild\r\n");
}
return 0;
}
static int cmd_wl_remove(int argc, char *argv[])
{
if(!ble_init_flag) {
return -BLE_STACK_ERR_INIT;
}
dev_addr_t addr;
int err;
if (argc == 3) {
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
return -EINVAL;
}
if(!is_wl_addr_exist(addr)) {
printf("wl addr not exist\r\n");
return -1;
}
err = ble_stack_white_list_remove(&addr);
if(!err) {
err = remove_addr_form_wl_list(addr);
if(err) {
printf("remove from upper wl list faild\r\n");
} else {
printf("Remove %s (%s) to white list\n", argv[1], argv[2]);
}
} else {
printf("add wl addr faild\r\n");
}
return err;
}
static int cmd_wl_clear(int argc, char *argv[])
{
if(!ble_init_flag) {
return -BLE_STACK_ERR_INIT;
}
int err = 0;
printf("Clear white list\n");
err = ble_stack_white_list_clear();
if(!err) {
clear_wl_list();
}
return err;
}
static int cmd_wl_show(int argc, char *argv[])
{
if(!ble_init_flag) {
return -BLE_STACK_ERR_INIT;
}
show_wl_list();
return 0;
}
#endif
#define HELP_NONE "[none]"
#define HELP_ADDR_LE "<address: XX:XX:XX:XX:XX:XX> <type: (public|random)>"
static const struct shell_cmd bt_commands[] = {
{ "init", cmd_init, HELP_ADDR_LE },
//{ "mac", flash_opt_mac, "<val:read/write> exp:write 11:22:33:44:55:66" },
#if defined(CONFIG_BT_HCI)
//{ "hci-cmd", cmd_hci_cmd, "<ogf> <ocf> [data]" },
#endif
{ "id-create", cmd_id_create, "[addr]" },
{ "id-reset", cmd_id_reset, "<id> [addr]" },
{ "id-delete", cmd_id_delete, "<id>" },
{ "id-show", cmd_id_show, HELP_NONE },
{ "id-select", cmd_id_select, "<id>" },
{ "name", cmd_name, "[name]" },
{
"scan", cmd_scan,
"<value: active, passive, off> <dup filter: dups, nodups> "\
"<scan interval> <scan window> "\
"<ad(len|adtype|addata ...): 0xxxxxxxx> <sd(len|adtype|addata ...): 0xxxxxxxx>"
},
{
"scan_filter", cmd_scan_filter,
"<filter_policy: 0 any adv 1 white list>"
},
{
"adv", cmd_advertise,
"<type: stop, conn, nconn> <ad(len|adtype|addata ...): 0xxxxxxxx> <sd(len|adtype|addata ...): 0xxxxxxxx>"
},
#if defined(CONFIG_BT_CONN)
{
"connect", cmd_connect_le, HELP_ADDR_LE\
" <interval_min> <interval_max>"\
" <latency> <timeout>"
},
{ "disconnect", cmd_disconnect, "[conn_handle]" },
{ "auto-conn", cmd_auto_conn, HELP_ADDR_LE" <action: on|off>"},
{ "select", cmd_select, HELP_ADDR_LE },
{ "conn-update", cmd_conn_update, "<min> <max> <latency> <timeout>" },
{ "oob", cmd_oob },
{ "clear", cmd_clear,"<dst:all,address> <type: (public|random>"},
#if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
{ "security", cmd_security, "<security level: 0, 1, 2, 3>" },
{
"io-capability", cmd_iocap_set,
"<io input: NONE,YESNO, KEYBOARD> <io output: NONE,DISPLAY>"
},
{ "auth-cancel", cmd_auth_cancel, HELP_NONE },
{ "auth-passkey", cmd_auth_passkey, "<passkey>" },
{ "auth-passkey-confirm", cmd_auth_passkey_confirm, HELP_NONE },
{ "auth-pairing-confirm", cmd_auth_pairing_confirm, HELP_NONE },
#if defined(CONFIG_BT_FIXED_PASSKEY)
{ "fixed-passkey", cmd_fixed_passkey, "[passkey]" },
#endif
#endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR) */
#if defined(CONFIG_BT_GATT_CLIENT)
{ "gatt-exchange-mtu", cmd_gatt_exchange_mtu, HELP_NONE },
{
"gatt-discover-primary", cmd_gatt_discover,
"<UUID> [start handle] [end handle]"
},
{
"gatt-discover-secondary", cmd_gatt_discover,
"<UUID> [start handle] [end handle]"
},
{
"gatt-discover-include", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{
"gatt-discover-characteristic", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{
"gatt-discover-descriptor", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{ "gatt-read-format",cmd_gatt_read_show_format,"<format:0,1>"},
{ "gatt-read", cmd_gatt_read, "<handle> [offset]" },
{ "gatt-read-multiple", cmd_gatt_mread, "<handle 1> <handle 2> ..." },
{ "gatt-write", cmd_gatt_write, "<handle> <offset> <data> [length]" },
{
"gatt-write-without-response", cmd_gatt_write_without_rsp,
"<handle> <data> [length] [repeat]"
},
{
"gatt-write-signed", cmd_gatt_write_without_rsp,
"<handle> <data> [length] [repeat]"
},
{
"gatt-subscribe", cmd_gatt_subscribe,
"<CCC handle> [ind]"
},
{ "gatt-unsubscribe", cmd_gatt_unsubscribe, "<CCC handle>"},
#endif /* CONFIG_BT_GATT_CLIENT */
{ "gatt-show-db", cmd_gatt_show_db, HELP_NONE },
{
"gatt-register-service", cmd_gatt_register_test_svc,
"register pre-predefined test service"
},
{
"gatt-register-service2", cmd_gatt_register_test_svc,
"register pre-predefined test2 service"
},
{
"gatt-transport-test-config", cmd_gatt_transport_test,
"<type 0:server 1 client> <mode 0:loop 1:single> <server tx mode 0:notify 1:indicate> <server rx handle> <client tx mode 0:write 1:write_withoutresponse> "\
"<data_len 0:stream 1~0xFFFFFFFF data size>"
},
{
"gatt-transport-test-op", cmd_gatt_transport_test,
"<op 0:stop 1:start 2:show result 3:reset>"
},
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
{ "l2cap-register", cmd_l2cap_register, "<psm> [sec_level]" },
{ "l2cap-connect", cmd_l2cap_connect, "<psm>" },
{ "l2cap-disconnect", cmd_l2cap_disconnect, "<psm>" },
{ "l2cap-send", cmd_l2cap_send, "<psm> <number of packets>" },
{ "l2cap-metrics", cmd_l2cap_metrics, "<value on, off>" },
#endif
#endif /* CONFIG_BT_CONN */
#if defined(CONFIG_BT_CTLR_ADV_EXT)
{ "advx", cmd_advx, "<on off> [coded] [anon] [txp]" },
{ "scanx", cmd_scanx, "<on passive off> [coded]" },
#endif /* CONFIG_BT_CTLR_ADV_EXT */
#if defined(CONFIG_BT_CTLR_DTM)
{ "test_tx", cmd_test_tx, "<chan> <len> <type> <phy>" },
{ "test_rx", cmd_test_rx, "<chan> <phy> <mod_idx>" },
{ "test_end", cmd_test_end, HELP_NONE},
#endif /* CONFIG_BT_CTLR_ADV_EXT */
#if defined(CONFIG_BT_WHITELIST)
{ "wl-size", cmd_wl_size, HELP_NONE},
{ "wl-add", cmd_wl_add, HELP_ADDR_LE},
{ "wl-remove", cmd_wl_remove, HELP_ADDR_LE},
{ "wl-clear", cmd_wl_clear, HELP_NONE},
{ "wl-show", cmd_wl_show, HELP_NONE},
#endif
{ NULL, NULL, NULL }
};
static void cmd_ble_func(char *wbuf, int wbuf_len, int argc, char **argv)
{
int i = 0;
int err;
if (argc < 2) {
printf("Ble support commands\n");
for (i = 0; bt_commands[i].cmd_name != NULL; i ++) {
printf(" %s %s\n", bt_commands[i].cmd_name, bt_commands[i].help);
}
return;
}
for (i = 0; bt_commands[i].cmd_name != NULL; i ++) {
if (strlen(bt_commands[i].cmd_name) == strlen(argv[1]) &&
!strncmp(bt_commands[i].cmd_name, argv[1], strlen(bt_commands[i].cmd_name))) {
if (bt_commands[i].cb) {
err = bt_commands[i].cb(argc - 1, &argv[1]);
if (err) {
printf("%s execute fail, %d\n", bt_commands[i].cmd_name, err);
}
break;
}
}
}
}
#if AOS_COMP_CLI
void cli_reg_cmd_ble(void)
{
static const struct cli_command cmd_info = {
"ble",
"ble commands",
cmd_ble_func,
};
aos_cli_register_command(&cmd_info);
}
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/bt.c | C | apache-2.0 | 50,694 |
/** @file
* @brief Bluetooth shell functions
*
* This is not to be included by the application.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_H
#define __BT_H
extern struct bt_conn *default_conn;
#endif /* __BT_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/bt.h | C | apache-2.0 | 285 |
/** @file
* @brief Bluetooth Controller and flash co-operation
*
*/
/*
* Copyright (c) 2017 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <shell/shell.h>
#include <misc/printk.h>
#include <stdlib.h>
#include <string.h>
#include "flash.h"
#include <soc.h>
#define FLASH_SHELL_MODULE "flash"
#define BUF_ARRAY_CNT 16
#define TEST_ARR_SIZE 0x1000
static u8_t test_arr[TEST_ARR_SIZE];
static int cmd_erase(int argc, char *argv[])
{
struct device *flash_dev;
bt_u32_t page_addr;
int result;
bt_u32_t size;
flash_dev = device_get_binding(FLASH_DEV_NAME);
if (!flash_dev) {
printk("Nordic nRF5 flash driver was not found!\n");
return -ENODEV;
}
if (argc < 2) {
printk("Missing page address.\n");
return -EINVAL;
}
page_addr = strtoul(argv[1], NULL, 16);
if (argc > 2) {
size = strtoul(argv[2], NULL, 16);
} else {
size = NRF_FICR->CODEPAGESIZE;
}
flash_write_protection_set(flash_dev, 0);
result = flash_erase(flash_dev, page_addr, size);
if (result) {
printk("Erase Failed, code %d.\n", result);
} else {
printk("Erase success.\n");
}
return result;
}
static int cmd_flash(int argc, char *argv[])
{
bt_u32_t check_array[BUF_ARRAY_CNT];
bt_u32_t buf_array[BUF_ARRAY_CNT];
struct device *flash_dev;
bt_u32_t w_addr;
int j = 0;
flash_dev = device_get_binding(FLASH_DEV_NAME);
if (!flash_dev) {
printk("Nordic nRF5 flash driver was not found!\n");
return -ENODEV;
}
if (argc < 2) {
printk("Missing address.\n");
return -EINVAL;
}
if (argc <= 2) {
printk("Type data to be written.\n");
return -EINVAL;
}
for (int i = 2; i < argc && i < BUF_ARRAY_CNT; i++) {
buf_array[j] = strtoul(argv[i], NULL, 16);
check_array[j] = ~buf_array[j];
j++;
}
flash_write_protection_set(flash_dev, 0);
w_addr = strtoul(argv[1], NULL, 16);
if (flash_write(flash_dev, w_addr, buf_array,
sizeof(buf_array[0]) * j) != 0) {
printk("Write internal ERROR!\n");
return -EIO;
}
printk("Write OK.\n");
flash_read(flash_dev, w_addr, check_array, sizeof(buf_array[0]) * j);
if (memcmp(buf_array, check_array, sizeof(buf_array[0]) * j) == 0) {
printk("Verified.\n");
} else {
printk("Verification ERROR!\n");
return -EIO;
}
return 0;
}
static int cmd_read(int argc, char *argv[])
{
struct device *flash_dev;
bt_u32_t addr;
int cnt;
flash_dev = device_get_binding(FLASH_DEV_NAME);
if (!flash_dev) {
printk("Nordic nRF5 flash driver was not found!\n");
return -ENODEV;
}
if (argc < 2) {
printk("Missing address.\n");
return -EINVAL;
}
addr = strtoul(argv[1], NULL, 16);
if (argc > 2) {
cnt = strtoul(argv[2], NULL, 16);
} else {
cnt = 1;
}
while (cnt--) {
bt_u32_t data;
flash_read(flash_dev, addr, &data, sizeof(data));
printk("0x%08x ", data);
addr += sizeof(data);
}
printk("\n");
return 0;
}
static int cmd_test(int argc, char *argv[])
{
struct device *flash_dev;
bt_u32_t repeat;
int result;
bt_u32_t addr;
bt_u32_t size;
flash_dev = device_get_binding(FLASH_DEV_NAME);
if (!flash_dev) {
printk("Nordic nRF5 flash driver was not found!\n");
return -ENODEV;
}
if (argc != 4) {
printk("3 parameters reqired.\n");
return -EINVAL;
}
addr = strtoul(argv[1], NULL, 16);
size = strtoul(argv[2], NULL, 16);
repeat = strtoul(argv[3], NULL, 16);
if (size > TEST_ARR_SIZE) {
printk("<size> must be at most 0x%x.", TEST_ARR_SIZE);
return -EINVAL;
}
flash_write_protection_set(flash_dev, 0);
for (bt_u32_t i = 0; i < size; i++) {
test_arr[i] = (u8_t)i;
}
while (repeat--) {
result = flash_erase(flash_dev, addr, size);
if (result) {
printk("Erase Failed, code %d.\n", result);
return -EIO;
}
printk("Erase OK.\n");
if (flash_write(flash_dev, addr, test_arr, size) != 0) {
printk("Write internal ERROR!\n");
return -EIO;
}
printk("Write OK.\n");
}
printk("Erase-Write test done.\n");
return 0;
}
static const struct shell_cmd flash_commands[] = {
{ "flash-write", cmd_flash, "<address> <Dword> <Dword>..."},
{ "flash-erase", cmd_erase, "<page address> <size>"},
{ "flash-read", cmd_read, "<address> <Dword count>"},
{ "flash-test", cmd_test, "<address> <size> <repeat count>"},
{ NULL, NULL, NULL}
};
SHELL_REGISTER(FLASH_SHELL_MODULE, flash_commands);
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/flash.c | C | apache-2.0 | 4,299 |
/** @file
* @brief Bluetooth GATT shell functions
*
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <bt_errno.h>
#include <ble_types/types.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <misc/byteorder.h>
#include <ble_os.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include "bt.h"
#include "gatt.h"
#include <aos/ble.h>
#include <aos/gatt.h>
#include <aos/kernel.h>
#include <work.h>
#define CHAR_SIZE_MAX 256
extern int16_t g_bt_conn_handle;
extern int16_t g_security_level;
#define VALUE_LEN 100
extern char *uuid_str(uuid_t *uuid);
extern void str2hex(uint8_t hex[], char *s, uint8_t cnt);
extern void hexdump(const u8_t *data, size_t len);
uint8_t gatt_read_show_mode = 0;
struct test_svc_t {
int16_t conn_handle;
uint16_t svc_handle;
uint16_t svc2_handle;
ccc_value_en ccc;
uint16_t mtu;
char value1[256];
char value2[VALUE_LEN];
char value3[8];
char value3_cud[30];
char value4[VALUE_LEN];
} test_svc = {
.conn_handle = -1,
.svc_handle = 0,
.svc2_handle = 0,
.mtu = VALUE_LEN,
.value1 = "test value 1",
.value2 = "test value 2",
.value3 = "test",
.value3_cud = "this is value3 cud",
.value4 = "test value 4",
};
#if defined(CONFIG_BT_GATT_CLIENT)
static int event_gatt_mtu_exchange(ble_event_en event, void *event_data)
{
evt_data_gatt_mtu_exchange_t *e = event_data;
test_svc.mtu = ble_stack_gatt_mtu_get(e->conn_handle);
printf("Exchange %s, MTU %d\n", e->err == 0 ? "successful" : "failed", test_svc.mtu);
return 0;
}
int cmd_gatt_exchange_mtu(int argc, char *argv[])
{
int err;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
err = ble_stack_gatt_mtu_exchange(g_bt_conn_handle);
if (err) {
printf("Exchange failed (err %d)\n", err);
} else {
printf("Exchange pending\n");
}
return 0;
}
static void print_chrc_props(u8_t properties)
{
printf("Properties: ");
if (properties & GATT_CHRC_PROP_BROADCAST) {
printf("[bcast]");
}
if (properties & GATT_CHRC_PROP_READ) {
printf("[read]");
}
if (properties & GATT_CHRC_PROP_WRITE) {
printf("[write]");
}
if (properties & GATT_CHRC_PROP_WRITE_WITHOUT_RESP) {
printf("[write w/w rsp]");
}
if (properties & GATT_CHRC_PROP_NOTIFY) {
printf("[notify]");
}
if (properties & GATT_CHRC_PROP_INDICATE) {
printf("[indicate]");
}
if (properties & GATT_CHRC_PROP_AUTH) {
printf("[auth]");
}
if (properties & GATT_CHRC_PROP_EXT_PROP) {
printf("[ext prop]");
}
printf("\n");
}
static int event_gatt_discovery(ble_event_en event, void *event_data)
{
union {
evt_data_gatt_discovery_svc_t svc;
evt_data_gatt_discovery_inc_svc_t svc_inc;
evt_data_gatt_discovery_char_t char_c;
evt_data_gatt_discovery_char_des_t char_des;
} *e;
e = event_data;
switch (event) {
case EVENT_GATT_DISCOVERY_SVC:
printf("Service %s found: start handle %x, end_handle %x\n",
uuid_str(&e->svc.uuid), e->svc.start_handle, e->svc.end_handle);
break;
case EVENT_GATT_DISCOVERY_CHAR:
printf("Characteristic %s found: handle %x\n", uuid_str(&e->char_c.uuid),
e->char_c.attr_handle);
print_chrc_props(e->char_c.props);
break;
case EVENT_GATT_DISCOVERY_INC_SVC:
printf("Include %s found: handle %x, start %x, end %x\n",
uuid_str(&e->svc_inc.uuid), e->svc_inc.attr_handle, e->svc_inc.start_handle,
e->svc_inc.end_handle);
break;
default:
printf("Descriptor %s found: handle %x\n", uuid_str(&e->char_des.uuid), e->char_des.attr_handle);
break;
}
return 0;
}
int cmd_gatt_discover(int argc, char *argv[])
{
int err;
gatt_discovery_type_en type;
union {
struct ut_uuid_16 uuid16;
struct ut_uuid_32 uuid32;
struct ut_uuid_128 uuid128;
} uuid = {0};
uint16_t start_handle = 0x0001;
uint16_t end_handle = 0xffff;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
if (!strcmp(argv[0], "gatt-discover-primary") ||
!strcmp(argv[0], "gatt-discover-secondary")) {
return -EINVAL;
}
goto done;
}
/* Only set the UUID if the value is valid (non zero) */
if (strlen(argv[1]) <= 4) {
uuid.uuid16.uuid.type = UUID_TYPE_16;
uuid.uuid16.val = strtoul(argv[1], NULL, 16);
} else if (strlen(argv[1]) == 32) {
uuid.uuid128.uuid.type = UUID_TYPE_128;
str2hex(uuid.uuid128.val, argv[1], 16);
} else {
printf("invaild uuid\n");
return -EINVAL;
}
if (argc > 2) {
start_handle = strtoul(argv[2], NULL, 16);
if (argc > 3) {
end_handle = strtoul(argv[3], NULL, 16);
}
}
done:
if (!strcmp(argv[0], "gatt-discover-secondary")) {
type = BT_GATT_DISCOVER_SECONDARY;
} else if (!strcmp(argv[0], "gatt-discover-include")) {
type = GATT_FIND_INC_SERVICE;
} else if (!strcmp(argv[0], "gatt-discover-characteristic")) {
type = GATT_FIND_CHAR;
} else if (!strcmp(argv[0], "gatt-discover-descriptor")) {
type = GATT_FIND_CHAR_DESCRIPTOR;
} else {
type = GATT_FIND_PRIMARY_SERVICE;
}
err = ble_stack_gatt_discovery(g_bt_conn_handle, type, (uuid.uuid16.uuid.type == 0 && uuid.uuid16.val == 0) ? NULL : (uuid_t *)&uuid, start_handle, end_handle);
if (err) {
printf("Discover failed (err %d)\n", err);
} else {
printf("Discover pending\n");
}
return 0;
}
static int event_gatt_read_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_read_cb_t *e = event_data;
printf("Read complete: err %u length %u\n", e->err, e->len);
if(!e->len || !e->data){
return 0;
}
if(!gatt_read_show_mode) {
hexdump(e->data, e->len);
} else {
for(int i = 0; i < e->len; i++) {
printf("%02x",*e->data++);
}
printf("\r\n");
}
return 0;
}
int cmd_gatt_read_show_format(int argc, char *argv[])
{
if (argc < 2) {
return -EINVAL;
}
gatt_read_show_mode = strtoul(argv[1], NULL, 16);
return 0;
}
int cmd_gatt_read(int argc, char *argv[])
{
int err;
uint16_t handle;
uint16_t offset = 0;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
handle = strtoul(argv[1], NULL, 16);
if (argc > 2) {
offset = strtoul(argv[2], NULL, 16);
}
err = ble_stack_gatt_read(g_bt_conn_handle, handle, offset);
if (err) {
printf("Read failed (err %d)\n", err);
} else {
printf("Read pending\n");
}
return 0;
}
int cmd_gatt_mread(int argc, char *argv[])
{
int i, err;
static uint16_t h[8];
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
if (argc - 1 > BLE_ARRAY_NUM(h)) {
printf("Enter max %lu handle items to read\n", ARRAY_SIZE(h));
return 0;
}
for (i = 0; i < argc - 1; i++) {
h[i] = strtoul(argv[i + 1], NULL, 16);
}
err = ble_stack_gatt_read_multiple(g_bt_conn_handle, argc - 1, h);
if (err) {
printf("GATT multiple read request failed (err %d)\n", err);
}
return 0;
}
static u8_t gatt_write_buf[CHAR_SIZE_MAX];
static int event_gatt_write_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_write_cb_t *e = event_data;
printf("Write complete: err %u\n", e->err);
return 0;
}
int cmd_gatt_write(int argc, char *argv[])
{
int err;
uint16_t handle, offset, len = 1;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 4) {
return -EINVAL;
}
handle = strtoul(argv[1], NULL, 16);
offset = strtoul(argv[2], NULL, 16);
gatt_write_buf[0] = strtoul(argv[3], NULL, 16);
if (argc == 5) {
int i;
len = BLE_MIN(strtoul(argv[4], NULL, 16), sizeof(gatt_write_buf));
for (i = 1; i < len; i++) {
gatt_write_buf[i] = gatt_write_buf[0];
}
}
err = ble_stack_gatt_write_response(g_bt_conn_handle, handle, gatt_write_buf, len, offset);
if (err) {
printf("Write failed (err %d)\n", err);
} else {
printf("Write pending\n");
}
return 0;
}
int cmd_gatt_write_without_rsp(int argc, char *argv[])
{
uint16_t handle;
uint16_t repeat;
int err = 0;
uint16_t len;
bool sign;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
sign = !strcmp(argv[0], "gatt-write-signed");
handle = strtoul(argv[1], NULL, 16);
gatt_write_buf[0] = strtoul(argv[2], NULL, 16);
len = 1;
if (argc > 3) {
int i;
len = BLE_MIN(strtoul(argv[3], NULL, 16), sizeof(gatt_write_buf));
for (i = 1; i < len; i++) {
gatt_write_buf[i] = gatt_write_buf[0];
}
}
repeat = 0;
if (argc > 4) {
repeat = strtoul(argv[4], NULL, 16);
}
if (!repeat) {
repeat = 1;
}
while (repeat--) {
if (sign) {
err = ble_stack_gatt_write_signed(g_bt_conn_handle, handle,
gatt_write_buf, len, 0);
} else {
err = ble_stack_gatt_write_no_response(g_bt_conn_handle, handle,
gatt_write_buf, len, 0);
}
if (err) {
break;
}
}
printf("Write Complete (err %d)\n", err);
return 0;
}
static int event_gatt_notify(ble_event_en event, void *event_data)
{
evt_data_gatt_notify_t *e = event_data;
printf("Notification: char handle %d length %u\n", e->char_handle, e->len);
hexdump(e->data, e->len);
return 0;
}
int cmd_gatt_subscribe(int argc, char *argv[])
{
int err;
uint16_t ccc_handle;
uint16_t value = 0;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
ccc_handle = strtoul(argv[1], NULL, 16);
value = CCC_VALUE_NOTIFY;
if (argc >= 3 && !strcmp(argv[2], "ind")) {
value = CCC_VALUE_INDICATE;
}
err = ble_stack_gatt_write_response(g_bt_conn_handle, ccc_handle, &value, sizeof(value), 0);
if (err) {
printf("Subscribe failed (err %d)\n", err);
} else {
printf("Subscribed\n");
}
return 0;
}
int cmd_gatt_unsubscribe(int argc, char *argv[])
{
int err;
uint16_t ccc_handle;
uint16_t value = CCC_VALUE_NONE;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
ccc_handle = strtoul(argv[1], NULL, 16);
err = ble_stack_gatt_write_response(g_bt_conn_handle, ccc_handle, &value, sizeof(value), 0);
if (err) {
printf("Unsubscribe failed (err %d)\n", err);
} else {
printf("Unsubscribe success\n");
}
return 0;
}
#endif /* CONFIG_BT_GATT_CLIENT */
static u8_t print_attr(const struct bt_gatt_attr *attr, void *user_data)
{
printf("attr %p handle 0x%04x uuid %s perm 0x%02x\n",
attr, attr->handle, bt_uuid_str(attr->uuid), attr->perm);
return BT_GATT_ITER_CONTINUE;
}
int cmd_gatt_show_db(int argc, char *argv[])
{
bt_gatt_foreach_attr(0x0001, 0xffff, print_attr, NULL);
return 0;
}
#define TEST_SERVICE_UUID UUID128_DECLARE(0xF0,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR1_UUID UUID128_DECLARE(0xF1,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR2_UUID UUID128_DECLARE(0xF2,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR3_UUID UUID128_DECLARE(0xF3,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR4_UUID UUID128_DECLARE(0xF4,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR5_UUID UUID128_DECLARE(0xF5,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR6_UUID UUID128_DECLARE(0xF6,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR7_UUID UUID128_DECLARE(0xF7,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_SERVICE_UUID UUID128_DECLARE(0xF0,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR1_UUID UUID128_DECLARE(0xF1,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR2_UUID UUID128_DECLARE(0xF2,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR3_UUID UUID128_DECLARE(0xF3,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR4_UUID UUID128_DECLARE(0xF4,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR5_UUID UUID128_DECLARE(0xF5,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR6_UUID UUID128_DECLARE(0xF6,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
enum {
TEST_IDX_SVC,
TEST_IDX_CHAR1,
TEST_IDX_CHAR1_VAL,
TEST_IDX_CHAR2,
TEST_IDX_CHAR2_VAL,
TEST_IDX_CHAR5,
TEST_IDX_CHAR5_VAL,
TEST_IDX_CHAR3,
TEST_IDX_CHAR3_VAL,
TEST_IDX_CHAR3_CUD,
TEST_IDX_CHAR3_CCC,
TEST_IDX_CHAR4,
TEST_IDX_CHAR4_VAL,
TEST_IDX_CHAR6,
TEST_IDX_CHAR6_VAL,
TEST_IDX_CHAR7,
TEST_IDX_CHAR7_VAL,
TEST_IDX_MAX,
};
//static struct bt_gatt_ccc_cfg_t bas_ccc_cfg[2] = {};
gatt_service test_service;
gatt_service test2_service;
static gatt_attr_t test_attrs[] = {
[TEST_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST_SERVICE_UUID),
[TEST_IDX_CHAR1] = GATT_CHAR_DEFINE(TEST_CHAR1_UUID, GATT_CHRC_PROP_READ),
[TEST_IDX_CHAR1_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR1_UUID, GATT_PERM_READ),
[TEST_IDX_CHAR2] = GATT_CHAR_DEFINE(TEST_CHAR2_UUID, GATT_CHRC_PROP_READ),
[TEST_IDX_CHAR2_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR2_UUID, GATT_PERM_READ | GATT_PERM_READ_AUTHEN),
[TEST_IDX_CHAR5] = GATT_CHAR_DEFINE(TEST_CHAR5_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR5_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR5_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST_IDX_CHAR3] = GATT_CHAR_DEFINE(TEST_CHAR3_UUID, GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_NOTIFY | GATT_CHRC_PROP_INDICATE | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR3_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR3_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST_IDX_CHAR3_CUD] = GATT_CHAR_CUD_DEFINE(test_svc.value3_cud, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST_IDX_CHAR3_CCC] = GATT_CHAR_CCC_DEFINE(),
[TEST_IDX_CHAR4] = GATT_CHAR_DEFINE(TEST_CHAR4_UUID, GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR4_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR4_UUID, GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE | GATT_PERM_WRITE_AUTHEN),
[TEST_IDX_CHAR6] = GATT_CHAR_DEFINE(TEST_CHAR6_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP),
[TEST_IDX_CHAR6_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR6_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST_IDX_CHAR7] = GATT_CHAR_DEFINE(TEST_CHAR7_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP),
[TEST_IDX_CHAR7_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR7_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE | GATT_PERM_WRITE_AUTHEN),
};
enum {
TEST2_IDX_SVC,
TEST2_IDX_CHAR1,
TEST2_IDX_CHAR1_VAL,
TEST2_IDX_CHAR2,
TEST2_IDX_CHAR2_VAL,
TEST2_IDX_CHAR5,
TEST2_IDX_CHAR5_VAL,
TEST2_IDX_CHAR3,
TEST2_IDX_CHAR3_VAL,
TEST2_IDX_CHAR4,
TEST2_IDX_CHAR4_VAL,
TEST2_IDX_CHAR6,
TEST2_IDX_CHAR6_VAL,
TEST2_IDX_MAX,
};
static gatt_attr_t test2_attrs[] = {
[TEST2_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST2_SERVICE_UUID),
[TEST2_IDX_CHAR1] = GATT_CHAR_DEFINE(TEST2_CHAR1_UUID, GATT_CHRC_PROP_READ),
[TEST2_IDX_CHAR1_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR1_UUID, GATT_PERM_READ),
[TEST2_IDX_CHAR2] = GATT_CHAR_DEFINE(TEST2_CHAR2_UUID, GATT_CHRC_PROP_READ),
[TEST2_IDX_CHAR2_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR2_UUID, GATT_PERM_READ | GATT_PERM_READ_ENCRYPT),
[TEST2_IDX_CHAR5] = GATT_CHAR_DEFINE(TEST2_CHAR5_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR5_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR5_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST2_IDX_CHAR3] = GATT_CHAR_DEFINE(TEST2_CHAR3_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR3_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR3_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST2_IDX_CHAR4] = GATT_CHAR_DEFINE(TEST2_CHAR4_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR4_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR4_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPT | GATT_PERM_PREPARE_WRITE),
[TEST2_IDX_CHAR6] = GATT_CHAR_DEFINE(TEST2_CHAR6_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR6_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR6_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPT),
};
enum {
TEST3_IDX_SVC,
TEST3_IDX_RX,
TEST3_IDX_RX_VAL,
TEST3_IDX_TX,
TEST3_IDX_TX_VAL,
TEST3_IDX_TX_CCC,
TEST3_IDX_MAX,
};
#define TEST3_SERVICE_UUID UUID128_DECLARE(0xF0,0x33,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST3_RX_UUID UUID128_DECLARE(0xF1,0x33,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST3_TX_UUID UUID128_DECLARE(0xF2,0x33,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
static BT_STACK_NOINIT(transport_task_stack, 1024);
//static struct bt_gatt_ccc_cfg_t test3_ccc_cfg[2] = {};
gatt_service test3_service;
struct {
struct k_thread thread;
uint8_t registed;
uint16_t svc_handle;
int16_t conn_handle;
uint8_t rx_buf[247];
uint16_t ccc;
uint8_t type; //0:server 1:client
uint8_t mode; // 0:loop 1:single
uint8_t svc_tx_mode; //0:notify 1:indicate
uint16_t svc_rx_handle;
uint8_t cli_tx_mode; //0:write 1:write without response
uint32_t data_len; // 0:stream otherwise data_size
uint32_t fail_count;
uint32_t missmatch_count;
uint32_t trans_data;
uint32_t tx_count;
uint32_t tx_cb_count;
uint32_t tx_retry_count;
uint32_t rx_count;
uint32_t connect_count;
uint32_t disconn_count;
aos_sem_t op_sem;
aos_sem_t sync_sem;
uint8_t op;
} test3_svc = {0};
static gatt_attr_t test3_attrs0[] = {
[TEST2_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST3_SERVICE_UUID),
[TEST3_IDX_RX] = GATT_CHAR_DEFINE(TEST3_RX_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST3_IDX_RX_VAL] = GATT_CHAR_VAL_DEFINE(TEST3_RX_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST3_IDX_TX] = GATT_CHAR_DEFINE(TEST3_TX_UUID, GATT_CHRC_PROP_NOTIFY),
[TEST3_IDX_TX_VAL] = GATT_CHAR_VAL_DEFINE(TEST3_TX_UUID, GATT_PERM_NONE),
[TEST3_IDX_TX_CCC] = GATT_CHAR_CCC_DEFINE(),
};
static gatt_attr_t test3_attrs1[] = {
[TEST2_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST3_SERVICE_UUID),
[TEST3_IDX_RX] = GATT_CHAR_DEFINE(TEST3_RX_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST3_IDX_RX_VAL] = GATT_CHAR_VAL_DEFINE(TEST3_RX_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST3_IDX_TX] = GATT_CHAR_DEFINE(TEST3_TX_UUID, GATT_CHRC_PROP_INDICATE),
[TEST3_IDX_TX_VAL] = GATT_CHAR_VAL_DEFINE(TEST3_TX_UUID, GATT_PERM_NONE),
[TEST3_IDX_TX_CCC] = GATT_CHAR_CCC_DEFINE(),
};
struct {
uint16_t notify_handle;
uint8_t notify_type;
uint8_t indicate_ongoing;
} g_notify_data = {0};
static void conn_change(ble_event_en event, void *event_data)
{
evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data;
if (e->connected == CONNECTED) {
test_svc.conn_handle = e->conn_handle;
} else {
test_svc.conn_handle = -1;
g_notify_data.notify_type = 0;
g_notify_data.indicate_ongoing = 0;
}
}
static int event_char_write(ble_event_en event, void *event_data)
{
evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
int16_t handle_offset = 0;
static int w_len = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
printf("event_char_write conn_handle %d char_handle %d len %d offset %d\n",
e->conn_handle, e->char_handle, e->len, e->offset);
hexdump(e->data, e->len);
if (test_svc.conn_handle == e->conn_handle) {
switch (handle_offset) {
case TEST_IDX_CHAR3_VAL:
if (e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST_IDX_CHAR5_VAL:
if (e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST_IDX_CHAR4_VAL:
case TEST_IDX_CHAR7_VAL:
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST_IDX_CHAR3_CUD:
if (e->offset + e->len > sizeof(test_svc.value3_cud)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3_cud + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3_cud)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3_cud));
break;
case TEST_IDX_CHAR6_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
if (e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
default:
e->len = 0;
break;
}
}
return 0;
}
static int event_char_read(ble_event_en event, void *event_data)
{
evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
if (test_svc.conn_handle == e->conn_handle) {
switch (handle_offset) {
case TEST_IDX_CHAR1_VAL:
e->data = (uint8_t *)test_svc.value1;
e->len = test_svc.mtu;
break;
case TEST_IDX_CHAR2_VAL:
e->data = (uint8_t *)test_svc.value2;
e->len = sizeof(test_svc.value1);
break;
case TEST_IDX_CHAR3_CUD:
e->data = (uint8_t *)test_svc.value3_cud;
e->len = sizeof(test_svc.value3_cud);
break;
case TEST_IDX_CHAR3_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST_IDX_CHAR5_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST_IDX_CHAR6_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST_IDX_CHAR7_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
default:
e->data = NULL;
e->len = 0;
break;
}
}
return 0;
}
static int event_gatt_indicate_confirm(ble_event_en event, void *event_data)
{
evt_data_gatt_indicate_cb_t *e = event_data;
if (e->err) {
printf("indicate fail, err %d\n", e->err);
} else {
printf("indicate char %d success\n", e->char_handle);
}
g_notify_data.indicate_ongoing = 0;
return 0;
}
struct k_delayed_work notify_work = {0};
void notify_action(struct k_work *work)
{
uint8_t data[2] = {1, 2};
if (g_notify_data.notify_type == CCC_VALUE_NOTIFY) {
ble_stack_gatt_notificate(g_bt_conn_handle, g_notify_data.notify_handle, data, 2);
k_delayed_work_submit(¬ify_work, 2000);
} else if (g_notify_data.notify_type == CCC_VALUE_INDICATE) {
if (!g_notify_data.indicate_ongoing) {
g_notify_data.indicate_ongoing = 1;
ble_stack_gatt_indicate(g_bt_conn_handle, g_notify_data.notify_handle, data, 2);
k_delayed_work_submit(¬ify_work, 2000);
}
}
}
static int event_char_ccc_change(ble_event_en event, void *event_data)
{
evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data;
uint16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
if (notify_work.work.handler == NULL) {
k_delayed_work_init(¬ify_work, notify_action);
}
if (handle_offset == TEST_IDX_CHAR3_CCC) {
test_svc.ccc = e->ccc_value;
printf("ccc handle %d change %d\n", e->char_handle, test_svc.ccc);
g_notify_data.notify_handle = e->char_handle - 2;
if (test_svc.ccc == CCC_VALUE_NOTIFY) {
g_notify_data.notify_type = CCC_VALUE_NOTIFY;
k_delayed_work_submit(¬ify_work, 2000);
} else if (test_svc.ccc == CCC_VALUE_INDICATE) {
g_notify_data.notify_type = CCC_VALUE_INDICATE;
k_delayed_work_submit(¬ify_work, 2000);
} else {
g_notify_data.notify_type = 0;
}
}
return 0;
}
static int test_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GAP_CONN_CHANGE:
conn_change(event, event_data);
break;
case EVENT_GATT_CHAR_READ:
event_char_read(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE:
event_char_write(event, event_data);
break;
case EVENT_GATT_CHAR_CCC_CHANGE:
event_char_ccc_change(event, event_data);
break;
#if defined(CONFIG_BT_GATT_CLIENT)
case EVENT_GATT_DISCOVERY_SVC:
case EVENT_GATT_DISCOVERY_INC_SVC:
case EVENT_GATT_DISCOVERY_CHAR:
case EVENT_GATT_DISCOVERY_CHAR_DES:
event_gatt_discovery(event, event_data);
break;
case EVENT_GATT_CHAR_READ_CB:
event_gatt_read_cb(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE_CB:
event_gatt_write_cb(event, event_data);
break;
case EVENT_GATT_NOTIFY:
event_gatt_notify(event, event_data);
break;
case EVENT_GATT_INDICATE_CB:
event_gatt_indicate_confirm(event, event_data);
break;
case EVENT_GATT_MTU_EXCHANGE:
event_gatt_mtu_exchange(event, event_data);
break;
#endif
default:
break;
}
return 0;
}
static ble_event_cb_t ble_cb1 = {
.callback = test_event_callback,
};
static int event2_char_write(ble_event_en event, void *event_data)
{
evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
int16_t handle_offset = 0;
static int w_len = 0;
static int w_len2 = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc2_handle, TEST2_IDX_MAX, e->char_handle, handle_offset);
printf("event_char_write conn_handle %d char_handle %d len %d offset %d\n",
e->conn_handle, e->char_handle, e->len, e->offset);
hexdump(e->data, e->len);
switch (handle_offset) {
case TEST2_IDX_CHAR3_VAL:
if (e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST2_IDX_CHAR4_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST2_IDX_CHAR5_VAL:
if (e->flag) {
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST2_IDX_CHAR6_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len2 = 0;
}
w_len2 += e->len;
e->len = 0;
return 0;
}
if (w_len2 > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len2 = 0;
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
default:
e->len = 0;
break;
}
return 0;
}
static int event2_char_read(ble_event_en event, void *event_data)
{
evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc2_handle, TEST2_IDX_MAX, e->char_handle, handle_offset);
switch (handle_offset) {
case TEST2_IDX_CHAR1_VAL:
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
e->data = (uint8_t *)test_svc.value1;
e->len = sizeof(test_svc.value1);
break;
case TEST2_IDX_CHAR2_VAL:
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
e->data = (uint8_t *)test_svc.value2;
e->len = sizeof(test_svc.value2);
break;
case TEST2_IDX_CHAR3_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST2_IDX_CHAR4_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST2_IDX_CHAR5_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST2_IDX_CHAR6_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
default:
e->data = NULL;
e->len = 0;
break;
}
return 0;
}
static int test2_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GATT_CHAR_READ:
event2_char_read(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE:
event2_char_write(event, event_data);
break;
default:
break;
}
return 0;
}
void test3_start_adv(void)
{
ad_data_t ad[2] = {0};
uint8_t flag = AD_FLAG_GENERAL | AD_FLAG_NO_BREDR;
ad[0].type = AD_DATA_TYPE_FLAGS;
ad[0].data = (uint8_t *)&flag;
ad[0].len = 1;
ad[1].type = AD_DATA_TYPE_NAME_COMPLETE;
ad[1].data = (uint8_t *)"TEST";
ad[1].len = strlen("TEST");
adv_param_t param = {
ADV_IND,
ad,
NULL,
BLE_ARRAY_NUM(ad),
0,
ADV_FAST_INT_MIN_1,
ADV_FAST_INT_MAX_1,
};
int ret = ble_stack_adv_start(¶m);
if (ret) {
test3_svc.fail_count++;
printf("adv start fail %d!\n", ret);
} else {
printf("adv start!\n");
}
}
static ble_event_cb_t ble_cb2 = {
.callback = test2_event_callback,
};
static int data_check(uint8_t *data, uint16_t len)
{
int i = 1;
while (i < len && data[i] == i) {
i++;
};
return (i == len);
}
static int event3_char_write(ble_event_en event, void *event_data)
{
int ret;
evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test3_svc.svc_handle, TEST3_IDX_MAX, e->char_handle, handle_offset);
//printf("event_char_write conn_handle %d char_handle %d len %d offset %d\n",
// e->conn_handle, e->char_handle, e->len, e->offset);
//hexdump(e->data, e->len);
switch (handle_offset) {
case TEST3_IDX_RX_VAL:
memcpy(test3_svc.rx_buf + e->offset, e->data, BLE_MIN(e->len, sizeof(test3_svc.rx_buf)));
e->len = BLE_MIN(e->len, sizeof(test3_svc.rx_buf));
test3_svc.rx_count++;
if (data_check(test3_svc.rx_buf, BLE_MIN(e->len, sizeof(test3_svc.rx_buf)))) {
test3_svc.trans_data += e->len;
} else {
test3_svc.missmatch_count++;
}
if (test3_svc.mode == 0) {
if (test3_svc.svc_tx_mode) {
if (test3_svc.ccc == CCC_VALUE_INDICATE) {
ret = ble_stack_gatt_indicate(test3_svc.conn_handle, test3_svc.svc_handle + TEST3_IDX_TX_VAL, test3_svc.rx_buf, e->len);
if (ret) {
test3_svc.fail_count++;
printf("indicate fail %d\n", ret);
return ret;
}
test3_svc.trans_data += e->len;
test3_svc.tx_count++;
} else {
test3_svc.fail_count++;
printf("indicate is disabled\n");
}
} else {
if (test3_svc.ccc == CCC_VALUE_NOTIFY) {
ret = ble_stack_gatt_notificate(test3_svc.conn_handle, test3_svc.svc_handle + TEST3_IDX_TX_VAL, test3_svc.rx_buf, e->len);
if (ret) {
test3_svc.fail_count++;
printf("nofify fail %d\n", ret);
return ret;
}
test3_svc.trans_data += e->len;
test3_svc.tx_count++;
} else {
test3_svc.fail_count++;
printf("nofify is disabled\n");
}
}
}
break;
default:
e->len = 0;
break;
}
return 0;
}
static int event3_char_read(ble_event_en event, void *event_data)
{
evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test3_svc.svc_handle, TEST3_IDX_MAX, e->char_handle, handle_offset);
switch (handle_offset) {
case TEST3_IDX_RX_VAL:
e->data = (uint8_t *)test3_svc.rx_buf;
e->len = sizeof(test3_svc.rx_buf);
break;
default:
e->data = NULL;
e->len = 0;
break;
}
return 0;
}
static int event3_ccc_change(ble_event_en event, void *event_data)
{
evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data;
test3_svc.ccc = e->ccc_value;
printf("CCC change %d\n", e->ccc_value);
return 0;
}
static void event3_conn_change(ble_event_en event, void *event_data)
{
evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data;
if (e->connected == CONNECTED) {
test3_svc.connect_count++;
test3_svc.conn_handle = e->conn_handle;
} else {
test3_svc.op = 0;
test3_svc.conn_handle = -1;
test3_svc.disconn_count++;
}
}
static void event3_indicate_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_indicate_cb_t *e = event_data;
if (e->char_handle == test3_svc.svc_handle + TEST3_IDX_TX_VAL) {
test3_svc.tx_cb_count++;
aos_sem_signal(&test3_svc.sync_sem);
}
}
static void event3_write_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_write_cb_t *e = event_data;
if (e->char_handle == test3_svc.svc_rx_handle) {
test3_svc.tx_cb_count++;
aos_sem_signal(&test3_svc.sync_sem);
}
}
static void event3_notify(ble_event_en event, void *event_data)
{
evt_data_gatt_notify_t *e = event_data;
//printf("event3_notify conn_handle %d char_handle %d len %d\n",
// e->conn_handle, e->char_handle, e->len);
//hexdump(e->data, e->len);
test3_svc.rx_count++;
if (data_check((uint8_t *)e->data, e->len)) {
test3_svc.trans_data += e->len;
} else {
test3_svc.missmatch_count++;
}
}
static void event3_mtu_change(ble_event_en event, void *event_data)
{
evt_data_gatt_mtu_exchange_t *e = event_data;
printf("mtu exchange %s, mtu %d\n", e->err ? "fail" : "success", ble_stack_gatt_mtu_get(e->conn_handle));
}
static int test3_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GAP_CONN_CHANGE:
event3_conn_change(event, event_data);
break;
case EVENT_GATT_CHAR_READ:
event3_char_read(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE:
event3_char_write(event, event_data);
break;
case EVENT_GATT_CHAR_CCC_CHANGE:
event3_ccc_change(event, event_data);
break;
case EVENT_GATT_INDICATE_CB:
event3_indicate_cb(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE_CB:
event3_write_cb(event, event_data);
break;
case EVENT_GATT_NOTIFY:
event3_notify(event, event_data);
break;
case EVENT_GATT_MTU_EXCHANGE:
event3_mtu_change(event, event_data);
break;
default:
break;
}
return 0;
}
static ble_event_cb_t ble_cb3 = {
.callback = test3_event_callback,
};
int cmd_gatt_register_test_svc(int argc, char *argv[])
{
int ret;
if (!strcmp(argv[0], "gatt-register-service")) {
ret = ble_stack_gatt_registe_service(&test_service, test_attrs, BLE_ARRAY_NUM(test_attrs));
if (ret < 0) {
printf("Registering test services faild (%d)\n", ret);
return ret;
}
test_svc.svc_handle = ret;
ret = ble_stack_event_register(&ble_cb1);
} else {
ret = ble_stack_gatt_registe_service(&test2_service, test2_attrs, BLE_ARRAY_NUM(test2_attrs));
if (ret < 0) {
printf("Registering test services faild (%d)\n", ret);
return ret;
}
test_svc.svc2_handle = ret;
ret = ble_stack_event_register(&ble_cb2);
}
if (ret) {
return ret;
}
printf("Registering test services\n");
return 0;
}
uint8_t test_data[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
static int gatt_indicate(const uint8_t *data, uint16_t len)
{
int ret = 0;
if (test3_svc.ccc == CCC_VALUE_INDICATE) {
ret = aos_sem_wait(&test3_svc.sync_sem, 10000);
if (ret) {
printf("indicate sem wait fail %d\n", ret);
return ret;
}
ret = ble_stack_gatt_indicate(test3_svc.conn_handle, test3_svc.svc_handle + TEST3_IDX_TX_VAL, data, len);
if (ret) {
test3_svc.fail_count++;
return ret;
}
test3_svc.trans_data += len;
} else {
ret = -1;
test3_svc.fail_count++;
printf("indicate is disabled\n");
}
return ret;
}
static int gatt_notification(const uint8_t *data, uint16_t len)
{
int ret = 0;
if (test3_svc.ccc == CCC_VALUE_NOTIFY) {
ret = ble_stack_gatt_notificate(test3_svc.conn_handle, test3_svc.svc_handle + TEST3_IDX_TX_VAL, data, len);
if (ret) {
return ret;
}
test3_svc.trans_data += len;
} else {
ret = -1;
printf("nofify is disabled\n");
}
return ret;
}
static int gatt_write(const uint8_t *data, uint16_t len)
{
int ret = 0;
ret = aos_sem_wait(&test3_svc.sync_sem, 1000);
if (ret) {
printf("write sem wait fail %d\n", ret);
return ret;
}
ret = ble_stack_gatt_write_response(test3_svc.conn_handle, test3_svc.svc_rx_handle, data, len, 0);
if (ret) {
return ret;
}
test3_svc.trans_data += len;
return ret;
}
static int gatt_write_no_response(const uint8_t *data, uint16_t len)
{
int ret = 0;
ret = ble_stack_gatt_write_no_response(test3_svc.conn_handle, test3_svc.svc_rx_handle, data, len, 0);
if (ret) {
return ret;
}
test3_svc.trans_data += len;
return ret;
}
typedef int (*gatt_send_func_t)(const uint8_t *data, uint16_t len);
gatt_send_func_t gatt_send_func_table[2][2] = {
{gatt_notification, gatt_indicate},
{gatt_write, gatt_write_no_response}
};
static void transport_task(void *arg)
{
int ret;
uint32_t trans_start_time;
uint32_t trans_end_time;
printf("transport task start\n");
while (1) {
aos_sem_wait(&test3_svc.op_sem, AOS_WAIT_FOREVER);
trans_start_time = aos_now_ms();
if (test3_svc.op == 1) {
gatt_send_func_t send_func;
if (test3_svc.type == 0) {
send_func = gatt_send_func_table[test3_svc.type][test3_svc.svc_tx_mode];
} else {
send_func = gatt_send_func_table[test3_svc.type][test3_svc.cli_tx_mode];
}
uint32_t count = test3_svc.data_len;
int mtu = ble_stack_gatt_mtu_get(test3_svc.conn_handle) - 3;
int i = 0;
if (test3_svc.data_len == 0) {
count = 0xFFFFFFFF;
}
while (count) {
uint16_t send_count = mtu < count ? mtu : count;
test_data[0] = i;
ret = send_func(test_data, send_count);
if (ret == -ENOMEM) {
test3_svc.tx_retry_count++;
aos_msleep(1);
continue;
}
i++;
if (ret) {
test3_svc.fail_count++;
printf("send fail %d\n", ret);
}
count -= send_count;
test3_svc.tx_count++;
if (test3_svc.op == 0) {
printf("op stop\n");
break;
}
if (test3_svc.data_len == 0) {
count = 0xFFFFFFFF;
}
}
trans_end_time = aos_now_ms();
float speed = (test3_svc.data_len * 1000 / 1024) / (trans_end_time - trans_start_time);
printf("send %d complete in %d ms ,speed %f kB/s\n", test3_svc.data_len,trans_end_time - trans_start_time,speed);
}
}
}
static int gatt_transport_test_config(int argc, char *argv[])
{
int ret;
if (argc < 6) {
printf("params num err");
return -EINVAL;
}
if (!test3_svc.registed) {
memset(&test3_svc, 0, sizeof(test3_svc));
test3_svc.conn_handle = -1;
}
test3_svc.type = atoi(argv[0]);
test3_svc.mode = atoi(argv[1]);
test3_svc.svc_tx_mode = atoi(argv[2]);
test3_svc.svc_rx_handle = atoi(argv[3]);
test3_svc.cli_tx_mode = atoi(argv[4]);
test3_svc.data_len = atoi(argv[5]);
if (!test3_svc.registed) {
if (test3_svc.type == 0) {
if (test3_svc.svc_tx_mode) {
ret = ble_stack_gatt_registe_service(&test3_service, test3_attrs1, BLE_ARRAY_NUM(test3_attrs1));
} else {
ret = ble_stack_gatt_registe_service(&test3_service, test3_attrs0, BLE_ARRAY_NUM(test3_attrs0));
}
if (ret < 0) {
printf("Registering test services faild (%d)\n", ret);
return ret;
}
test3_svc.svc_handle = ret;
}
ret = ble_stack_event_register(&ble_cb3);
if (ret) {
return ret;
}
ret = aos_sem_new(&test3_svc.sync_sem, 1);
if (ret) {
return ret;
}
ret = aos_sem_new(&test3_svc.op_sem, 0);
if (ret) {
return ret;
}
ret = k_thread_spawn(&test3_svc.thread, "gatt test", transport_task_stack,
K_THREAD_STACK_SIZEOF(transport_task_stack),
transport_task, NULL, 30);
if (ret) {
return ret;
}
test3_svc.registed = 1;
}
printf("gatt-transport-test-config success!\n");
if (test3_svc.type == 0) {
printf("type:server mode:%s tx mode:%s data len:%d\n", test3_svc.mode ? "single" : "loop", test3_svc.svc_tx_mode ? "indicate" : "notify", test3_svc.data_len);
printf("use <ble adv conn> command to start advertising!\n");
} else {
printf("type:client mode:%s svc rx handle:0x%x tx mode: %s data len:%d\n",
test3_svc.mode ? "single" : "loop", test3_svc.svc_rx_handle,
test3_svc.cli_tx_mode ? "write without response" : "write",
test3_svc.data_len);
printf("use <ble connect> command to connect test device which in server mode!\n");
}
return 0;
}
static int gatt_transport_test_start()
{
if (test3_svc.conn_handle == -1) {
printf("Not Connected\n");
return -1;
}
test3_svc.op = 1;
aos_sem_signal(&test3_svc.op_sem);
return 0;
}
static int gatt_transport_test_show_result()
{
printf("TRANSPORT TEST REPORT:\n");
printf("Type : %s\n", test3_svc.type ? "Client" : "Server");
printf("Mode : %s\n", test3_svc.mode ? "Single" : "Loop");
if (test3_svc.type == 0) {
printf("TX mode : %s\n", test3_svc.svc_tx_mode ? "Indication" : "Notification");
} else {
printf("TX mode : %s\n", test3_svc.cli_tx_mode ? "Write without response" : "Write with response");
}
if (test3_svc.data_len) {
printf("Data Len : %d\n", test3_svc.data_len);
} else {
printf("Data Len : stream\n");
}
printf("Transport data amount : %d\n", test3_svc.trans_data);
printf("Transport missmatch : %d\n", test3_svc.missmatch_count);
printf("Transport tx count : %d\n", test3_svc.tx_count);
printf("Transport tx cb count : %d\n", test3_svc.tx_cb_count);
printf("Transport resend count: %d\n", test3_svc.tx_retry_count);
printf("Transport rx count : %d\n", test3_svc.rx_count);
printf("Transport fail count : %d\n", test3_svc.fail_count);
printf("Transport conn count : %d\n", test3_svc.connect_count);
printf("Transport discon count: %d\n", test3_svc.disconn_count);
return 0;
}
static int gatt_transport_test_op(int argc, char *argv[])
{
uint8_t op = 0xFF;
if (argc < 1) {
printf("params num err");
return -EINVAL;
}
op = atoi(argv[0]);
test3_svc.op = op;
if (op == 1) {
return gatt_transport_test_start();
} else if (op == 2) {
return gatt_transport_test_show_result();
} else if (op == 3) {
test3_svc.trans_data = 0;
test3_svc.fail_count = 0;
test3_svc.missmatch_count = 0;
test3_svc.tx_count = 0;
test3_svc.tx_cb_count = 0;
test3_svc.rx_count = 0;
test3_svc.tx_retry_count = 0;
}
return 0;
}
int cmd_gatt_transport_test(int argc, char *argv[])
{
if (!strcmp(argv[0], "gatt-transport-test-config")) {
return gatt_transport_test_config(argc - 1, &argv[1]);
} else if (!strcmp(argv[0], "gatt-transport-test-op")) {
return gatt_transport_test_op(argc - 1, &argv[1]);
}
return 0;
}
int cmd_gatt_unregister_test_svc(int argc, char *argv[])
{
printf("Unregistering test vendor services\n");
return 0;
}
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/gatt.c | C | apache-2.0 | 53,682 |
/** @file
@brief GATT shell functions
This is not to be included by the application.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __GATT_H
#define __GATT_H
int cmd_gatt_show_db(int argc, char *argv[]);
int cmd_gatt_exchange_mtu(int argc, char *argv[]);
int cmd_gatt_discover(int argc, char *argv[]);
int cmd_gatt_read_show_format(int argc, char *argv[]);
int cmd_gatt_read(int argc, char *argv[]);
int cmd_gatt_mread(int argc, char *argv[]);
int cmd_gatt_write(int argc, char *argv[]);
int cmd_gatt_write_without_rsp(int argc, char *argv[]);
int cmd_gatt_subscribe(int argc, char *argv[]);
int cmd_gatt_unsubscribe(int argc, char *argv[]);
int cmd_gatt_register_test_svc(int argc, char *argv[]);
int cmd_gatt_unregister_test_svc(int argc, char *argv[]);
int cmd_gatt_write_cmd_metrics(int argc, char *argv[]);
int cmd_gatt_transport_test(int argc, char *argv[]);
#endif /* __GATT_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/gatt.h | C | apache-2.0 | 948 |
/** @file
* @brief Bluetooth Link Layer functions
*
*/
/*
* Copyright (c) 2017 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdlib.h>
#include <string.h>
#include <zephyr.h>
#include <shell/shell.h>
#include <misc/printk.h>
#include <bluetooth/hci.h>
#include "../controller/include/ll.h"
#if defined(CONFIG_BT_CTLR_DTM)
#include "../controller/ll_sw/ll_test.h"
int cmd_test_tx(int argc, char *argv[])
{
u8_t chan, len, type, phy;
bt_u32_t err;
if (argc < 5) {
return -EINVAL;
}
chan = strtoul(argv[1], NULL, 16);
len = strtoul(argv[2], NULL, 16);
type = strtoul(argv[3], NULL, 16);
phy = strtoul(argv[4], NULL, 16);
err = ll_test_tx(chan, len, type, phy);
if (err) {
return -EINVAL;
}
printk("test_tx...\n");
return 0;
}
int cmd_test_rx(int argc, char *argv[])
{
u8_t chan, phy, mod_idx;
bt_u32_t err;
if (argc < 4) {
return -EINVAL;
}
chan = strtoul(argv[1], NULL, 16);
phy = strtoul(argv[2], NULL, 16);
mod_idx = strtoul(argv[3], NULL, 16);
err = ll_test_rx(chan, phy, mod_idx);
if (err) {
return -EINVAL;
}
printk("test_rx...\n");
return 0;
}
int cmd_test_end(int argc, char *argv[])
{
u16_t num_rx;
bt_u32_t err;
err = ll_test_end(&num_rx);
if (err) {
return -EINVAL;
}
printk("num_rx= %u.\n", num_rx);
return 0;
}
#endif /* CONFIG_BT_CTLR_DTM */
#if defined(CONFIG_BT_CTLR_ADV_EXT)
#define ADV_INTERVAL 0x000020
#define ADV_TYPE 0x05 /* Adv. Ext. */
#define OWN_ADDR_TYPE 1
#define PEER_ADDR_TYPE 0
#define PEER_ADDR NULL
#define ADV_CHAN_MAP 0x07
#define FILTER_POLICY 0x00
#define ADV_TX_PWR NULL
#define ADV_SEC_SKIP 0
#define ADV_PHY_S 0x01
#define ADV_SID 0
#define SCAN_REQ_NOT 0
#define SCAN_INTERVAL 0x0004
#define SCAN_WINDOW 0x0004
#define SCAN_OWN_ADDR_TYPE 1
#define SCAN_FILTER_POLICY 0
int cmd_advx(int argc, char *argv[])
{
u16_t evt_prop;
u8_t enable;
u8_t phy_p;
bt_s32_t err;
if (argc < 2) {
return -EINVAL;
}
if (argc > 1) {
if (!strcmp(argv[1], "on")) {
evt_prop = 0;
enable = 1;
} else if (!strcmp(argv[1], "off")) {
enable = 0;
goto disable;
} else {
return -EINVAL;
}
}
phy_p = BIT(0);
if (argc > 2) {
if (!strcmp(argv[2], "coded")) {
phy_p = BIT(2);
} else if (!strcmp(argv[2], "anon")) {
evt_prop |= BIT(5);
} else if (!strcmp(argv[2], "txp")) {
evt_prop |= BIT(6);
} else {
return -EINVAL;
}
}
if (argc > 3) {
if (!strcmp(argv[3], "anon")) {
evt_prop |= BIT(5);
} else if (!strcmp(argv[3], "txp")) {
evt_prop |= BIT(6);
} else {
return -EINVAL;
}
}
if (argc > 4) {
if (!strcmp(argv[4], "txp")) {
evt_prop |= BIT(6);
} else {
return -EINVAL;
}
}
printk("adv param set...");
err = ll_adv_params_set(0x00, evt_prop, ADV_INTERVAL, ADV_TYPE,
OWN_ADDR_TYPE, PEER_ADDR_TYPE, PEER_ADDR,
ADV_CHAN_MAP, FILTER_POLICY, ADV_TX_PWR,
phy_p, ADV_SEC_SKIP, ADV_PHY_S, ADV_SID,
SCAN_REQ_NOT);
if (err) {
goto exit;
}
disable:
printk("adv enable (%u)...", enable);
err = ll_adv_enable(enable);
if (err) {
goto exit;
}
exit:
printk("done (err= %d).\n", err);
return 0;
}
int cmd_scanx(int argc, char *argv[])
{
u8_t type = 0;
u8_t enable;
bt_s32_t err;
if (argc < 2) {
return -EINVAL;
}
if (argc > 1) {
if (!strcmp(argv[1], "on")) {
enable = 1;
type = 1;
} else if (!strcmp(argv[1], "passive")) {
enable = 1;
type = 0;
} else if (!strcmp(argv[1], "off")) {
enable = 0;
goto disable;
} else {
return -EINVAL;
}
}
type |= BIT(1);
if (argc > 2) {
if (!strcmp(argv[2], "coded")) {
type &= BIT(0);
type |= BIT(3);
} else {
return -EINVAL;
}
}
printk("scan param set...");
err = ll_scan_params_set(type, SCAN_INTERVAL, SCAN_WINDOW,
SCAN_OWN_ADDR_TYPE, SCAN_FILTER_POLICY);
if (err) {
goto exit;
}
disable:
printk("scan enable (%u)...", enable);
err = ll_scan_enable(enable);
if (err) {
goto exit;
}
exit:
printk("done (err= %d).\n", err);
return 0;
}
#endif /* CONFIG_BT_CTLR_ADV_EXT */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/ll.c | C | apache-2.0 | 4,026 |
/** @file
* @brief Bluetooth Link Layer shell functions
*
* This is not to be included by the application.
*/
/*
* Copyright (c) 2017 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __LL_H
#define __LL_H
int cmd_advx(int argc, char *argv[]);
int cmd_scanx(int argc, char *argv[]);
int cmd_test_tx(int argc, char *argv[]);
int cmd_test_rx(int argc, char *argv[]);
int cmd_test_end(int argc, char *argv[]);
#endif /* __LL_H */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/ll.h | C | apache-2.0 | 466 |
#include <aos/kernel.h>
#include <stddef.h>
/*
#define ASSERT(expr) \
(expr?0: printf("ASSERTION Failed %s: %d\n", __FILE__,__LINE__))
#define TEST_ASSERT_EQUAL(a,b) ASSERT(a==b)
#define TEST_ASSERT_NOT_EQUAL(a,b) ASSERT(a!=b)
#define TEST_ASSERT(expr) ASSERT(expr)
#define TEST_ASSERT_TRUE(expr) ASSERT(expr)
#define TEST_ASSERT_FALSE(expr) ASSERT(!(expr))
#define ASSERT_STRING(a, b ,c) \
if(memcmp(a,b,c) != 0) { \
printf("ASSERTION Failed %s: %d\n", __FILE__,__LINE__); \
}
#define ASSERT_STRING_FALSE(a, b ,c) \
if(memcmp(a,b,c) == 0) { \
printf("ASSERTION Failed %s: %d\n", __FILE__,__LINE__); \
}
*/
#define TEST_ASSERT_EQUAL(a,b,fail_q,args...) \
if( a!= b) {\
printf("ASSERTION Failed %s: %d", __FILE__,__LINE__); \
printf(" >>> "args); \
printf("\n"); \
printf("Expected value is %d, actual value is %d\n", a, b); \
if (fail_q == 1) { \
fail_count++; \
} \
}
#define TEST_ASSERT_NOT_EQUAL(a,b,fail_q,args...) \
if( a== b) {\
printf("ASSERTION Failed %s: %d", __FILE__,__LINE__); \
printf(" >>> "args); \
printf("\n"); \
printf("NOT Expected value is %d, but actual value is %d\n", a, b); \
if (fail_q == 1) { \
fail_count++; \
} \
}
#define ASSERT_NULL(a,fail_q,args...) \
if( a != NULL) {\
printf("ASSERTION Failed %s: %d", __FILE__,__LINE__); \
printf(" >>> "args); \
printf("\n"); \
printf("Expected value is NULL, but actual value is %p\n", a); \
if (fail_q == 1) { \
fail_count++; \
} \
}
#define ASSERT_NOT_NULL(a,fail_q,args...) \
if( a == NULL) {\
printf("ASSERTION Failed %s: %d", __FILE__,__LINE__); \
printf(" >>> "args); \
printf("\n"); \
printf("Expected value is NULL, but actual value is %p\n", a); \
if (fail_q == 1) { \
fail_count++; \
} \
}
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/test/app_test.h | C | apache-2.0 | 2,041 |
/** @file
* @brief Bluetooth shell module
*
* Provide some Bluetooth shell commands that can be useful to applications.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <bt_errno.h>
#include <ble_types/types.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <misc/byteorder.h>
#include <zephyr.h>
#include <settings/settings.h>
#include <bluetooth/hci.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/sdp.h>
#include <aos/ble.h>
#include <common/log.h>
#include <conn_internal.h>
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
// #include <yoc/hrs.h>
/** @brief Callback called when command is entered.
*
* @param argc Number of parameters passed.
* @param argv Array of option strings. First option is always command name.
*
* @return 0 in case of success or negative value in case of error.
*/
typedef int (*shell_cmd_function_t)(int argc, char *argv[]);
struct shell_cmd {
const char *cmd_name;
shell_cmd_function_t cb;
const char *help;
const char *desc;
};
#include "bt.h"
#include "gatt.h"
#include "ll.h"
#include <app_test.h>
#define DEVICE_NAME CONFIG_BT_DEVICE_NAME
#define DEVICE_NAME_LEN (sizeof(DEVICE_NAME) - 1)
#define CREDITS 10
#define DATA_MTU (23 * CREDITS)
#define DATA_BREDR_MTU 48
int fail_count = 0;
//int16_t g_yoc_uart_handle = -1;
static u8_t selected_id = BT_ID_DEFAULT;
#if defined(CONFIG_BT_CONN)
struct bt_conn *default_conn;
int16_t g_bt_conn_handle = -1;
int16_t g_security_level = 0;
extern int16_t g_handle;
/* Connection context for BR/EDR legacy pairing in sec mode 3 */
static int16_t g_pairing_handle = -1;
#endif /* CONFIG_BT_CONN */
static void device_find(ble_event_en event, void *event_data);
#if defined(CONFIG_BT_SMP)
static void smp_event(ble_event_en event, void *event_data);
#endif
static void conn_param_req(ble_event_en event, void *event_data);
static void conn_param_update(ble_event_en event, void *event_data);
#define L2CAP_DYM_CHANNEL_NUM 2
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
NET_BUF_POOL_DEFINE(data_tx_pool, L2CAP_DYM_CHANNEL_NUM, DATA_MTU, BT_BUF_USER_DATA_MIN, NULL);
NET_BUF_POOL_DEFINE(data_rx_pool, L2CAP_DYM_CHANNEL_NUM, DATA_MTU, BT_BUF_USER_DATA_MIN, NULL);
#endif
#if defined(CONFIG_BT_BREDR)
NET_BUF_POOL_DEFINE(data_bredr_pool, 1, DATA_BREDR_MTU, BT_BUF_USER_DATA_MIN,
NULL);
#define SDP_CLIENT_USER_BUF_LEN 512
NET_BUF_POOL_DEFINE(sdp_client_pool, CONFIG_BT_MAX_CONN,
SDP_CLIENT_USER_BUF_LEN, BT_BUF_USER_DATA_MIN, NULL);
#endif /* CONFIG_BT_BREDR */
#if defined(CONFIG_BT_RFCOMM)
static struct bt_sdp_attribute spp_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_SERIAL_PORT_SVCLASS)
},
)
),
BT_SDP_LIST(
BT_SDP_ATTR_PROTO_DESC_LIST,
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 12),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 3),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
BT_SDP_ARRAY_16(BT_SDP_PROTO_L2CAP)
},
)
},
{
BT_SDP_TYPE_SIZE_VAR(BT_SDP_SEQ8, 5),
BT_SDP_DATA_ELEM_LIST(
{
BT_SDP_TYPE_SIZE(BT_SDP_UUID16),
BT_SDP_ARRAY_16(BT_SDP_PROTO_RFCOMM)
},
{
BT_SDP_TYPE_SIZE(BT_SDP_UINT8),
BT_SDP_ARRAY_8(BT_RFCOMM_CHAN_SPP)
},
)
},
)
),
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_SERIAL_PORT_SVCLASS)
},
{
BT_SDP_TYPE_SIZE(BT_SDP_UINT16),
BT_SDP_ARRAY_16(0x0102)
},
)
},
)
),
BT_SDP_SERVICE_NAME("Serial Port"),
};
static struct bt_sdp_record spp_rec = BT_SDP_RECORD(spp_attrs);
#endif /* CONFIG_BT_RFCOMM */
#define NAME_LEN 30
static char *addr_le_str(const bt_addr_le_t *addr)
{
static char bufs[2][27];
static u8_t cur;
char *str;
str = bufs[cur++];
cur %= ARRAY_SIZE(bufs);
bt_addr_le_to_str(addr, str, sizeof(bufs[cur]));
return str;
}
static uint8_t char2u8(char c)
{
if (c >= '0' && c <= '9') {
return (c - '0');
} else if (c >= 'a' && c <= 'f') {
return (c - 'a' + 10);
} else if (c >= 'A' && c <= 'F') {
return (c - 'A' + 10);
} else {
return 0;
}
}
void str2hex(uint8_t hex[], char *s, uint8_t cnt)
{
uint8_t i;
if (!s) {
return;
}
for (i = 0; (*s != '\0') && (i < cnt); i++, s += 2) {
hex[i] = ((char2u8(*s) & 0x0f) << 4) | ((char2u8(*(s + 1))) & 0x0f);
}
}
static inline int bt_addr2str(const dev_addr_t *addr, char *str,
uint16_t len)
{
char type[10];
switch (addr->type) {
case BT_ADDR_LE_PUBLIC:
strcpy(type, "public");
break;
case BT_ADDR_LE_RANDOM:
strcpy(type, "random");
break;
default:
snprintf(type, sizeof(type), "0x%02x", addr->type);
break;
}
return snprintf(str, len, "%02X:%02X:%02X:%02X:%02X:%02X (%s)",
addr->val[5], addr->val[4], addr->val[3],
addr->val[2], addr->val[1], addr->val[0], type);
}
static int chars2hex(const char *c, u8_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 -EINVAL;
}
return 0;
}
static int str2bt_addr(const char *str, dev_addr_t *addr)
{
int i, j;
u8_t tmp;
if (strlen(str) != 17) {
return -EINVAL;
}
for (i = 5, j = 1; *str != '\0'; str++, j++) {
if (!(j % 3) && (*str != ':')) {
return -EINVAL;
} else if (*str == ':') {
i--;
continue;
}
addr->val[i] = addr->val[i] << 4;
if (chars2hex(str, &tmp) < 0) {
return -EINVAL;
}
addr->val[i] |= tmp;
}
return 0;
}
static int str2bt_addr_le(const char *str, const char *type, dev_addr_t *addr)
{
int err;
err = str2bt_addr(str, addr);
if (err < 0) {
return err;
}
if (!strcmp(type, "public") || !strcmp(type, "(public)")) {
addr->type = DEV_ADDR_LE_PUBLIC;
} else if (!strcmp(type, "random") || !strcmp(type, "(random)")) {
addr->type = DEV_ADDR_LE_RANDOM;
} else {
return -EINVAL;
}
return 0;
}
static void conn_change(ble_event_en event, void *event_data)
{
int only_one = 1;
evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data;
connect_info_t info;
if (only_one) {
int ret;
printf("******* test ble_stack_connect_info_get start ******\n");
ret = ble_stack_connect_info_get(e->conn_handle, &info);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_connect_info_get fail");
if (ret == 0) {
printf("********conn get info.role=%d\n", info.role);
printf("********conn get info.interval=%d\n", info.interval);
}
printf("info.local_addr.val[]=");
for (int i = 0; i < 6; i++) {
printf("%x:", info.local_addr.val[i]);
}
printf("\n");
printf("info.peer_addr.val[]=");
for (int i = 0; i < 6; i++) {
printf("%x:", info.peer_addr.val[i]);
}
printf("\n");
ret = ble_stack_connect_info_get(e->conn_handle, NULL);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_connect_info_get fail");
ret = ble_stack_connect_info_get(-1, &info);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_connect_info_get fail");
printf("******* test ble_stack_connect_info_get end ******\n");
only_one = 0;
}
ble_stack_connect_info_get(e->conn_handle, &info);
if (e->connected == CONNECTED && e->err == 0) {
printf("Connected (%d): %s\n", e->conn_handle, addr_le_str((bt_addr_le_t *)&info.peer_addr));
if (g_bt_conn_handle == -1) {
g_bt_conn_handle = e->conn_handle;
}
/* clear connection reference for sec mode 3 pairing */
if (g_pairing_handle != -1) {
g_pairing_handle = -1;
}
} else {
printf("Disconected (%d): %s err %d\n", e->conn_handle, addr_le_str((bt_addr_le_t *)&info.peer_addr), e->err);
if (e->err == 31) {
while (1);
}
if (g_bt_conn_handle == e->conn_handle) {
g_bt_conn_handle = -1;
}
g_security_level = 0;
}
}
static void conn_security_change(ble_event_en event, void *event_data)
{
evt_data_gap_security_change_t *e = (evt_data_gap_security_change_t *)event_data;
printf("conn %d security level change to level%d\n", e->conn_handle, e->level);
g_security_level = e->level;
}
//int16_t g_tx_ccc_value = 0;
//static void event_char_ccc_change(ble_event_en event, void *event_data)
//{
// evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data;
// g_tx_ccc_value = e->ccc_value;
//}
//void event_char_write(ble_event_en event, void *event_data)
//{
// evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
// int16_t hande_offset = 0;
//
// if (g_conn_hanlde == e->conn_handle) {
// if (e->char_handle > g_yoc_uart_handle) {
// hande_offset = e->char_handle - g_yoc_uart_handle;
// } else {
// return;
// }
//
// switch (hande_offset) {
// case YOC_UART_IDX_RX_VAL:
// memcpy(rx_buf, e->data, MIN(e->len, sizeof(rx_buf)));
// e->len = MIN(e->len, sizeof(rx_buf));
// rx_buf[e->len] = '\0';
// LOGI(TAG, "recv (%d) data:%s\n", e->len, rx_buf);
//
// memcpy(tx_buf, rx_buf, sizeof(rx_buf));
// return;
// }
// }
//
// e->len = 0;
// return;
//}
//void event_char_read(ble_event_en event, void *event_data)
//{
// evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
// int16_t hande_offset = 0;
//
// if (g_conn_hanlde == e->conn_handle) {
// if (e->char_handle > g_yoc_uart_handle) {
// hande_offset = e->char_handle - g_yoc_uart_handle;
// } else {
// return;
// }
//
// switch (hande_offset) {
// case YOC_UART_IDX_RX_VAL:
// memcpy(e->data, rx_buf, MIN(e->len, sizeof(rx_buf)));
// e->len = MIN(e->len, sizeof(rx_buf));
// return;
//
// case YOC_UART_IDX_TX_VAL:
// memcpy(e->data, tx_buf, MIN(e->len, sizeof(tx_buf)));
// e->len = MIN(e->len, sizeof(tx_buf));
// return;
//
// case YOC_UART_IDX_RX_DES:
// memcpy(e->data, rx_char_des, MIN(e->len, strlen(rx_char_des)));
// e->len = MIN(e->len, strlen(rx_char_des));
// return;
//
// case YOC_UART_IDX_TX_DES:
// memcpy(e->data, tx_char_des, MIN(e->len, strlen(tx_char_des)));
// e->len = MIN(e->len, strlen(tx_char_des));
// return;
// }
// }
//
// e->len = 0;
// return;
//}
static int event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GAP_CONN_CHANGE:
conn_change(event, event_data);
break;
case EVENT_GAP_CONN_SECURITY_CHANGE:
conn_security_change(event, event_data);
break;
//case EVENT_GATT_CHAR_CCC_CHANGE:
// event_char_ccc_change(event, event_data);
// break;
//case EVENT_GATT_CHAR_WRITE:
// event_char_write(event, event_data);
// break;
//case EVENT_GATT_CHAR_READ:
// event_char_read(event, event_data);
// break;
case EVENT_GAP_DEV_FIND:
device_find(event, event_data);
break;
case EVENT_GAP_CONN_PARAM_REQ:
conn_param_req(event, event_data);
break;
case EVENT_GAP_CONN_PARAM_UPDATE:
conn_param_update(event, event_data);
break;
#if defined(CONFIG_BT_SMP)
case EVENT_SMP_PASSKEY_DISPLAY:
case EVENT_SMP_PASSKEY_CONFIRM:
case EVENT_SMP_PASSKEY_ENTER:
case EVENT_SMP_PAIRING_CONFIRM:
case EVENT_SMP_PAIRING_COMPLETE:
case EVENT_SMP_CANCEL:
smp_event(event, event_data);
break;
#endif
default:
//printf("Unhandle event %d\n", event);
break;
}
return 0;
}
static ble_event_cb_t ble_cb = {
.callback = event_callback,
};
static int cmd_init(int argc, char *argv[])
{
if (!strcmp(argv[1], "test")) {
fail_count = 0;
int err;
#define DEV_ADDR {0xCC,0x3B,0xE3,0x82,0xBA,0xC0}
#define DEV_NAME "BLE_INIT"
init_param_t init = {NULL, NULL, 1};
dev_addr_t addr2 = {DEV_ADDR_LE_RANDOM, DEV_ADDR};
init_param_t demo = {
.dev_name = DEV_NAME,
.dev_addr = &addr2,
.conn_num_max = 1,
};
//param = NULL
err = ble_stack_init(NULL);
TEST_ASSERT_EQUAL(-1, err, 1, "ble_stack_init param=NULL fail");
//dev_name = NULL.设备的名称为NULL
init.dev_addr = &addr2;
err = ble_stack_init(&init);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack_init param.dev_name=NULL fail");
//dev_addr = NULL
init.dev_name = DEV_NAME;
init.dev_addr = NULL;
err = ble_stack_init(&init);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack_init param.dev_addr=NULL fail");
//最大连接数为0
init.dev_addr = &addr2;
init.conn_num_max = 0;
err = ble_stack_init(&init);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack_init conn_num_max=0 fail");
//测试设备的type
for (int i = 0; i < 4; i++) {
addr2.type = i;
demo.dev_addr = &addr2;
err = ble_stack_init(&demo);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack_init dev_addr->type fail");
}
//测试设备的最大连接数
addr2.type = DEV_ADDR_LE_RANDOM;
demo.dev_addr = &addr2;
demo.conn_num_max = 65535;
err = ble_stack_init(&demo);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack init conn_num_max=65535 fail");
if (fail_count == 0) {
printf("BLE_INIT TEST PASS\n");
} else {
fail_count = 0;
printf("BLE_INIT TEST FAILED\n");
}
return 0;
} else {
int err;
fail_count = 0;
dev_addr_t addr;
init_param_t init = {NULL, NULL, 1};
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
NET_BUF_POOL_INIT(data_tx_pool);
NET_BUF_POOL_INIT(data_rx_pool);
#endif
#if defined(CONFIG_BT_BREDR)
NET_BUF_POOL_INIT(data_bredr_pool);
NET_BUF_POOL_INIT(sdp_client_pool);
#endif /* CONFIG_BT_BREDR */
if (argc == 3) {
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid address\n");
return err;
}
init.dev_addr = &addr;
}
err = ble_stack_init(&init);
if (err) {
printf("Bluetooth init failed (err %d)\n", err);
return err;
}
err = ble_stack_setting_load();
if (err) {
printf("Bluetooth load failed (err %d)\n", err);
return err;
}
err = ble_stack_event_register(NULL);
TEST_ASSERT_EQUAL(-1, err, 1, "ble_stack event_register fail");
err = ble_stack_event_register(&ble_cb);
TEST_ASSERT_EQUAL(0, err, 1, "ble_stack_event_register fail");
if (err == 0) {
printf("Bluetooth stack init success\n");
}
if (fail_count == 0) {
printf("BLE_INIT TEST PASS\n");
} else {
fail_count = 0;
printf("BLE_INIT TEST FAILED\n");
}
return 0;
}
}
#if defined(CONFIG_BT_HCI) || defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
void hexdump(const u8_t *data, size_t len)
{
int n = 0;
while (len--) {
if (n % 16 == 0) {
printf("%08X ", n);
}
printf("%02X ", *data++);
n++;
if (n % 8 == 0) {
if (n % 16 == 0) {
printf("\n");
} else {
printf(" ");
}
}
}
if (n % 16) {
printf("\n");
}
}
#endif /* CONFIG_BT_HCI || CONFIG_BT_L2CAP_DYNAMIC_CHANNEL */
#if defined(CONFIG_BT_HCI)
static int cmd_hci_cmd(int argc, char *argv[])
{
u8_t ogf;
u16_t ocf;
struct net_buf *buf = NULL, *rsp;
int err;
if (argc < 3) {
return -EINVAL;
}
ogf = strtoul(argv[1], NULL, 16);
ocf = strtoul(argv[2], NULL, 16);
if (argc > 3) {
int i;
buf = bt_hci_cmd_create(BT_OP(ogf, ocf), argc - 3);
for (i = 3; i < argc; i++) {
net_buf_add_u8(buf, strtoul(argv[i], NULL, 16));
}
}
err = bt_hci_cmd_send_sync(BT_OP(ogf, ocf), buf, &rsp);
if (err) {
printf("HCI command failed (err %d)\n", err);
} else {
hexdump(rsp->data, rsp->len);
net_buf_unref(rsp);
}
return 0;
}
#endif /* CONFIG_BT_HCI */
static int cmd_name(int argc, char *argv[])
{
int err;
if (argc < 2) {
printf("Bluetooth Local Name: %s\n", bt_get_name());
return 0;
}
err = bt_set_name(argv[1]);
if (err) {
printf("Unable to set name %s (err %d)", argv[1], err);
}
return 0;
}
static int cmd_id_create(int argc, char *argv[])
{
dev_addr_t addr;
int err;
if (argc > 1) {
err = str2bt_addr_le(argv[1], "random", &addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
bt_addr_le_copy((bt_addr_le_t *)&addr, BT_ADDR_LE_ANY);
}
err = bt_id_create((bt_addr_le_t *)&addr, NULL);
if (err < 0) {
printf("Creating new ID failed (err %d)\n", err);
return 0;
}
printf("New identity (%d) created: %s\n", err, addr_le_str((bt_addr_le_t *)&addr));
return 0;
}
static int cmd_id_reset(int argc, char *argv[])
{
bt_addr_le_t addr;
u8_t id;
int err;
if (argc < 2) {
printf("Identity identifier not specified\n");
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
if (argc > 2) {
err = str2bt_addr_le(argv[2], "random", (dev_addr_t *)&addr);
if (err) {
printf("Invalid address\n");
return err;
}
} else {
bt_addr_le_copy(&addr, BT_ADDR_LE_ANY);
}
err = bt_id_reset(id, &addr, NULL);
if (err < 0) {
printf("Resetting ID %u failed (err %d)\n", id, err);
return 0;
}
printf("Identity %u reset: %s\n", id, addr_le_str(&addr));
return 0;
}
static int cmd_id_delete(int argc, char *argv[])
{
u8_t id;
int err;
if (argc < 2) {
printf("Identity identifier not specified\n");
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
err = bt_id_delete(id);
if (err < 0) {
printf("Deleting ID %u failed (err %d)\n", id, err);
return 0;
}
printf("Identity %u deleted\n", id);
return 0;
}
static int cmd_id_show(int argc, char *argv[])
{
bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
size_t i, count = CONFIG_BT_ID_MAX;
bt_id_get(addrs, &count);
for (i = 0; i < count; i++) {
printf("%s%zu: %s\n", i == selected_id ? "*" : " ", i,
addr_le_str(&addrs[i]));
}
return 0;
}
static int cmd_id_select(int argc, char *argv[])
{
bt_addr_le_t addrs[CONFIG_BT_ID_MAX];
size_t count = CONFIG_BT_ID_MAX;
u8_t id;
if (argc < 2) {
return -EINVAL;
}
id = strtol(argv[1], NULL, 10);
bt_id_get(addrs, &count);
if (count <= id) {
printf("Invalid identity\n");
return 0;
}
//printf("Selected identity: %s\n", addr_le_str(&addrs[id]));
selected_id = id;
return 0;
}
static inline int parse_ad(uint8_t *data, uint16_t len, int (* cb)(ad_data_t *data, void *arg), void *cb_arg)
{
int num = 0;
uint8_t *pdata = data;
ad_data_t ad = {0};
int ret;
while (len) {
if (pdata[0] == 0) {
return num;
}
if (len < pdata[0] + 1) {
return -1;
};
ad.len = pdata[0] - 1;
ad.type = pdata[1];
ad.data = &pdata[2];
if (cb) {
ret = cb(&ad, cb_arg);
if (ret) {
break;
}
}
num++;
len -= (pdata[0] + 1);
pdata += (pdata[0] + 1);
}
return num;
}
uint8_t *pscan_ad = NULL;
uint8_t *pscan_sd = NULL;
static int scan_ad_cmp(ad_data_t *ad, void *arg)
{
ad_data_t *ad2 = arg;
return (ad->type == ad2->type && ad->len == ad2->len
&& 0 == memcmp(ad->data, ad2->data, ad->len));
}
static int scan_ad_callback(ad_data_t *ad, void *arg)
{
evt_data_gap_dev_find_t *e = arg;
int ad_num;
uint8_t *pad = NULL;
int ret;
if (e->adv_len) {
if (e->adv_type == 0x04) {
pad = pscan_sd;
} else {
pad = pscan_ad;
}
ad_num = parse_ad(pad, 31, NULL, NULL);
ret = parse_ad(pad, 31, scan_ad_cmp, (void *)ad);
if (ret < ad_num) {
return 1;
}
}
return 0;
}
static void device_find(ble_event_en event, void *event_data)
{
evt_data_gap_dev_find_t *e = event_data;
int ad_num = parse_ad(e->adv_data, e->adv_len, NULL, NULL);
int ret;
char addr_str[32] = {0};
bt_addr2str(&e->dev_addr, addr_str, sizeof(addr_str));
if (pscan_ad || pscan_sd) {
ret = parse_ad(e->adv_data, e->adv_len, scan_ad_callback, event_data);
if (ret < ad_num) {
printf("[DEVICE]: %s, adv type %d, rssi %d, Raw data:%s\n", addr_str, e->adv_type, e->rssi, bt_hex(e->adv_data, e->adv_len));
}
} else {
printf("[DEVICE]: %s, adv type %d, rssi %d, Raw data:%s\n", addr_str, e->adv_type, e->rssi, bt_hex(e->adv_data, e->adv_len));
}
}
static void conn_param_req(ble_event_en event, void *event_data)
{
evt_data_gap_conn_param_req_t *e = event_data;
printf("LE conn param req: int (0x%04x, 0x%04x) lat %d to %d\n",
e->param.interval_min, e->param.interval_max, e->param.latency,
e->param.timeout);
e->accept = 1;
}
static void conn_param_update(ble_event_en event, void *event_data)
{
evt_data_gap_conn_param_update_t *e = event_data;
printf("LE conn param updated: int 0x%04x lat %d to %d\n", e->interval,
e->latency, e->timeout);
}
static int cmd_scan(int argc, char *argv[])
{
int ret;
static uint8_t scan_ad[31] = {0};
static uint8_t scan_sd[31] = {0};
scan_param_t params = {
SCAN_PASSIVE,
SCAN_FILTER_DUP_DISABLE,
SCAN_FAST_INTERVAL,
SCAN_FAST_WINDOW,
};
if (argc < 2) {
return -EINVAL;
}
if (argc >= 2) {
if (!strcmp(argv[1], "active")) {
params.type = SCAN_ACTIVE;
} else if (!strcmp(argv[1], "off")) {
pscan_ad = NULL;
pscan_sd = NULL;
ret = ble_stack_scan_stop();
if (!ret) {
printf("Scan stop succ\n");
} else {
printf("Scan stop fail\n");
}
return ret;
} else if (!strcmp(argv[1], "passive")) {
params.type = SCAN_PASSIVE;
} else if (!strcmp(argv[1], "test")) {
scan_param_t param = {
SCAN_PASSIVE,
SCAN_FILTER_DUP_ENABLE,
SCAN_FAST_INTERVAL,
SCAN_FAST_WINDOW,
};
fail_count = 0;
//参数为NULL
ret = ble_stack_scan_start(NULL);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
//测试扫描方式
for (int i = 0; i < 2; i++) {
param.type = i ;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
}
param.type = 2 ;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.type = SCAN_PASSIVE;
//测试是否过滤重复包
for (int i = 0 ; i < 2; i++) {
param.filter_dup = i;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
}
param.filter_dup = 2;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
//测试扫描间隔时间 0x0004~0x4000
param.filter_dup = 0x00;
param.interval = 0x0000; // interval设置为0
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.interval = 0x0003; // interval设置为3
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.interval = 0x0004; // interval设置为4
param.window = 0x0004;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.interval = 0x4000;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.interval = 0x4001;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.interval = 0x0800; // interval设置为0x0800,对应的时间为1.28s
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
//测试窗口持续时间
param.window = 0x0000;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.window = 0x0001;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.window = 0x0004;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ret = ble_stack_scan_stop();
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_stop fail");
} else {
ret = ble_stack_scan_stop();
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_stop fail");
}
param.window = 0x4000;
param.interval = 0x4000;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ble_stack_scan_stop();
}
param.window = 0x4001;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret == 0) {
ret = ble_stack_scan_stop();
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_stop fail");
} else {
ret = ble_stack_scan_stop();
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_scan_stop fail");
}
param.type = SCAN_PASSIVE;
param.filter_dup = SCAN_FILTER_DUP_ENABLE;
param.interval = SCAN_FAST_INTERVAL;
param.window = SCAN_FAST_WINDOW;
ret = ble_stack_scan_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_scan_start fail");
if (ret) {
printf("scan start fail %d!", ret);
} else {
printf("scan start!");
}
//test ble_stack_get_local_addr
dev_addr_t addr = {0x00, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}};
ret = ble_stack_get_local_addr(NULL);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_get_local_addr fail");
ret = ble_stack_get_local_addr(&addr);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_get_local_addr fail");
if (ret == 0) {
printf("addr.type =%d\n", addr.type);
if (addr.type < 0 || addr.type > 1) {
printf("ASSERTION Failed %s: %d", __FILE__, __LINE__);
}
for (int i = 0; i < 6; i++) {
printf("addr.val[%d] = %d\n", i, addr.val[i]);
}
}
ble_stack_scan_stop();
if (fail_count == 0) {
printf("TEST PASS\n");
} else {
fail_count = 0;
printf("TEST FAILED\n");
}
return 0;
} else {
return -EINVAL;
}
}
if (argc >= 3) {
if (!strcmp(argv[2], "dups")) {
params.filter_dup = SCAN_FILTER_DUP_DISABLE;
} else if (!strcmp(argv[2], "nodups")) {
params.filter_dup = SCAN_FILTER_DUP_ENABLE;
} else {
return -EINVAL;
}
}
if (argc >= 4) {
params.interval = strtol(argv[3], NULL, 10);
}
if (argc >= 5) {
params.window = strtol(argv[4], NULL, 10);
}
if (argc >= 6) {
pscan_ad = scan_ad;
memset(scan_ad, 0, sizeof(scan_ad));
str2hex(scan_ad, argv[5], sizeof(scan_ad));
}
if (argc >= 7) {
pscan_sd = scan_sd;
memset(scan_sd, 0, sizeof(scan_sd));
str2hex(scan_sd, argv[6], sizeof(scan_sd));
}
return ble_stack_scan_start(¶ms);
}
static inline int parse_ad_data(uint8_t *data, uint16_t len, ad_data_t *ad, uint8_t *ad_num)
{
uint8_t num = 0;
uint8_t *pdata = data;
while (len) {
if (len < pdata[0] + 1) {
*ad_num = 0;
return -1;
};
num++;
if (ad && num <= *ad_num) {
ad->len = pdata[0] - 1;
ad->type = pdata[1];
ad->data = &pdata[2];
}
len -= (pdata[0] + 1);
pdata += (pdata[0] + 1);
if (ad) {
ad++;
}
}
*ad_num = num;
return 0;
}
static inline int adv_ad_callback(ad_data_t *ad, void *arg)
{
ad_data_t **pad = (ad_data_t **)arg;
(*pad)->type = ad->type;
(*pad)->len = ad->len;
(*pad)->data = ad->data;
(*pad)++;
return 0;
}
static int cmd_advertise(int argc, char *argv[])
{
int err;
adv_param_t param3 = {0};
uint8_t ad_hex[31] = {0};
uint8_t sd_hex[31] = {0};
ad_data_t *ad = NULL;
uint8_t ad_num = 0;
ad_data_t *sd = NULL;
uint8_t sd_num = 0;
if (argc < 2) {
goto fail;
}
if (!strcmp(argv[1], "stop")) {
if (bt_le_adv_stop() < 0) {
printf("Failed to stop advertising\n");
} else {
printf("Advertising stopped\n");
}
return 0;
}
if (!strcmp(argv[1], "test")) {
fail_count = 0;
int ret;
ad_data_t ad[3] = {0};
ad_data_t sd[1] = {0};
uint8_t flag = AD_FLAG_GENERAL | AD_FLAG_NO_BREDR;
ad[0].type = AD_DATA_TYPE_FLAGS;
ad[0].data = (uint8_t *)&flag;
ad[0].len = 1;
uint8_t uuid16_list[] = {0x0d, 0x18};
ad[1].type = AD_DATA_TYPE_UUID16_ALL;
ad[1].data = (uint8_t *)uuid16_list;
ad[1].len = sizeof(uuid16_list);
ad[2].type = AD_DATA_TYPE_NAME_COMPLETE;
ad[2].data = (uint8_t *)DEVICE_NAME;
ad[2].len = strlen(DEVICE_NAME);
uint8_t manu_data[10] = {0x01, 0x02, 0x3, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10};
sd[0].type = AD_DATA_TYPE_MANUFACTURER_DATA;
sd[0].data = (uint8_t *)manu_data;
sd[0].len = sizeof(manu_data);
adv_param_t param = {
ADV_NONCONN_IND,
ad,
sd,
BLE_ARRAY_NUM(ad),
BLE_ARRAY_NUM(sd),
ADV_FAST_INT_MIN_2,
ADV_FAST_INT_MAX_2,
};
adv_param_t par = {
ADV_NONCONN_IND,
ad,
sd,
BLE_ARRAY_NUM(ad),
BLE_ARRAY_NUM(sd),
ADV_FAST_INT_MIN_2,
ADV_FAST_INT_MAX_2,
};
ret = ble_stack_adv_start(NULL);
TEST_ASSERT_EQUAL(-1, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//蓝牙广播属性测试
for (int i = 0; i < 5; i++) {
par.type = i;
if (i == 1 || i == 4) {
ret = ble_stack_adv_start(&par);
TEST_ASSERT_EQUAL(-2, ret, 1, "ble_stack_adv_start fail");
ble_stack_adv_stop();
} else if (i == 0) {
par.sd = NULL;
par.sd_num = 0;
par.interval_min = ADV_FAST_INT_MIN_1;
par.interval_max = ADV_FAST_INT_MAX_1;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ret = ble_stack_adv_stop();
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_stop fail");
}
ble_stack_adv_stop();
} else if (i == 2) {
par.sd = sd;
par.sd_num = BLE_ARRAY_NUM(sd);
par.interval_min = ADV_SCAN_INT_MIN_1;
par.interval_max = ADV_SCAN_INT_MAX_1;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ret = ble_stack_adv_stop();
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_stop fail");
}
ble_stack_adv_stop();
} else if (i == 3) {
par.sd = sd;
par.sd_num = BLE_ARRAY_NUM(sd);
par.interval_min = ADV_FAST_INT_MIN_2;
par.interval_max = ADV_FAST_INT_MAX_2;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ret = ble_stack_adv_stop();
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_adv_stop fail");
}
ble_stack_adv_stop();
}
}
param.type = 5;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
param.type = ADV_IND;
param.ad = ad;
param.sd = sd;
param.ad_num = BLE_ARRAY_NUM(ad);
param.sd_num = BLE_ARRAY_NUM(sd);
param.interval_min = ADV_FAST_INT_MIN_1;
param.interval_max = ADV_FAST_INT_MAX_1;
//ad=NULL
param.type = ADV_IND;
param.ad = NULL;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//ad不为NULL,ad_num=0
param.ad = ad;
param.ad_num = 0;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//sd=NULL
param.ad_num = BLE_ARRAY_NUM(ad);
param.sd = NULL;
param.sd_num = BLE_ARRAY_NUM(sd);
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//sd不为NULL,sd_num=0
param.sd = sd;
param.sd_num = 0;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//广播最小间隔时间<允许的最小值20ms
param.sd_num = BLE_ARRAY_NUM(sd);
param.interval_min = 0x001f; //允许的最小值0x0020(20ms)
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-3, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
////广播最小间隔时间=允许的最小值20ms
//param.interval_min = 0x0020; //允许的最小值0x0020(20ms)
//ret = ble_stack_adv_start(¶m);
//TEST_ASSERT_EQUAL(0,ret,1,"test_ble_stack_adv_start fail");
//if (ret == 0){
// ble_stack_adv_stop();
//}
//广播最大间隔时间>允许的最大值10.24s(0x4000)
param.interval_max = 0x4001;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-3, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
////广播最大间隔时间=允许的最大值10.24s(0x07C0)
//param.interval_max = 0x4000;
//ret = ble_stack_adv_start(¶m);
//TEST_ASSERT_EQUAL(0,ret,1,"test_ble_stack_adv_start fail");
//if (ret == 0){
// ble_stack_adv_stop();
//}
//广播最小间隔时间>最大间隔时间
param.interval_min = 0x00f0;
param.interval_max = 0x00a0;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_EQUAL(-3, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//data的len的长度超出最大长度27+1+4
param.interval_min = ADV_FAST_INT_MIN_1;
param.interval_max = ADV_FAST_INT_MAX_1;
uint8_t ad_data[] = {0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x01, 0x02, 0x3, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x01, 0x02, 0x3, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12};
ad[1].data = (uint8_t *)ad_data;
ad[1].len = sizeof(ad_data);
ad[1].type = AD_DATA_TYPE_UUID16_ALL;
param.ad_num = BLE_ARRAY_NUM(ad);
param.ad = ad;
ret = ble_stack_adv_start(¶m);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_adv_start fail");
if (ret == 0) {
ble_stack_adv_stop();
}
//*data为NULL
ad_data_t add[1] = {0};
ad_data_t sdd[1] = {0};
add[0].type = AD_DATA_TYPE_UUID16_ALL;
add[0].data = NULL;
add[0].len = 1;
sdd[0].type = AD_DATA_TYPE_MANUFACTURER_DATA;
sdd[0].data = NULL;
sdd[0].len = 0;
adv_param_t param2 = {
ADV_IND,
add,
sdd,
BLE_ARRAY_NUM(add),
BLE_ARRAY_NUM(sdd),
ADV_FAST_INT_MIN_1,
ADV_FAST_INT_MAX_1,
};
ret = ble_stack_adv_start(¶m2);
TEST_ASSERT_NOT_EQUAL(0, ret, 1, "test_ble_stack_adv_start fail");
if (fail_count == 0) {
printf("BLE_ADV TEST PASS\n");
} else {
fail_count = 0;
printf("BLE_ADV TEST FAILED\n");
}
if (ret == 0) {
ble_stack_adv_stop();
printf("adv start!");
} else {
printf("adv start fail %d!", ret);
}
return 0;
}
if (!strcmp(argv[1], "adv_nonconn_ind")) {
param3.type = ADV_NONCONN_IND;
} else if (!strcmp(argv[1], "adv_ind")) {
param3.type = ADV_IND;
} else if (!strcmp(argv[1], "scan_ind")) {
param3.type = ADV_SCAN_IND;
}
if (argc > 2) {
if (strlen(argv[2]) > 62) {
printf("max len\n");
goto fail;
}
str2hex(ad_hex, argv[2], sizeof(ad_hex));
ad_num = parse_ad(ad_hex, strlen(argv[2]) / 2, NULL, NULL);
if (ad_num < 0) {
printf("ad formate error\n");
goto fail;
}
ad = malloc(sizeof(*ad) * ad_num);
if (ad == NULL) {
printf("ad malloc fail\n");
goto fail;
}
ad_data_t *pad = ad;
parse_ad(ad_hex, strlen(argv[2]) / 2, adv_ad_callback, (void *)&pad);
}
if (argc > 3) {
if (strlen(argv[3]) > 62) {
printf("max len\n");
goto fail;
}
str2hex(sd_hex, argv[3], sizeof(sd_hex));
sd_num = parse_ad(sd_hex, strlen(argv[3]) / 2, NULL, NULL);
if (sd_num < 0) {
printf("sd formate error\n");
goto fail;
}
sd = malloc(sizeof(*sd) * sd_num);
if (sd == NULL) {
printf("sd malloc fail\n");
goto fail;
}
ad_data_t *psd = sd;
parse_ad(sd_hex, strlen(argv[3]) / 2, adv_ad_callback, (void *)&psd);
param3.type = ADV_SCAN_IND;
}
if (param3.type == ADV_NONCONN_IND) {
param3.ad = ad;
param3.sd = sd;
param3.ad_num = ad_num;
param3.sd_num = sd_num;
param3.interval_min = ADV_FAST_INT_MIN_2;
param3.interval_max = ADV_FAST_INT_MAX_2;
err = ble_stack_adv_start(¶m3);
if (err < 0) {
printf("Failed to start advertising nonconn_ind(err %d)\n", err);
} else {
printf("adv_type:%x;adv_interval_min:%d (*0.625)ms;adv_interval_max:%d (*0.625)ms\n", param3.type, (int)param3.interval_min, (int)param3.interval_max);
printf("Advertising started\n");
}
return 0;
}
if (param3.type == ADV_IND) {
param3.ad = ad;
param3.sd = NULL;
param3.ad_num = ad_num;
param3.sd_num = 0;
param3.interval_min = ADV_FAST_INT_MIN_1;
param3.interval_max = ADV_FAST_INT_MAX_1;
err = ble_stack_adv_start(¶m3);
if (err < 0) {
printf("Failed to start advertising adv_ind(err %d)\n", err);
} else {
printf("adv_type:%x;adv_interval_min:%d (*0.625)ms;adv_interval_max:%d (*0.625)ms\n", param3.type, (int)param3.interval_min, (int)param3.interval_max);
printf("Advertising started\n");
}
return 0;
}
if (param3.type == ADV_SCAN_IND) {
param3.ad = ad;
param3.sd = sd;
param3.ad_num = ad_num;
param3.sd_num = sd_num;
param3.interval_min = ADV_SCAN_INT_MIN_1;
param3.interval_max = ADV_SCAN_INT_MAX_1;
err = ble_stack_adv_start(¶m3);
if (err < 0) {
printf("Failed to start advertising scan_ind (err %d)\n", err);
} else {
printf("adv_type:%x;adv_interval_min:%d (*0.625)ms;adv_interval_max:%d (*0.625)ms\n", param3.type, (int)param3.interval_min, (int)param3.interval_max);
printf("Advertising started\n");
}
return 0;
}
return 0;
fail:
return -EINVAL;
}
#if defined(CONFIG_BT_CONN)
static int cmd_connect_le(int argc, char *argv[])
{
int ret;
dev_addr_t addr;
int16_t conn_handle;
conn_param_t param = {
CONN_INT_MIN_INTERVAL,
CONN_INT_MAX_INTERVAL,
0,
400,
};
conn_param_t demo = {
CONN_INT_MIN_INTERVAL,
CONN_INT_MAX_INTERVAL,
0,
400,
};
if (argc < 3) {
return -EINVAL;
}
if (argc >= 3) {
ret = str2bt_addr_le(argv[1], argv[2], &addr);
if (ret) {
printf("Invalid peer address (err %d)\n", ret);
return 0;
}
}
if (!strcmp(argv[3], "test")) {
fail_count = 0;
//test ble_stack_connet
ret = ble_stack_connect(NULL, ¶m, 0); //peer_addr=NULL
TEST_ASSERT_EQUAL(-1, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
ret = ble_stack_connect(&addr, NULL, 0); //param=NULL
TEST_ASSERT_EQUAL(-5, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
param.interval_min = 0x0006; //设为最小值min
param.interval_max = 0x0006;
ret = ble_stack_connect(&addr, ¶m, 0);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
param.interval_min = 0x0C80; //设为最大值
param.interval_max = 0x0C80;
param.timeout = 801;
ret = ble_stack_connect(&addr, ¶m, 0);
TEST_ASSERT_EQUAL(0, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
param.interval_min = 0x0C80; //min > max
param.interval_max = 0x0C00;
param.timeout = 801;
ret = ble_stack_connect(&addr, ¶m, 0);
if (ret == 0) {
ble_stack_disconnect(ret);
}
TEST_ASSERT_EQUAL(-5, ret, 1, "test_ble_stack_connect fail");
//latency超出范围
param.interval_min = 0x0018;
param.interval_max = 0x0028;
param.latency = 500;
ret = ble_stack_connect(&addr, ¶m, 0);
TEST_ASSERT_EQUAL(-5, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
//超时时间小于心跳,实际应大于心跳
param.interval_min = 0x0018;
param.interval_max = 0x0028;
param.latency = 0;
param.timeout = 3;
ret = ble_stack_connect(&addr, ¶m, 0);
TEST_ASSERT_EQUAL(-5, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
//timeout超出范围
param.timeout = 3201;
ret = ble_stack_connect(&addr, ¶m, 0);
TEST_ASSERT_EQUAL(-5, ret, 1, "test_ble_stack_connect fail");
if (ret == 0) {
ble_stack_disconnect(ret);
}
//auto超出范围
int ret2;
param.interval_min = 0x0018;
param.interval_max = 0x0028;
param.latency = 0;
param.timeout = 400;
ret2 = ble_stack_connect(&addr, ¶m, 2);
TEST_ASSERT_EQUAL(-2, ret2, 1, "test_ble_stack_connect fail");
if (ret2 != 0) {
ret = ble_stack_disconnect(ret2);
TEST_ASSERT_EQUAL(-2, ret2, 1, "test_ble_stack_disconnect fail");
} else {
ret = ble_stack_disconnect(ret2);
TEST_ASSERT_EQUAL(0, ret2, 1, "test_ble_stack_disconnect fail");
}
//auto == 1
ret2 = ble_stack_connect(&addr, ¶m, 1);
TEST_ASSERT_EQUAL(0, ret2, 1, "test_ble_stack_connect fail");
if (ret2 == 0) {
ble_stack_disconnect(ret2);
}
if (fail_count == 0) {
printf("BLE_CONN TEST PASS\n");
} else {
fail_count = 0;
printf("BLE_CONN TEST FAILED\n");
}
return 0;
}
if (argc >= 5) {
param.interval_min = strtol(argv[3], NULL, 16);
param.interval_max = strtol(argv[4], NULL, 16);
}
if (argc >= 7) {
param.latency = strtol(argv[5], NULL, 16);
param.timeout = strtol(argv[6], NULL, 16);
}
conn_handle = ble_stack_connect(&addr, &demo, 0);
if (conn_handle < 0) {
printf("Connection failed\n");
return -EIO;
}
return 0;
}
static int cmd_disconnect(int argc, char *argv[])
{
int16_t conn_handle = 0;
int err;
if (g_bt_conn_handle != -1 && argc < 2) {
conn_handle = g_bt_conn_handle;
} else {
if (argc < 2) {
return -EINVAL;
}
conn_handle = strtol(argv[1], NULL, 10);
}
err = ble_stack_disconnect(conn_handle);
if (err) {
printf("Disconnection failed (err %d)\n", err);
}
return 0;
}
static int cmd_auto_conn(int argc, char *argv[])
{
dev_addr_t addr;
conn_param_t param = {
CONN_INT_MIN_INTERVAL,
CONN_INT_MAX_INTERVAL,
0,
400,
};
int err;
conn_param_t *pparam = NULL;
uint8_t auto_conn = 1;
if (argc < 3) {
return -EINVAL;
}
err = str2bt_addr_le(argv[1], argv[2], &addr);
if (err) {
printf("Invalid peer address (err %d)\n", err);
return -EINVAL;
}
if (argc > 3) {
if (!strcmp(argv[3], "on")) {
auto_conn = 1;
pparam = ¶m;
} else if (!strcmp(argv[3], "off")) {
auto_conn = 0;
pparam = NULL;
} else {
return -EINVAL;
}
} else {
auto_conn = 1;
pparam = ¶m;
}
err = ble_stack_connect(&addr, pparam, auto_conn);
if (err < 0) {
return err;
}
printf("connect (%d) pending\n", err);
return 0;
}
static int cmd_select(int argc, char *argv[])
{
struct bt_conn *conn;
bt_addr_le_t addr;
int err;
if (argc < 3) {
return -EINVAL;
}
err = str2bt_addr_le(argv[1], argv[2], (dev_addr_t *)&addr);
if (err) {
printf("Invalid peer address (err %d)\n", err);
return 0;
}
conn = bt_conn_lookup_addr_le(BT_ID_DEFAULT, &addr);
if (!conn) {
printf("No matching connection found\n");
return 0;
}
if (default_conn) {
bt_conn_unref(default_conn);
}
default_conn = conn;
return 0;
}
static int cmd_conn_update(int argc, char *argv[])
{
if (argc < 5 && argc != 2) {
return -EINVAL;
}
if (argc == 2 && !strcmp(argv[1], "test")) {
int ret;
fail_count = 0;
printf("******* test ble_stack_connect_param_update start ******\n");
conn_param_t param;
param.interval_min = 0x0028;
param.interval_min = 0x0060;
param.latency = 0;
param.timeout = 400;
ret = ble_stack_connect_param_update(-1, ¶m);
TEST_ASSERT_EQUAL(-2, ret, 1, "test_ble_stack_connect_param_update fail");
ret = ble_stack_connect_param_update(g_bt_conn_handle, NULL);
TEST_ASSERT_EQUAL(-2, ret, 1, "test_ble_stack_connect_param_update fail");
param.interval_min = 0x0005;
param.interval_max = 0x0006;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(-22, ret, 1, "ble_stack_connect_param_update fail");
param.interval_min = 0x0006; //设为最小值min
param.interval_max = 0x0006;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_connect_param_update fail");
aos_msleep(1000);
param.interval_min = 0x0C80; //设为最大值
param.interval_max = 0x0C80;
param.timeout = 801;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(0, ret, 1, "ble_stack_connect_param_update fail");
param.interval_min = 0x0C80; //min > max
param.interval_max = 0x0C00;
param.timeout = 801;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(-22, ret, 1, "ble_stack_connect_param_update fail");
//latency超出范围
param.interval_min = 0x0018;
param.interval_max = 0x0028;
param.latency = 500;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(-22, ret, 1, "ble_stack_connect_param_update fail");
//超时时间小于心跳,实际应大于心跳
param.interval_min = 0x0018;
param.interval_max = 0x0028;
param.latency = 0;
param.timeout = 3;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(-22, ret, 1, "ble_stack_connect_param_update fail");
//timeout超出范围
param.timeout = 3201;
ret = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
TEST_ASSERT_EQUAL(-22, ret, 1, "ble_stack_connect_param_update fail");
printf("******* test ble_stack_connect_param_update end ******\n");
if (fail_count == 0) {
printf("TEST PASS\n");
} else {
printf("TEST FAIL\n");
}
return 0;
}
conn_param_t param;
int err;
param.interval_min = strtoul(argv[1], NULL, 16);
param.interval_max = strtoul(argv[2], NULL, 16);
param.latency = strtoul(argv[3], NULL, 16);
param.timeout = strtoul(argv[4], NULL, 16);
err = ble_stack_connect_param_update(g_bt_conn_handle, ¶m);
if (err) {
printf("conn update failed (err %d).\n", err);
} else {
printf("conn update initiated.\n");
}
return 0;
}
static int cmd_oob(int argc, char *argv[])
{
char addr[BT_ADDR_LE_STR_LEN];
struct bt_le_oob oob;
int err;
err = bt_le_oob_get_local(selected_id, &oob);
if (err) {
printf("OOB data failed\n");
return 0;
}
bt_addr_le_to_str(&oob.addr, addr, sizeof(addr));
printf("OOB data:\n");
printf(" addr %s\n", addr);
return 0;
}
static int cmd_clear(int argc, char *argv[])
{
bt_addr_le_t addr;
int err;
if (argc < 2) {
printf("Specify remote address or \"all\"\n");
return 0;
}
if (strcmp(argv[1], "all") == 0) {
// err = bt_unpair(selected_id, NULL);
err = ble_stack_dev_unpair(NULL);
if (err) {
printf("Failed to clear pairings (err %d)\n", err);
} else {
printf("Pairings successfully cleared\n");
}
return 0;
}
if (argc < 3) {
#if defined(CONFIG_BT_BREDR)
addr.type = BT_ADDR_LE_PUBLIC;
err = str2bt_addr(argv[1], &addr.a);
#else
printf("Both address and address type needed\n");
return 0;
#endif
} else {
err = str2bt_addr_le(argv[1], argv[2], (dev_addr_t *)&addr);
}
if (err) {
printf("Invalid address\n");
return 0;
}
//err = bt_unpair(selected_id, &addr);
err = ble_stack_dev_unpair(&addr);
if (err) {
printf("Failed to clear pairing (err %d)\n", err);
} else {
printf("Pairing successfully cleared\n");
}
return 0;
}
#endif /* CONFIG_BT_CONN */
#if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
static int cmd_security(int argc, char *argv[])
{
int err, sec;
/*************API TEST************/
int ret = 99;
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
ret = ble_stack_security(-1, 0);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_security");
printf("API exception parameter test end!\n");
return 0;
}
/*************shell****************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
sec = *argv[1] - '0';
err = ble_stack_security(g_bt_conn_handle, sec);
if (err) {
printf("Setting security failed (err %d)\n", err);
}
return 0;
}
static void smp_passkey_display(evt_data_smp_passkey_display_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Passkey for %s: %s\n", addr, e->passkey);
}
static void smp_passkey_confirm(evt_data_smp_passkey_confirm_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Pairing passkey for %s: %s\n", addr, e->passkey);
}
static void smp_passkey_entry(evt_data_smp_passkey_enter_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Enter passkey for %s\n", addr);
}
static void smp_cancel(evt_data_smp_cancel_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Pairing cancelled: %s\n", addr);
/* clear connection reference for sec mode 3 pairing */
if (g_pairing_handle) {
g_pairing_handle = -1;
}
}
static void smp_pairing_confirm(evt_data_smp_pairing_confirm_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
printf("Confirm pairing for %s\n", addr);
}
static void smp_pairing_complete(evt_data_smp_pairing_complete_t *e)
{
char addr[32];
bt_addr2str(&e->peer_addr, addr, 32);
if (e->err) {
printf("Pairing failed with %s, err %d\n", addr, e->err);
} else {
printf("%s with %s\n", e->bonded ? "Bonded" : "Paired", addr);
}
}
static void smp_event(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_SMP_PASSKEY_DISPLAY:
smp_passkey_display(event_data);
break;
case EVENT_SMP_PASSKEY_CONFIRM:
smp_passkey_confirm(event_data);
break;
case EVENT_SMP_PASSKEY_ENTER:
smp_passkey_entry(event_data);
break;
case EVENT_SMP_PAIRING_CONFIRM:
smp_pairing_confirm(event_data);
break;
case EVENT_SMP_PAIRING_COMPLETE:
smp_pairing_complete(event_data);
break;
case EVENT_SMP_CANCEL:
smp_cancel(event_data);
break;
default:
break;
}
}
static int cmd_iocap_set(int argc, char *argv[])
{
uint8_t io_cap = 0;
/************API TEST****************/
int ret = 99;
int err = 99;
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
ret = ble_stack_iocapability_set(0);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_iocapability_set1");
ret = ble_stack_iocapability_set(8);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_iocapability_set2");
ret = ble_stack_iocapability_set(13);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_iocapability_set3");
ret = ble_stack_iocapability_set(15);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_iocapability_set4");
printf("API exception parameter test end\n");
return 0;
}
/************API shell****************/
if (argc < 3) {
return -EINVAL;
}
if (!strcmp(argv[1], "NONE")) {
io_cap |= IO_CAP_IN_NONE;
} else if (!strcmp(argv[1], "YESNO")) {
io_cap |= IO_CAP_IN_YESNO;
} else if (!strcmp(argv[1], "KEYBOARD")) {
io_cap |= IO_CAP_IN_KEYBOARD;
} else {
return -EINVAL;
}
if (!strcmp(argv[2], "NONE")) {
io_cap |= IO_CAP_OUT_NONE;
} else if (!strcmp(argv[2], "DISPLAY")) {
io_cap |= IO_CAP_OUT_DISPLAY;
} else {
return -EINVAL;
}
/****zhangyj add***********/
err = ble_stack_iocapability_set(io_cap);
if (err) {
printf("Set iocapability failed!(err %d)\n", err);
} else {
printf("Set iocapability success!\n");
}
return 0;
}
static int cmd_auth_cancel(int argc, char *argv[])
{
int16_t conn_handle;
/************API TEST****************/
if (!strcmp(argv[1], "test")) {
int ret = 99;
printf("API exception parameter test start!\n");
ret = ble_stack_smp_cancel(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_smp_cancel");
printf("API exception parameter test end\n");
return 0;
}
/************shell*****************/
if (g_bt_conn_handle != -1) {
conn_handle = g_bt_conn_handle;
} else if (g_pairing_handle != -1) {
conn_handle = g_pairing_handle;
} else {
conn_handle = 0;
}
ble_stack_smp_cancel(conn_handle);
return 0;
}
static int cmd_auth_passkey_confirm(int argc, char *argv[])
{
/*************API TEST************/
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
int ret = 99;
ret = ble_stack_smp_passkey_confirm(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_smp_passkey_confirm");
printf("API exception parameter test end!\n");
return 0;
}
/*************shell**************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
ble_stack_smp_passkey_confirm(g_bt_conn_handle);
return 0;
}
static int cmd_auth_pairing_confirm(int argc, char *argv[])
{
/*************API TEST************/
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
int ret = 99;
ret = ble_stack_smp_pairing_confirm(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_smp_pairing_confirm");
printf("API exception parameter test end\n");
return 0;
}
/*************shell**************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
ble_stack_smp_pairing_confirm(g_bt_conn_handle);
return 0;
}
#if defined(CONFIG_BT_FIXED_PASSKEY)
static int cmd_fixed_passkey(int argc, char *argv[])
{
unsigned int passkey;
int err;
if (argc < 2) {
bt_passkey_set(BT_PASSKEY_INVALID);
printf("Fixed passkey cleared\n");
return 0;
}
passkey = atoi(argv[1]);
if (passkey > 999999) {
printf("Passkey should be between 0-999999\n");
return 0;
}
err = bt_passkey_set(passkey);
if (err) {
printf("Setting fixed passkey failed (err %d)\n", err);
}
return 0;
}
#endif
static int cmd_auth_passkey(int argc, char *argv[])
{
unsigned int passkey;
/*************API TEST************/
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
int ret = 99;
ret = ble_stack_smp_passkey_entry(-1, passkey);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_smp_passkey_entry1");
ret = ble_stack_smp_passkey_entry(0, 100001);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_smp_passkey_entry2");
printf("API exception parameter test end\n");
return 0;
}
/*************shell**************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
passkey = atoi(argv[1]);
if (passkey > 999999) {
printf("Passkey should be between 0-999999\n");
return 0;
}
ble_stack_smp_passkey_entry(g_bt_conn_handle, passkey);
return 0;
}
static int cmd_auth_get_keysize(int argc, char *argv[])
{
int size = 99;
/*************API TEST************/
if (!strcmp(argv[1], "test")) {
printf("API exception parameter test start!\n");
int ret = 99;
ret = ble_stack_enc_key_size_get(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_enc_key_size_get");
printf("API exception parameter test end\n");
return 0;
}
/*************shell**************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
size = ble_stack_enc_key_size_get(g_bt_conn_handle);
if (size >= 7 && size <= 16) {
printf("Get key size corret!(%d)\n", size);
} else {
printf("Get key size wrong!(%d)\n", size);
}
return 0;
}
#endif /* CONFIG_BT_SMP) || CONFIG_BT_BREDR */
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
static bt_u32_t l2cap_rate;
static void l2cap_recv_metrics(struct bt_l2cap_chan *chan, struct net_buf *buf)
{
return;
}
static void l2cap_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
{
printf("Incoming data channel %p psm %d len %u\n", chan, chan->psm, buf->len);
if (buf->len) {
hexdump(buf->data, buf->len);
}
}
static void l2cap_connected(struct bt_l2cap_chan *chan)
{
printf("Channel %p psm %d connected\n", chan, chan->psm);
}
static void l2cap_disconnected(struct bt_l2cap_chan *chan)
{
printf("Channel %p psm %d disconnected\n", chan, chan->psm);
}
static struct net_buf *l2cap_alloc_buf(struct bt_l2cap_chan *chan)
{
/* print if metrics is disabled */
if (chan->ops->recv != l2cap_recv_metrics) {
printf("Channel %p requires buffer\n", chan);
}
return net_buf_alloc(&data_rx_pool, K_FOREVER);
}
static struct bt_l2cap_chan_ops l2cap_ops = {
.alloc_buf = l2cap_alloc_buf,
.recv = l2cap_recv,
.connected = l2cap_connected,
.disconnected = l2cap_disconnected,
};
static struct bt_l2cap_le_chan l2cap_chan[L2CAP_DYM_CHANNEL_NUM] = {
0
};
static int l2cap_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
{
printf("Incoming conn %p\n", conn);
int i;
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.conn == NULL) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No channels available\n");
return -ENOMEM;
}
l2cap_chan[i].chan.ops = &l2cap_ops;
l2cap_chan[i].rx.mtu = DATA_MTU;
*chan = &l2cap_chan[i].chan;
return 0;
}
static struct bt_l2cap_server server[L2CAP_DYM_CHANNEL_NUM] = {
0
};
static int cmd_l2cap_register(int argc, char *argv[])
{
int i;
if (argc < 2) {
return -EINVAL;
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (server[i].psm == 0) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No more channel\n");
return 0;
}
server[i].accept = l2cap_accept;
server[i].psm = strtoul(argv[1], NULL, 16);
if (argc > 2) {
server[i].sec_level = strtoul(argv[2], NULL, 10);
}
if (bt_l2cap_server_register(&server[i]) < 0) {
printf("Unable to register psm\n");
server[i].psm = 0;
} else {
printf("L2CAP psm %u sec_level %u registered\n", server[i].psm,
server[i].sec_level);
}
return 0;
}
static int cmd_l2cap_connect(int argc, char *argv[])
{
u16_t psm;
int err;
int i;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.conn == NULL) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("No more Channel\n");
return -EINVAL;
}
l2cap_chan[i].chan.ops = &l2cap_ops;
l2cap_chan[i].rx.mtu = DATA_MTU;
psm = strtoul(argv[1], NULL, 16);
err = bt_l2cap_chan_connect(bt_conn_lookup_id(g_bt_conn_handle), &l2cap_chan[i].chan, psm);
if (err < 0) {
printf("Unable to connect to psm %u (err %u)\n", psm, err);
} else {
printf("L2CAP connection pending\n");
}
return 0;
}
static int cmd_l2cap_disconnect(int argc, char *argv[])
{
int err;
u16_t psm;
int i;
psm = strtoul(argv[1], NULL, 16);
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.psm == psm) {
err = bt_l2cap_chan_disconnect(&l2cap_chan[i].chan);
if (err) {
printf("Unable to disconnect: err %u\n", -err);
}
return err;
}
}
return 0;
}
static int cmd_l2cap_send(int argc, char *argv[])
{
static u8_t buf_data[DATA_MTU] = { [0 ...(DATA_MTU - 1)] = 0xff };
int ret, len, count = 1;
struct net_buf *buf;
u16_t psm = 0;
int i;
if (argc > 1) {
psm = strtoul(argv[1], NULL, 16);
} else {
return -EINVAL;
}
if (argc > 2) {
count = strtoul(argv[2], NULL, 10);
}
for (i = 0; i < L2CAP_DYM_CHANNEL_NUM; i++) {
if (l2cap_chan[i].chan.psm == psm) {
break;
}
}
if (i == L2CAP_DYM_CHANNEL_NUM) {
printf("Can't find channel\n");
return -EINVAL;
}
len = min(l2cap_chan[i].tx.mtu, DATA_MTU - BT_L2CAP_CHAN_SEND_RESERVE);
while (count--) {
buf = net_buf_alloc(&data_tx_pool, K_FOREVER);
net_buf_reserve(buf, BT_L2CAP_CHAN_SEND_RESERVE);
net_buf_add_mem(buf, buf_data, len);
ret = bt_l2cap_chan_send(&l2cap_chan[i].chan, buf);
if (ret < 0) {
printf("Unable to send: %d\n", -ret);
net_buf_unref(buf);
break;
}
}
return 0;
}
static int cmd_l2cap_metrics(int argc, char *argv[])
{
const char *action;
if (argc < 2) {
printf("l2cap rate: %u bps.\n", l2cap_rate);
return 0;
}
action = argv[1];
if (!strcmp(action, "on")) {
l2cap_ops.recv = l2cap_recv_metrics;
} else if (!strcmp(action, "off")) {
l2cap_ops.recv = l2cap_recv;
} else {
return -EINVAL;
}
printf("l2cap metrics %s.\n", action);
return 0;
}
#endif
#if defined(CONFIG_BT_BREDR)
static void l2cap_bredr_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)
{
printf("Incoming data channel %p len %u\n", chan, buf->len);
}
static void l2cap_bredr_connected(struct bt_l2cap_chan *chan)
{
printf("Channel %p connected\n", chan);
}
static void l2cap_bredr_disconnected(struct bt_l2cap_chan *chan)
{
printf("Channel %p disconnected\n", chan);
}
static struct net_buf *l2cap_bredr_alloc_buf(struct bt_l2cap_chan *chan)
{
printf("Channel %p requires buffer\n", chan);
return net_buf_alloc(&data_bredr_pool, K_FOREVER);
}
static struct bt_l2cap_chan_ops l2cap_bredr_ops = {
.alloc_buf = l2cap_bredr_alloc_buf,
.recv = l2cap_bredr_recv,
.connected = l2cap_bredr_connected,
.disconnected = l2cap_bredr_disconnected,
};
static struct bt_l2cap_br_chan l2cap_bredr_chan = {
.chan.ops = &l2cap_bredr_ops,
/* Set for now min. MTU */
.rx.mtu = 48,
};
static int l2cap_bredr_accept(struct bt_conn *conn, struct bt_l2cap_chan **chan)
{
printf("Incoming BR/EDR conn %p\n", conn);
if (l2cap_bredr_chan.chan.conn) {
printf("No channels available");
return -ENOMEM;
}
*chan = &l2cap_bredr_chan.chan;
return 0;
}
static struct bt_l2cap_server br_server = {
.accept = l2cap_bredr_accept,
};
static int cmd_bredr_l2cap_register(int argc, char *argv[])
{
if (argc < 2) {
return -EINVAL;
}
if (br_server.psm) {
printf("Already registered\n");
return 0;
}
br_server.psm = strtoul(argv[1], NULL, 16);
if (bt_l2cap_br_server_register(&br_server) < 0) {
printf("Unable to register psm\n");
br_server.psm = 0;
} else {
printf("L2CAP psm %u registered\n", br_server.psm);
}
return 0;
}
#if defined(CONFIG_BT_RFCOMM)
static void rfcomm_bredr_recv(struct bt_rfcomm_dlc *dlci, struct net_buf *buf)
{
printf("Incoming data dlc %p len %u\n", dlci, buf->len);
}
static void rfcomm_bredr_connected(struct bt_rfcomm_dlc *dlci)
{
printf("Dlc %p connected\n", dlci);
}
static void rfcomm_bredr_disconnected(struct bt_rfcomm_dlc *dlci)
{
printf("Dlc %p disconnected\n", dlci);
}
static struct bt_rfcomm_dlc_ops rfcomm_bredr_ops = {
.recv = rfcomm_bredr_recv,
.connected = rfcomm_bredr_connected,
.disconnected = rfcomm_bredr_disconnected,
};
static struct bt_rfcomm_dlc rfcomm_dlc = {
.ops = &rfcomm_bredr_ops,
.mtu = 30,
};
static int rfcomm_bredr_accept(struct bt_conn *conn, struct bt_rfcomm_dlc **dlc)
{
printf("Incoming RFCOMM conn %p\n", conn);
if (rfcomm_dlc.session) {
printf("No channels available");
return -ENOMEM;
}
*dlc = &rfcomm_dlc;
return 0;
}
struct bt_rfcomm_server rfcomm_server = {
.accept = &rfcomm_bredr_accept,
};
static int cmd_bredr_rfcomm_register(int argc, char *argv[])
{
int ret;
if (rfcomm_server.channel) {
printf("Already registered\n");
return 0;
}
rfcomm_server.channel = BT_RFCOMM_CHAN_SPP;
ret = bt_rfcomm_server_register(&rfcomm_server);
if (ret < 0) {
printf("Unable to register channel %x\n", ret);
rfcomm_server.channel = 0;
} else {
printf("RFCOMM channel %u registered\n", rfcomm_server.channel);
bt_sdp_register_service(&spp_rec);
}
return 0;
}
static int cmd_rfcomm_connect(int argc, char *argv[])
{
u8_t channel;
int err;
if (!default_conn) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
channel = strtoul(argv[1], NULL, 16);
err = bt_rfcomm_dlc_connect(default_conn, &rfcomm_dlc, channel);
if (err < 0) {
printf("Unable to connect to channel %d (err %u)\n",
channel, err);
} else {
printf("RFCOMM connection pending\n");
}
return 0;
}
static int cmd_rfcomm_send(int argc, char *argv[])
{
u8_t buf_data[DATA_BREDR_MTU] = { [0 ...(DATA_BREDR_MTU - 1)] =
0xff
};
int ret, len, count = 1;
struct net_buf *buf;
if (argc > 1) {
count = strtoul(argv[1], NULL, 10);
}
while (count--) {
buf = bt_rfcomm_create_pdu(&data_bredr_pool);
/* Should reserve one byte in tail for FCS */
len = min(rfcomm_dlc.mtu, net_buf_tailroom(buf) - 1);
net_buf_add_mem(buf, buf_data, len);
ret = bt_rfcomm_dlc_send(&rfcomm_dlc, buf);
if (ret < 0) {
printf("Unable to send: %d\n", -ret);
net_buf_unref(buf);
break;
}
}
return 0;
}
static int cmd_rfcomm_disconnect(int argc, char *argv[])
{
int err;
err = bt_rfcomm_dlc_disconnect(&rfcomm_dlc);
if (err) {
printf("Unable to disconnect: %u\n", -err);
}
return 0;
}
#endif /* CONFIG_BT_RFCOMM) */
static int cmd_bredr_discoverable(int argc, char *argv[])
{
int err;
const char *action;
if (argc < 2) {
return -EINVAL;
}
action = argv[1];
if (!strcmp(action, "on")) {
err = bt_br_set_discoverable(true);
} else if (!strcmp(action, "off")) {
err = bt_br_set_discoverable(false);
} else {
return -EINVAL;
}
if (err) {
printf("BR/EDR set/reset discoverable failed (err %d)\n", err);
} else {
printf("BR/EDR set/reset discoverable done\n");
}
return 0;
}
static int cmd_bredr_connectable(int argc, char *argv[])
{
int err;
const char *action;
if (argc < 2) {
return -EINVAL;
}
action = argv[1];
if (!strcmp(action, "on")) {
err = bt_br_set_connectable(true);
} else if (!strcmp(action, "off")) {
err = bt_br_set_connectable(false);
} else {
return -EINVAL;
}
if (err) {
printf("BR/EDR set/rest connectable failed (err %d)\n", err);
} else {
printf("BR/EDR set/reset connectable done\n");
}
return 0;
}
static int cmd_bredr_oob(int argc, char *argv[])
{
char addr[BT_ADDR_STR_LEN];
struct bt_br_oob oob;
int err;
err = bt_br_oob_get_local(&oob);
if (err) {
printf("BR/EDR OOB data failed\n");
return 0;
}
bt_addr_to_str(&oob.addr, addr, sizeof(addr));
printf("BR/EDR OOB data:\n");
printf(" addr %s\n", addr);
return 0;
}
static int cmd_bredr_sdp_find_record(int argc, char *argv[])
{
int err = 0, res;
const char *action;
if (!default_conn) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
action = argv[1];
if (!strcmp(action, "HFPAG")) {
discov = discov_hfpag;
} else if (!strcmp(action, "A2SRC")) {
discov = discov_a2src;
} else {
err = -EINVAL;
}
if (err) {
printf("SDP UUID to resolve not valid (err %d)\n", err);
printf("Supported UUID are \'HFPAG\' \'A2SRC\' only\n");
return err;
}
printf("SDP UUID \'%s\' gets applied\n", action);
res = bt_sdp_discover(default_conn, &discov);
if (res) {
printf("SDP discovery failed: result %d\n", res);
} else {
printf("SDP discovery started\n");
}
return 0;
}
#endif
#define HELP_NONE "[none]"
#define HELP_ADDR_LE "<address: XX:XX:XX:XX:XX:XX>or<test> <type: (public|random)>"
static const struct shell_cmd bt_commands[] = {
{ "init", cmd_init, HELP_ADDR_LE },
#if defined(CONFIG_BT_HCI)
{ "hci-cmd", cmd_hci_cmd, "<ogf> <ocf> [data]" },
#endif
{ "id-create", cmd_id_create, "[addr]" },
{ "id-reset", cmd_id_reset, "<id> [addr]" },
{ "id-delete", cmd_id_delete, "<id>" },
{ "id-show", cmd_id_show, HELP_NONE },
{ "id-select", cmd_id_select, "<id>" },
{ "name", cmd_name, "[name]" },
{
"scan", cmd_scan,
"<value: active, passive, off,test> <dup filter: dups, nodups> "\
"<scan interval> <scan window> "\
"<ad(len|adtype|addata ...): 0xxxxxxxx> <sd(len|adtype|addata ...): 0xxxxxxxx>"
},
{
"adv", cmd_advertise,
"<type: stop, adv_ind, adv_nonconn_ind,scan_ind,test> <ad(len|adtype|addata ...): 0xxxxxxxx> <sd(len|adtype|addata ...): 0xxxxxxxx>"
},
#if defined(CONFIG_BT_CONN)
{
"connect", cmd_connect_le, HELP_ADDR_LE\
" <addr> <addr_type>"\
"<test> or <interval_min> <interval_max>"\
" <latency> <timeout>"
},
{ "disconnect", cmd_disconnect, "[conn_handle]" },
{ "auto-conn", cmd_auto_conn, HELP_ADDR_LE" <type: on|off>"},
{ "select", cmd_select, HELP_ADDR_LE },
{ "conn-update", cmd_conn_update, "<min> <max> <latency> <timeout>" },
{ "oob", cmd_oob },
{ "clear", cmd_clear },
#if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
{ "security", cmd_security, "<security level: 0, 1, 2, 3>" },
{
"io-capability", cmd_iocap_set,
"<io input: NONE,YESNO, KEYBOARD> <io output: NONE,DISPLAY>"
},
{ "auth-cancel", cmd_auth_cancel, HELP_NONE },
{ "auth-passkey", cmd_auth_passkey, "<passkey>" },
{ "auth-passkey-confirm", cmd_auth_passkey_confirm, HELP_NONE },
{ "auth-pairing-confirm", cmd_auth_pairing_confirm, HELP_NONE },
{ "auth-get-keysize", cmd_auth_get_keysize, HELP_NONE },
#if defined(CONFIG_BT_FIXED_PASSKEY)
{ "fixed-passkey", cmd_fixed_passkey, "[passkey]" },
#endif
#if defined(CONFIG_BT_BREDR)
{ "auth-pincode", cmd_auth_pincode, "<pincode>" },
#endif /* CONFIG_BT_BREDR */
#endif /* CONFIG_BT_SMP || CONFIG_BT_BREDR) */
#if defined(CONFIG_BT_GATT_CLIENT)
{ "gatt-exchange-mtu", cmd_gatt_exchange_mtu, HELP_NONE },
{
"gatt-discover-primary", cmd_gatt_discover,
"<UUID> [start handle] [end handle]"
},
{
"gatt-discover-secondary", cmd_gatt_discover,
"<UUID> [start handle] [end handle]"
},
{
"gatt-discover-include", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{
"gatt-discover-characteristic", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{
"gatt-discover-descriptor", cmd_gatt_discover,
"[UUID] [start handle] [end handle]"
},
{ "gatt-read", cmd_gatt_read, "<handle> [offset],<test>" },
{ "gatt-read-multiple", cmd_gatt_mread, "[<handle 1>,test] <handle 2> ..." },
{ "gatt-write", cmd_gatt_write, "<handle> <offset> <data> [length],<test>" },
{
"gatt-write-without-response", cmd_gatt_write_without_rsp,
"<handle> <data> [length] [repeat]"
},
{
"gatt-write-signed", cmd_gatt_write_without_rsp,
"<handle> <data> [length] [repeat]"
},
{
"gatt-subscribe", cmd_gatt_subscribe,
"<CCC handle> [ind]"
},
{ "gatt-unsubscribe", cmd_gatt_unsubscribe, "<CCC handle>"},
#endif /* CONFIG_BT_GATT_CLIENT */
{ "gatt-show-db", cmd_gatt_show_db, HELP_NONE },
{
"gatt-register-service", cmd_gatt_register_test_svc,
"register pre-predefined test service"
},
{
"gatt-register-service2", cmd_gatt_register_test_svc,
"register pre-predefined test2 service"
},
{
"gatt-unregister-service", cmd_gatt_unregister_test_svc,
"unregister pre-predefined test service"
},
#if defined(CONFIG_BT_L2CAP_DYNAMIC_CHANNEL)
{ "l2cap-register", cmd_l2cap_register, "<psm> [sec_level]" },
{ "l2cap-connect", cmd_l2cap_connect, "<psm>" },
{ "l2cap-disconnect", cmd_l2cap_disconnect, "<psm>" },
{ "l2cap-send", cmd_l2cap_send, "<psm> <number of packets>" },
{ "l2cap-metrics", cmd_l2cap_metrics, "<value on, off>" },
#endif
#if defined(CONFIG_BT_BREDR)
{ "br-iscan", cmd_bredr_discoverable, "<value: on, off>" },
{ "br-pscan", cmd_bredr_connectable, "value: on, off" },
{ "br-connect", cmd_connect_bredr, "<address>" },
{
"br-discovery", cmd_bredr_discovery,
"<value: on, off> [length: 1-48] [mode: limited]"
},
{ "br-l2cap-register", cmd_bredr_l2cap_register, "<psm>" },
{ "br-oob", cmd_bredr_oob },
{ "br-sdp-find", cmd_bredr_sdp_find_record, "<HFPAG>" },
#if defined(CONFIG_BT_RFCOMM)
{ "br-rfcomm-register", cmd_bredr_rfcomm_register },
{ "br-rfcomm-connect", cmd_rfcomm_connect, "<channel>" },
{ "br-rfcomm-send", cmd_rfcomm_send, "<number of packets>"},
{ "br-rfcomm-disconnect", cmd_rfcomm_disconnect, HELP_NONE },
#endif /* CONFIG_BT_RFCOMM */
#endif /* CONFIG_BT_BREDR */
#endif /* CONFIG_BT_CONN */
#if defined(CONFIG_BT_CTLR_ADV_EXT)
{ "advx", cmd_advx, "<on off> [coded] [anon] [txp]" },
{ "scanx", cmd_scanx, "<on passive off> [coded]" },
#endif /* CONFIG_BT_CTLR_ADV_EXT */
#if defined(CONFIG_BT_CTLR_DTM)
{ "test_tx", cmd_test_tx, "<chan> <len> <type> <phy>" },
{ "test_rx", cmd_test_rx, "<chan> <phy> <mod_idx>" },
{ "test_end", cmd_test_end, HELP_NONE},
#endif /* CONFIG_BT_CTLR_ADV_EXT */
{ NULL, NULL, NULL }
};
static void cmd_ble_func(char *wbuf, int wbuf_len, int argc, char **argv)
{
int i = 0;
int err;
if (argc < 2) {
printf("Ble support commands\n");
for (i = 0; bt_commands[i].cmd_name != NULL; i ++) {
printf(" %s %s\n", bt_commands[i].cmd_name, bt_commands[i].help);
}
return;
}
for (i = 0; bt_commands[i].cmd_name != NULL; i ++) {
if (strlen(bt_commands[i].cmd_name) == strlen(argv[1]) &&
!strncmp(bt_commands[i].cmd_name, argv[1], strlen(bt_commands[i].cmd_name))) {
if (bt_commands[i].cb) {
err = bt_commands[i].cb(argc - 1, &argv[1]);
if (err) {
printf("%s execute fail, %d\n", bt_commands[i].cmd_name, err);
}
break;
}
}
}
}
#if AOS_COMP_CLI
void cli_reg_cmd_ble(void)
{
static const struct cli_command cmd_info = {
"ble",
"ble commands",
cmd_ble_func,
};
aos_cli_register_command(&cmd_info);
}
#endif /* AOS_COMP_CLI */
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/test/bt.c | C | apache-2.0 | 84,868 |
/** @file
* @brief Bluetooth GATT shell functions
*
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <bt_errno.h>
#include <ble_types/types.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <misc/byteorder.h>
#include <zephyr.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include "bt.h"
#include "gatt.h"
#include <aos/ble.h>
#include <aos/gatt.h>
#include <aos/kernel.h>
#include "app_test.h"
#include <work.h>
extern int16_t fail_count;
#define CHAR_SIZE_MAX 512
extern int16_t g_bt_conn_handle;
extern int16_t g_security_level;
#define VALUE_LEN 100
extern char *uuid_str(uuid_t *uuid);
extern void str2hex(uint8_t hex[], char *s, uint8_t cnt);
extern void hexdump(const u8_t *data, size_t len);
struct test_svc_t {
int16_t conn_handle;
uint16_t svc_handle;
uint16_t svc2_handle;
ccc_value_en ccc;
uint16_t mtu;
char value1[VALUE_LEN];
char value2[VALUE_LEN];
char value3[8];
char value3_cud[30];
char value4[VALUE_LEN];
} test_svc = {
.conn_handle = -1,
.svc_handle = 0,
.svc2_handle = 0,
.mtu = VALUE_LEN,
.value1 = "test value 1",
.value2 = "test value 2",
.value3 = "test",
.value3_cud = "this is value3 cud",
.value4 = "test value 4",
};
#if defined(CONFIG_BT_GATT_CLIENT)
static int event_gatt_mtu_exchange(ble_event_en event, void *event_data)
{
evt_data_gatt_mtu_exchange_t *e = event_data;
printf("Exchange %s\n", e->err == 0 ? "successful" : "failed");
test_svc.mtu = ble_stack_gatt_mtu_get(e->conn_handle);
return 0;
}
int cmd_gatt_exchange_mtu(int argc, char *argv[])
{
int err;
int getmtu;
/************API TEST****************/
if (!strcmp(argv[1], "test")) {
int ret = 99;
printf("API exception parameter test start!\n");
//Exchange mtu
ret = ble_stack_gatt_mtu_exchange(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_mtu_exchange");
//Get mtu
ret = ble_stack_gatt_mtu_get(-1);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_mtu_get1");
printf("API exception parameter test end!\n");
return 0;
}
/************shell****************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
err = ble_stack_gatt_mtu_exchange(g_bt_conn_handle);
if (err) {
printf("Exchange failed (err %d)\n", err);
return 0;
} else {
printf("Exchange pending\n");
}
//add by zhangyj to test mtu_get,when define CONFIG_BT_SMP,mtu defult 65,otherwise 23
aos_msleep(2000);
getmtu = ble_stack_gatt_mtu_get(g_bt_conn_handle);
if (getmtu <= 0 && getmtu >= 244) {
printf("Get mtu failed (err %d)\n", getmtu);
return 0;
} else {
printf("Get mtu success(mtu %d)!\n", getmtu);
}
return 0;
}
static void print_chrc_props(u8_t properties)
{
printf("Properties: ");
if (properties & GATT_CHRC_PROP_BROADCAST) {
printf("[bcast]");
}
if (properties & GATT_CHRC_PROP_READ) {
printf("[read]");
}
if (properties & GATT_CHRC_PROP_WRITE) {
printf("[write]");
}
if (properties & GATT_CHRC_PROP_WRITE_WITHOUT_RESP) {
printf("[write w/w rsp]");
}
if (properties & GATT_CHRC_PROP_NOTIFY) {
printf("[notify]");
}
if (properties & GATT_CHRC_PROP_INDICATE) {
printf("[indicate]");
}
if (properties & GATT_CHRC_PROP_AUTH) {
printf("[auth]");
}
if (properties & GATT_CHRC_PROP_EXT_PROP) {
printf("[ext prop]");
}
printf("\n");
}
static int event_gatt_discovery(ble_event_en event, void *event_data)
{
union {
evt_data_gatt_discovery_svc_t svc;
evt_data_gatt_discovery_inc_svc_t svc_inc;
evt_data_gatt_discovery_char_t char_c;
evt_data_gatt_discovery_char_des_t char_des;
} *e;
e = event_data;
switch (event) {
case EVENT_GATT_DISCOVERY_SVC:
printf("Service %s found: start handle %x, end_handle %x\n",
uuid_str(&e->svc.uuid), e->svc.start_handle, e->svc.end_handle);
break;
case EVENT_GATT_DISCOVERY_CHAR:
printf("Characteristic %s found: handle %x\n", (char *)(&e->char_c.uuid),
e->char_c.attr_handle);
print_chrc_props(e->char_c.props);
break;
case EVENT_GATT_DISCOVERY_INC_SVC:
printf("Include %s found: handle %x, start %x, end %x\n",
uuid_str(&e->svc_inc.uuid), e->svc_inc.attr_handle, e->svc_inc.start_handle,
e->svc_inc.end_handle);
break;
default:
printf("Descriptor %s found: handle %x\n", uuid_str(&e->char_des.uuid), e->char_des.attr_handle);
break;
}
return 0;
}
int cmd_gatt_discover(int argc, char *argv[])
{
int err;
gatt_discovery_type_en type;
struct ut_uuid_128 uuid = {0};
uint16_t start_handle = 0x0001;
uint16_t end_handle = 0xffff;
/************API TEST****************/
//API test must be execute after connected
if (!strcmp(argv[1], "test")) {
fail_count = 0;
int ret = 99;
printf("API exception parameter test start!\n");
ret = ble_stack_gatt_discovery(-1, 0, 2800, 1, 10);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_discovery1");
ret = ble_stack_gatt_discovery(g_bt_conn_handle, -1, 2800, 1, 10);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_discovery2");
ret = ble_stack_gatt_discovery(g_bt_conn_handle, 4, 2800, 1, 10);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_discovery3");
//assert
ret = ble_stack_gatt_discovery(g_bt_conn_handle, GATT_FIND_PRIMARY_SERVICE, 2800, 1, 10);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_discovery4");
ret = ble_stack_gatt_discovery(g_bt_conn_handle, GATT_FIND_PRIMARY_SERVICE, 2800, 1, 10);
TEST_ASSERT_EQUAL(-2, ret, 0, "ble_stack_gatt_discovery5");
printf("API exception parameter test end!\n");
if (!fail_count) {
printf("BLE_GATT_DIS PASS\n");
} else {
printf("BLE_GATT_DIS FAILED\n");
}
return 0;
}
/************shell****************/
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
if (!strcmp(argv[0], "gatt-discover-primary") ||
!strcmp(argv[0], "gatt-discover-secondary")) {
return -EINVAL;
}
goto done;
}
/* Only set the UUID if the value is valid (non zero) */
if (strlen(argv[1]) == 4) {
struct ut_uuid_16 uuid1 = {0};
uuid1.uuid.type = UUID_TYPE_16;
uuid1.val = strtoul(argv[1], NULL, 16);
uuid = *(struct ut_uuid_128 *)(&uuid1);
} else if (strlen(argv[1]) == 32) {
uuid.uuid.type = UUID_TYPE_128;
str2hex(uuid.val, argv[1], 16);
}
if (argc > 2) {
start_handle = strtoul(argv[2], NULL, 16);
if (argc > 3) {
end_handle = strtoul(argv[3], NULL, 16);
}
}
done:
if (!strcmp(argv[0], "gatt-discover-secondary")) {
type = BT_GATT_DISCOVER_SECONDARY;
} else if (!strcmp(argv[0], "gatt-discover-include")) {
type = GATT_FIND_INC_SERVICE;
} else if (!strcmp(argv[0], "gatt-discover-characteristic")) {
type = GATT_FIND_CHAR;
} else if (!strcmp(argv[0], "gatt-discover-descriptor")) {
type = GATT_FIND_CHAR_DESCRIPTOR;
} else {
type = GATT_FIND_PRIMARY_SERVICE;
}
err = ble_stack_gatt_discovery(g_bt_conn_handle, type, (uuid.uuid.type == 0 && uuid.val == 0) ? NULL : (uuid_t *)&uuid, start_handle, end_handle);
if (err) {
printf("Discover failed (err %d)\n", err);
} else {
printf("Discover pending\n");
}
return 0;
}
static int event_gatt_read_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_read_cb_t *e = event_data;
printf("Read complete: err %u length %u\n", e->err, e->len);
hexdump(e->data, e->len);
return 0;
}
int cmd_gatt_read(int argc, char *argv[])
{
int err;
uint16_t handle;
uint16_t offset = 0;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
if (argc == 4) {
printf("***** test ble_stack_gatt_read start *****\n");
handle = strtoul(argv[1], NULL, 16);
offset = strtoul(argv[2], NULL, 16);
if (!strcmp(argv[3], "test")) {
err = ble_stack_gatt_read(-1, handle, offset);
TEST_ASSERT_EQUAL(-2, err, 1, "test_ble_stack_gatt_read fail");
}
printf("***** test ble_stack_gatt_read end *****\n");
return 0;
}
handle = strtoul(argv[1], NULL, 16);
if (argc > 2) {
offset = strtoul(argv[2], NULL, 16);
}
err = ble_stack_gatt_read(g_bt_conn_handle, handle, offset);
if (err) {
printf("Read failed (err %d)\n", err);
} else {
printf("Read pending\n");
}
return 0;
}
int cmd_gatt_mread(int argc, char *argv[])
{
int i, err;
uint16_t h[8];
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
if (argc == 4) {
if (!strcmp(argv[3], "test")) {
printf("***** test ble_stack_gatt_read_multiple start *****");
for (i = 0; i < argc - 1; i++) {
h[i] = strtoul(argv[i + 1], NULL, 16);
}
err = ble_stack_gatt_read_multiple(-1, argc - 1, h);
TEST_ASSERT_EQUAL(-2, err, 1, "test_ble_stack_gatt_read_multiple fail");
printf("***** test ble_stack_gatt_read_multiple start *****");
return 0;
}
}
if (argc - 1 > BLE_ARRAY_NUM(h)) {
printf("Enter max %lu handle items to read\n", ARRAY_SIZE(h));
return 0;
}
for (i = 0; i < argc - 1; i++) {
h[i] = strtoul(argv[i + 1], NULL, 16);
}
err = ble_stack_gatt_read_multiple(g_bt_conn_handle, argc - 1, h);
if (err) {
printf("GATT multiple read request failed (err %d)\n", err);
}
return 0;
}
static u8_t gatt_write_buf[CHAR_SIZE_MAX];
static int event_gatt_write_cb(ble_event_en event, void *event_data)
{
evt_data_gatt_write_cb_t *e = event_data;
printf("Write complete: err %u\n", e->err);
return 0;
}
int cmd_gatt_write(int argc, char *argv[])
{
int err;
uint16_t handle, offset, len = 1;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 4) {
return -EINVAL;
}
handle = strtoul(argv[1], NULL, 16);
offset = strtoul(argv[2], NULL, 16);
gatt_write_buf[0] = strtoul(argv[3], NULL, 16);
if (argc == 6) {
int i;
len = BLE_MIN(strtoul(argv[4], NULL, 16), sizeof(gatt_write_buf));
for (i = 1; i < len; i++) {
gatt_write_buf[i] = gatt_write_buf[0];
}
if (!strcmp(argv[5], "test")) {
fail_count = 0;
printf("****** test ble_stack_gatt_write start *****\n");
err = ble_stack_gatt_write_response(-1, handle, gatt_write_buf, len, offset);
TEST_ASSERT_EQUAL(-5, err, 1, "test_ble_stack_gatt_write fail");
err = ble_stack_gatt_write_response(g_bt_conn_handle, handle, NULL, len, offset);
TEST_ASSERT_EQUAL(-2, err, 1, "test_ble_stack_gatt_write fail");
err = ble_stack_gatt_write_response(g_bt_conn_handle, handle, gatt_write_buf, 0, offset);
TEST_ASSERT_EQUAL(-2, err, 1, "test_ble_stack_gatt_write fail");
err = ble_stack_gatt_write(g_bt_conn_handle, handle, gatt_write_buf, len, offset, 3);
TEST_ASSERT_EQUAL(-3, err, 1, "test_ble_stack_gatt_write fail");
printf("****** test ble_stack_gatt_write end *****\n");
if (!fail_count) {
printf("BLE_GATT_WRITE PASS\n");
} else {
printf("BLE_GATT_WRITE FAILED\n");
}
}
return 0;
}
if (argc == 5) {
int i;
len = BLE_MIN(strtoul(argv[4], NULL, 16), sizeof(gatt_write_buf));
for (i = 1; i < len; i++) {
gatt_write_buf[i] = gatt_write_buf[0];
}
}
err = ble_stack_gatt_write_response(g_bt_conn_handle, handle, gatt_write_buf, len, offset);
if (err) {
printf("Write failed (err %d)\n", err);
} else {
printf("Write pending\n");
}
return 0;
}
int cmd_gatt_write_without_rsp(int argc, char *argv[])
{
uint16_t handle;
uint16_t repeat;
int err = 0;
uint16_t len;
bool sign;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
sign = !strcmp(argv[0], "gatt-write-signed");
handle = strtoul(argv[1], NULL, 16);
gatt_write_buf[0] = strtoul(argv[2], NULL, 16);
len = 1;
if (argc > 3) {
int i;
len = BLE_MIN(strtoul(argv[3], NULL, 16), sizeof(gatt_write_buf));
for (i = 1; i < len; i++) {
gatt_write_buf[i] = gatt_write_buf[0];
}
}
repeat = 0;
if (argc > 4) {
repeat = strtoul(argv[4], NULL, 16);
}
if (!repeat) {
repeat = 1;
}
while (repeat--) {
if (sign) {
err = ble_stack_gatt_write_signed(g_bt_conn_handle, handle,
gatt_write_buf, len, 0);
} else {
err = ble_stack_gatt_write_no_response(g_bt_conn_handle, handle,
gatt_write_buf, len, 0);
}
if (err) {
break;
}
}
printf("Write Complete (err %d)\n", err);
return 0;
}
static int event_gatt_notify(ble_event_en event, void *event_data)
{
evt_data_gatt_notify_t *e = event_data;
printf("Notification: char handle %d length %u\n", e->char_handle, e->len);
hexdump(e->data, e->len);
return 0;
}
int cmd_gatt_subscribe(int argc, char *argv[])
{
int err;
uint16_t ccc_handle;
uint16_t value = 0;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 3) {
return -EINVAL;
}
ccc_handle = strtoul(argv[1], NULL, 16);
value = CCC_VALUE_NOTIFY;
if (argc > 3 && !strcmp(argv[2], "ind")) {
value = CCC_VALUE_INDICATE;
}
err = ble_stack_gatt_write_response(g_bt_conn_handle, ccc_handle, &value, sizeof(value), 0);
if (err) {
printf("Subscribe failed (err %d)\n", err);
} else {
printf("Subscribed\n");
}
return 0;
}
int cmd_gatt_unsubscribe(int argc, char *argv[])
{
int err;
uint16_t ccc_handle;
uint16_t value = CCC_VALUE_NONE;
if (g_bt_conn_handle == -1) {
printf("Not connected\n");
return 0;
}
if (argc < 2) {
return -EINVAL;
}
ccc_handle = strtoul(argv[1], NULL, 16);
err = ble_stack_gatt_write_response(g_bt_conn_handle, ccc_handle, &value, sizeof(value), 0);
if (err) {
printf("Unsubscribe failed (err %d)\n", err);
} else {
printf("Unsubscribe success\n");
}
return 0;
}
#endif /* CONFIG_BT_GATT_CLIENT */
static u8_t print_attr(const struct bt_gatt_attr *attr, void *user_data)
{
printf("attr %p handle 0x%04x uuid %s perm 0x%02x\n",
attr, attr->handle, bt_uuid_str(attr->uuid), attr->perm);
return BT_GATT_ITER_CONTINUE;
}
int cmd_gatt_show_db(int argc, char *argv[])
{
bt_gatt_foreach_attr(0x0001, 0xffff, print_attr, NULL);
return 0;
}
#define TEST_SERVICE_UUID UUID128_DECLARE(0xF0,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR1_UUID UUID128_DECLARE(0xF1,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR2_UUID UUID128_DECLARE(0xF2,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR3_UUID UUID128_DECLARE(0xF3,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR4_UUID UUID128_DECLARE(0xF4,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR5_UUID UUID128_DECLARE(0xF5,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR6_UUID UUID128_DECLARE(0xF6,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST_CHAR7_UUID UUID128_DECLARE(0xF7,0x31,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_SERVICE_UUID UUID128_DECLARE(0xF0,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR1_UUID UUID128_DECLARE(0xF1,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR2_UUID UUID128_DECLARE(0xF2,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR3_UUID UUID128_DECLARE(0xF3,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR4_UUID UUID128_DECLARE(0xF4,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR5_UUID UUID128_DECLARE(0xF5,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
#define TEST2_CHAR6_UUID UUID128_DECLARE(0xF6,0x30,0x35,0xd4,0x12,0xf3,0x11,0xe9, 0xab,0x14,0xd6,0x63,0xbd,0x87,0x3d,0x93)
static struct bt_gatt_ccc_cfg_t test3_ccc_cfg[2] = {};
enum {
TEST_IDX_SVC,
TEST_IDX_CHAR1,
TEST_IDX_CHAR1_VAL,
TEST_IDX_CHAR2,
TEST_IDX_CHAR2_VAL,
TEST_IDX_CHAR5,
TEST_IDX_CHAR5_VAL,
TEST_IDX_CHAR3,
TEST_IDX_CHAR3_VAL,
TEST_IDX_CHAR3_CUD,
TEST_IDX_CHAR3_CCC,
TEST_IDX_CHAR4,
TEST_IDX_CHAR4_VAL,
TEST_IDX_CHAR6,
TEST_IDX_CHAR6_VAL,
TEST_IDX_CHAR7,
TEST_IDX_CHAR7_VAL,
TEST_IDX_MAX,
};
gatt_service test_service;
gatt_service test2_service;
static gatt_attr_t test_attrs[] = {
[TEST_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST_SERVICE_UUID),
[TEST_IDX_CHAR1] = GATT_CHAR_DEFINE(TEST_CHAR1_UUID, GATT_CHRC_PROP_READ),
[TEST_IDX_CHAR1_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR1_UUID, GATT_PERM_READ),
[TEST_IDX_CHAR2] = GATT_CHAR_DEFINE(TEST_CHAR2_UUID, GATT_CHRC_PROP_READ),
[TEST_IDX_CHAR2_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR2_UUID, GATT_PERM_READ | GATT_PERM_READ_AUTHEN),
[TEST_IDX_CHAR5] = GATT_CHAR_DEFINE(TEST_CHAR5_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR5_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR5_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST_IDX_CHAR3] = GATT_CHAR_DEFINE(TEST_CHAR3_UUID, GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_NOTIFY | GATT_CHRC_PROP_INDICATE | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR3_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR3_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST_IDX_CHAR3_CUD] = GATT_CHAR_CUD_DEFINE(test_svc.value3_cud, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST_IDX_CHAR3_CCC] = GATT_CHAR_CCC_DEFINE(test3_ccc_cfg),
[TEST_IDX_CHAR4] = GATT_CHAR_DEFINE(TEST_CHAR4_UUID, GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP | GATT_CHRC_PROP_AUTH),
[TEST_IDX_CHAR4_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR4_UUID, GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE | GATT_PERM_WRITE_AUTHEN),
[TEST_IDX_CHAR6] = GATT_CHAR_DEFINE(TEST_CHAR6_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP),
[TEST_IDX_CHAR6_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR6_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST_IDX_CHAR7] = GATT_CHAR_DEFINE(TEST_CHAR7_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP | GATT_CHRC_PROP_EXT_PROP),
[TEST_IDX_CHAR7_VAL] = GATT_CHAR_VAL_DEFINE(TEST_CHAR7_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE | GATT_PERM_WRITE_AUTHEN),
};
enum {
TEST2_IDX_SVC,
TEST2_IDX_CHAR1,
TEST2_IDX_CHAR1_VAL,
TEST2_IDX_CHAR2,
TEST2_IDX_CHAR2_VAL,
TEST2_IDX_CHAR5,
TEST2_IDX_CHAR5_VAL,
TEST2_IDX_CHAR3,
TEST2_IDX_CHAR3_VAL,
TEST2_IDX_CHAR4,
TEST2_IDX_CHAR4_VAL,
TEST2_IDX_CHAR6,
TEST2_IDX_CHAR6_VAL,
TEST2_IDX_MAX,
};
static gatt_attr_t test2_attrs[] = {
[TEST2_IDX_SVC] = GATT_PRIMARY_SERVICE_DEFINE(TEST2_SERVICE_UUID),
[TEST2_IDX_CHAR1] = GATT_CHAR_DEFINE(TEST2_CHAR1_UUID, GATT_CHRC_PROP_READ),
[TEST2_IDX_CHAR1_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR1_UUID, GATT_PERM_READ),
[TEST2_IDX_CHAR2] = GATT_CHAR_DEFINE(TEST2_CHAR2_UUID, GATT_CHRC_PROP_READ),
[TEST2_IDX_CHAR2_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR2_UUID, GATT_PERM_READ | GATT_PERM_READ_ENCRYPT),
[TEST2_IDX_CHAR5] = GATT_CHAR_DEFINE(TEST2_CHAR5_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR5_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR5_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_PREPARE_WRITE),
[TEST2_IDX_CHAR3] = GATT_CHAR_DEFINE(TEST2_CHAR3_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR3_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR3_UUID, GATT_PERM_READ | GATT_PERM_WRITE),
[TEST2_IDX_CHAR4] = GATT_CHAR_DEFINE(TEST2_CHAR4_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR4_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR4_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPT | GATT_PERM_PREPARE_WRITE),
[TEST2_IDX_CHAR6] = GATT_CHAR_DEFINE(TEST2_CHAR6_UUID, GATT_CHRC_PROP_READ | GATT_CHRC_PROP_WRITE | GATT_CHRC_PROP_WRITE_WITHOUT_RESP),
[TEST2_IDX_CHAR6_VAL] = GATT_CHAR_VAL_DEFINE(TEST2_CHAR6_UUID, GATT_PERM_READ | GATT_PERM_WRITE | GATT_PERM_WRITE_ENCRYPT),
};
struct {
uint16_t notify_handle;
uint8_t notify_type;
uint8_t indicate_ongoing;
} g_notify_data = {0};
static void conn_change(ble_event_en event, void *event_data)
{
evt_data_gap_conn_change_t *e = (evt_data_gap_conn_change_t *)event_data;
if (e->connected == CONNECTED) {
test_svc.conn_handle = e->conn_handle;
} else {
test_svc.conn_handle = -1;
g_notify_data.notify_type = 0;
g_notify_data.indicate_ongoing = 0;
}
}
static int event_char_write(ble_event_en event, void *event_data)
{
evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
int16_t handle_offset = 0;
static int w_len = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
printf("event_char_write conn_handle %d char_handle %d len %ld offset %d\n",
e->conn_handle, e->char_handle, e->len, e->offset);
hexdump(e->data, e->len);
if (test_svc.conn_handle == e->conn_handle) {
switch (handle_offset) {
case TEST_IDX_CHAR3_VAL:
if (e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST_IDX_CHAR5_VAL:
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST_IDX_CHAR4_VAL:
case TEST_IDX_CHAR7_VAL:
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST_IDX_CHAR3_CUD:
if (e->offset + e->len > sizeof(test_svc.value3_cud)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3_cud + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3_cud)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3_cud));
break;
case TEST_IDX_CHAR6_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
if (e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
default:
e->len = 0;
break;
}
}
return 0;
}
static int event_char_read(ble_event_en event, void *event_data)
{
evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
if (test_svc.conn_handle == e->conn_handle) {
switch (handle_offset) {
case TEST_IDX_CHAR1_VAL:
e->data = (uint8_t *)test_svc.value1;
e->len = test_svc.mtu;
break;
case TEST_IDX_CHAR2_VAL:
e->data = (uint8_t *)test_svc.value2;
e->len = sizeof(test_svc.value1);
break;
case TEST_IDX_CHAR3_CUD:
e->data = (uint8_t *)test_svc.value3_cud;
e->len = sizeof(test_svc.value3_cud);
break;
case TEST_IDX_CHAR3_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST_IDX_CHAR5_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST_IDX_CHAR6_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST_IDX_CHAR7_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
default:
e->data = NULL;
e->len = 0;
break;
}
}
return 0;
}
static int event_gatt_indicate_confirm(ble_event_en event, void *event_data)
{
evt_data_gatt_indicate_cb_t *e = event_data;
if (e->err) {
printf("indicate fail, err %d\n", e->err);
} else {
printf("indicate char %d success\n", e->char_handle);
}
g_notify_data.indicate_ongoing = 0;
return 0;
}
struct k_delayed_work notify_work = {0};
void notify_action(struct k_work *work)
{
uint8_t data[2] = {1, 2};
if (g_notify_data.notify_type == CCC_VALUE_NOTIFY) {
ble_stack_gatt_notificate(g_bt_conn_handle, g_notify_data.notify_handle, data, 2);
} else if (g_notify_data.notify_type == CCC_VALUE_INDICATE) {
if (!g_notify_data.indicate_ongoing) {
g_notify_data.indicate_ongoing = 1;
ble_stack_gatt_indicate(g_bt_conn_handle, g_notify_data.notify_handle, data, 2);
}
}
}
static int event_char_ccc_change(ble_event_en event, void *event_data)
{
evt_data_gatt_char_ccc_change_t *e = (evt_data_gatt_char_ccc_change_t *)event_data;
uint16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc_handle, TEST_IDX_MAX, e->char_handle, handle_offset);
if (notify_work.work_q == NULL) {
k_delayed_work_init(¬ify_work, notify_action);
}
if (handle_offset == TEST_IDX_CHAR3_CCC) {
test_svc.ccc = e->ccc_value;
printf("ccc handle %d change %d\n", e->char_handle, test_svc.ccc);
g_notify_data.notify_handle = e->char_handle - 2;
if (test_svc.ccc == CCC_VALUE_NOTIFY) {
g_notify_data.notify_type = CCC_VALUE_NOTIFY;
k_delayed_work_submit(¬ify_work, 2000);
} else if (test_svc.ccc == CCC_VALUE_INDICATE) {
g_notify_data.notify_type = CCC_VALUE_INDICATE;
k_delayed_work_submit(¬ify_work, 2000);
} else {
g_notify_data.notify_type = 0;
}
}
return 0;
}
static int test_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GAP_CONN_CHANGE:
conn_change(event, event_data);
break;
case EVENT_GATT_CHAR_READ:
event_char_read(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE:
event_char_write(event, event_data);
break;
case EVENT_GATT_CHAR_CCC_CHANGE:
event_char_ccc_change(event, event_data);
break;
case EVENT_GATT_DISCOVERY_SVC:
case EVENT_GATT_DISCOVERY_INC_SVC:
case EVENT_GATT_DISCOVERY_CHAR:
case EVENT_GATT_DISCOVERY_CHAR_DES:
event_gatt_discovery(event, event_data);
break;
case EVENT_GATT_CHAR_READ_CB:
event_gatt_read_cb(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE_CB:
event_gatt_write_cb(event, event_data);
break;
case EVENT_GATT_NOTIFY:
event_gatt_notify(event, event_data);
break;
case EVENT_GATT_INDICATE_CB:
event_gatt_indicate_confirm(event, event_data);
break;
case EVENT_GATT_MTU_EXCHANGE:
event_gatt_mtu_exchange(event, event_data);
break;
default:
break;
}
return 0;
}
static ble_event_cb_t ble_cb1 = {
.callback = test_event_callback,
};
static int event2_char_write(ble_event_en event, void *event_data)
{
evt_data_gatt_char_write_t *e = (evt_data_gatt_char_write_t *)event_data;
int16_t handle_offset = 0;
static int w_len = 0;
static int w_len2 = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc2_handle, TEST2_IDX_MAX, e->char_handle, handle_offset);
printf("event_char_write conn_handle %d char_handle %d len %ld offset %d\n",
e->conn_handle, e->char_handle, e->len, e->offset);
hexdump(e->data, e->len);
switch (handle_offset) {
case TEST2_IDX_CHAR3_VAL:
if (e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (e->flag) {
e->len = 0;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
case TEST2_IDX_CHAR4_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST2_IDX_CHAR5_VAL:
if (e->flag) {
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
if (e->offset == 0) {
w_len = 0;
}
w_len += e->len;
e->len = 0;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
if (w_len > sizeof(test_svc.value4)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len = 0;
memcpy(test_svc.value4 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value4)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value4));
break;
case TEST2_IDX_CHAR6_VAL:
if (e->flag) {
if (e->offset == 0) {
w_len2 = 0;
}
w_len2 += e->len;
e->len = 0;
return 0;
}
if (w_len2 > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_ATTRIBUTE_LEN;
return 0;
}
w_len2 = 0;
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
if (e->offset + e->len > sizeof(test_svc.value3)) {
e->len = -ATT_ERR_INVALID_OFFSET;
return 0;
}
memcpy(test_svc.value3 + e->offset, e->data, BLE_MIN(e->len, sizeof(test_svc.value3)));
e->len = BLE_MIN(e->len, sizeof(test_svc.value3));
break;
default:
e->len = 0;
break;
}
return 0;
}
static int event2_char_read(ble_event_en event, void *event_data)
{
evt_data_gatt_char_read_t *e = (evt_data_gatt_char_read_t *)event_data;
int16_t handle_offset = 0;
BLE_CHAR_RANGE_CHECK(test_svc.svc2_handle, TEST2_IDX_MAX, e->char_handle, handle_offset);
switch (handle_offset) {
case TEST2_IDX_CHAR1_VAL:
if (g_security_level < 2) {
e->len = -ATT_ERR_AUTHORIZATION;
return 0;
}
e->data = (uint8_t *)test_svc.value1;
e->len = sizeof(test_svc.value1);
break;
case TEST2_IDX_CHAR2_VAL:
if (ble_stack_enc_key_size_get(e->conn_handle) < 10) {
e->len = -ATT_ERR_ENCRYPTION_KEY_SIZE;
return 0;
}
e->data = (uint8_t *)test_svc.value2;
e->len = sizeof(test_svc.value2);
break;
case TEST2_IDX_CHAR3_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
case TEST2_IDX_CHAR4_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST2_IDX_CHAR5_VAL:
e->data = (uint8_t *)test_svc.value4;
e->len = sizeof(test_svc.value4);
break;
case TEST2_IDX_CHAR6_VAL:
e->data = (uint8_t *)test_svc.value3;
e->len = sizeof(test_svc.value3);
break;
default:
e->data = NULL;
e->len = 0;
break;
}
return 0;
}
static int test2_event_callback(ble_event_en event, void *event_data)
{
switch (event) {
case EVENT_GATT_CHAR_READ:
event2_char_read(event, event_data);
break;
case EVENT_GATT_CHAR_WRITE:
event2_char_write(event, event_data);
break;
default:
break;
}
return 0;
}
static ble_event_cb_t ble_cb2 = {
.callback = test2_event_callback,
};
int cmd_gatt_register_test_svc(int argc, char *argv[])
{
int ret;
if (!strcmp(argv[0], "gatt-register-service")) {
ret = ble_stack_gatt_registe_service(&test_service, test_attrs, BLE_ARRAY_NUM(test_attrs));
if (ret < 0) {
printf("Registering test services faild (%d)\n", ret);
return ret;
}
test_svc.svc_handle = ret;
ret = ble_stack_event_register(&ble_cb1);
} else {
ret = ble_stack_gatt_registe_service(&test2_service, test2_attrs, BLE_ARRAY_NUM(test2_attrs));
if (ret < 0) {
printf("Registering test services faild (%d)\n", ret);
return ret;
}
test_svc.svc2_handle = ret;
ret = ble_stack_event_register(&ble_cb2);
}
if (ret) {
return ret;
}
printf("Registering test services\n");
return 0;
}
int cmd_gatt_unregister_test_svc(int argc, char *argv[])
{
printf("Unregistering test vendor services\n");
return 0;
}
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/test/gatt.c | C | apache-2.0 | 38,944 |
/** @file
* @brief Bluetooth Controller Ticker functions
*
*/
/*
* Copyright (c) 2017-2018 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <shell/shell.h>
#include <misc/printk.h>
#if defined(CONFIG_SOC_FAMILY_NRF)
#include "../controller/hal/nrf5/ticker.h"
#endif /* CONFIG_SOC_FAMILY_NRF */
#include "../controller/util/memq.h"
#include "../controller/util/mayfly.h"
#include "../controller/ticker/ticker.h"
#define TICKER_SHELL_MODULE "ticker"
#if defined(CONFIG_BT_MAX_CONN)
#define TICKERS_MAX (CONFIG_BT_MAX_CONN + 2)
#else
#define TICKERS_MAX 2
#endif
static void ticker_op_done(bt_u32_t err, void *context)
{
*((bt_u32_t volatile *)context) = err;
}
int cmd_ticker_info(int argc, char *argv[])
{
struct {
u8_t id;
bt_u32_t ticks_to_expire;
} tickers[TICKERS_MAX];
bt_u32_t ticks_to_expire;
bt_u32_t ticks_current;
u8_t tickers_count;
u8_t ticker_id;
u8_t retry;
u8_t i;
ticker_id = TICKER_NULL;
ticks_to_expire = 0;
ticks_current = 0;
tickers_count = 0;
retry = 4;
do {
bt_u32_t volatile err_cb = TICKER_STATUS_BUSY;
bt_u32_t ticks_previous;
bt_u32_t err;
ticks_previous = ticks_current;
err = ticker_next_slot_get(0, MAYFLY_CALL_ID_PROGRAM,
&ticker_id, &ticks_current,
&ticks_to_expire,
ticker_op_done, (void *)&err_cb);
if (err == TICKER_STATUS_BUSY) {
while (err_cb == TICKER_STATUS_BUSY) {
ticker_job_sched(0, MAYFLY_CALL_ID_PROGRAM);
}
}
if ((err_cb != TICKER_STATUS_SUCCESS) ||
(ticker_id == TICKER_NULL)) {
printk("Query done (0x%02x, err= %u).\n", ticker_id,
err);
break;
}
if (ticks_current != ticks_previous) {
retry--;
if (!retry) {
printk("Retry again, tickers too busy now.\n");
return -EAGAIN;
}
if (tickers_count) {
tickers_count = 0;
printk("Query reset, %u retries remaining.\n",
retry);
}
}
tickers[tickers_count].id = ticker_id;
tickers[tickers_count].ticks_to_expire = ticks_to_expire;
tickers_count++;
} while (tickers_count < TICKERS_MAX);
printk("Tickers: %u.\n", tickers_count);
printk("Tick: %u (%uus).\n", ticks_current,
HAL_TICKER_TICKS_TO_US(ticks_current));
if (!tickers_count) {
return 0;
}
printk("---------------------\n");
printk(" id offset offset\n");
printk(" (tick) (us)\n");
printk("---------------------\n");
for (i = 0; i < tickers_count; i++) {
printk("%03u %08u %08u\n", tickers[i].id,
tickers[i].ticks_to_expire,
HAL_TICKER_TICKS_TO_US(tickers[i].ticks_to_expire));
}
printk("---------------------\n");
return 0;
}
static const struct shell_cmd ticker_commands[] = {
{ "info", cmd_ticker_info, "Enumerate active ticker details."},
{ NULL, NULL, NULL}
};
SHELL_REGISTER(TICKER_SHELL_MODULE, ticker_commands);
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/bt_host/ticker.c | C | apache-2.0 | 2,843 |
##
# Copyright (C) 2017 C-SKY Microsystems Co., All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.crg/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.
##
ifeq ($(CONFIG_BT), y)
L_PATH := $(call cur-dir)
include $(DEFINE_LOCAL)
L_MODULE := libbt_shell
L_CFLAGS := -Wall
include $(L_PATH)/../bt_defconfig
L_INCS += $(L_PATH)/../include $(L_PATH)/../bt_host/port/include $(L_PATH)/../bt_host/port/aos/include $(L_PATH)/../bt_host \
$(L_PATH)/../bt_host/host
ifeq ($(CONFIG_BT_SHELL), y)
L_INCS += $(L_PATH)/bt_host
ifeq ($(CONFIG_BT_TEST), y)
L_INCS += $(L_PATH)/bt_host/test
L_SRCS += bt_host/test/bt.c
else
L_SRCS += bt_host/bt.c
endif
ifeq ($(CONFIG_BT_CONN), y)
ifeq ($(CONFIG_BT_TEST), y)
L_SRCS += bt_host/test/gatt.c
else
L_SRCS += bt_host/gatt.c
endif
endif
endif
ifeq ($(CONFIG_BT_MESH), y)
ifeq ($(CONFIG_BT_MESH_SHELL), y)
L_SRCS += bt_mesh/shell.c
endif
endif
include $(BUILD_MODULE)
endif
| YifuLiu/AliOS-Things | components/ble_host/bt_shell/build.mk | Makefile | apache-2.0 | 1,397 |
/* atomic operations */
/*
* Copyright (c) 1997-2015, Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __ATOMIC_H__
#define __ATOMIC_H__
#include <ble_types/types.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef int atomic_t;
typedef atomic_t atomic_val_t;
/**
* @defgroup atomic_apis Atomic Services APIs
* @ingroup kernel_apis
* @{
*/
/**
* @brief Atomic compare-and-set.
*
* This routine performs an atomic compare-and-set on @a target. If the current
* value of @a target equals @a old_value, @a target is set to @a new_value.
* If the current value of @a target does not equal @a old_value, @a target
* is left unchanged.
*
* @param target Address of atomic variable.
* @param old_value Original value to compare against.
* @param new_value New value to store.
* @return 1 if @a new_value is written, 0 otherwise.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline int atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value)
{
return __atomic_compare_exchange_n(target, &old_value, new_value,
0, __ATOMIC_SEQ_CST,
__ATOMIC_SEQ_CST);
}
#else
extern int atomic_cas(atomic_t *target, atomic_val_t old_value,
atomic_val_t new_value);
#endif
/**
*
* @brief Atomic addition.
*
* This routine performs an atomic addition on @a target.
*
* @param target Address of atomic variable.
* @param value Value to add.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_add(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_add(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic subtraction.
*
* This routine performs an atomic subtraction on @a target.
*
* @param target Address of atomic variable.
* @param value Value to subtract.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_sub(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic increment.
*
* This routine performs an atomic increment by 1 on @a target.
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_inc(atomic_t *target)
{
return atomic_add(target, 1);
}
#else
extern atomic_val_t atomic_inc(atomic_t *target);
#endif
/**
*
* @brief Atomic decrement.
*
* This routine performs an atomic decrement by 1 on @a target.
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_dec(atomic_t *target)
{
return atomic_sub(target, 1);
}
#else
extern atomic_val_t atomic_dec(atomic_t *target);
#endif
/**
*
* @brief Atomic get.
*
* This routine performs an atomic read on @a target.
*
* @param target Address of atomic variable.
*
* @return Value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_get(const atomic_t *target)
{
return __atomic_load_n(target, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_get(const atomic_t *target);
#endif
/**
*
* @brief Atomic get-and-set.
*
* This routine atomically sets @a target to @a value and returns
* the previous value of @a target.
*
* @param target Address of atomic variable.
* @param value Value to write to @a target.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)
{
/* This builtin, as described by Intel, is not a traditional
* test-and-set operation, but rather an atomic exchange operation. It
* writes value into *ptr, and returns the previous contents of *ptr.
*/
return __atomic_exchange_n(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_set(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic clear.
*
* This routine atomically sets @a target to zero and returns its previous
* value. (Hence, it is equivalent to atomic_set(target, 0).)
*
* @param target Address of atomic variable.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_clear(atomic_t *target)
{
return atomic_set(target, 0);
}
#else
extern atomic_val_t atomic_clear(atomic_t *target);
#endif
/**
*
* @brief Atomic bitwise inclusive OR.
*
* This routine atomically sets @a target to the bitwise inclusive OR of
* @a target and @a value.
*
* @param target Address of atomic variable.
* @param value Value to OR.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_or(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_or(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise exclusive OR (XOR).
*
* This routine atomically sets @a target to the bitwise exclusive OR (XOR) of
* @a target and @a value.
*
* @param target Address of atomic variable.
* @param value Value to XOR
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_xor(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise AND.
*
* This routine atomically sets @a target to the bitwise AND of @a target
* and @a value.
*
* @param target Address of atomic variable.
* @param value Value to AND.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_and(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_and(atomic_t *target, atomic_val_t value);
#endif
/**
*
* @brief Atomic bitwise NAND.
*
* This routine atomically sets @a target to the bitwise NAND of @a target
* and @a value. (This operation is equivalent to target = ~(target & value).)
*
* @param target Address of atomic variable.
* @param value Value to NAND.
*
* @return Previous value of @a target.
*/
#ifdef CONFIG_ATOMIC_OPERATIONS_BUILTIN
static inline atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value)
{
return __atomic_fetch_nand(target, value, __ATOMIC_SEQ_CST);
}
#else
extern atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value);
#endif
/**
* @brief Initialize an atomic variable.
*
* This macro can be used to initialize an atomic variable. For example,
* @code atomic_t my_var = ATOMIC_INIT(75); @endcode
*
* @param i Value to assign to atomic variable.
*/
#define ATOMIC_INIT(i) (i)
/**
* @cond INTERNAL_HIDDEN
*/
#define ATOMIC_BITS (sizeof(atomic_val_t) * 8)
#define ATOMIC_MASK(bit) (1 << ((bit) & (ATOMIC_BITS - 1)))
#define ATOMIC_ELEM(addr, bit) ((addr) + ((bit) / ATOMIC_BITS))
/**
* INTERNAL_HIDDEN @endcond
*/
/**
* @brief Define an array of atomic variables.
*
* This macro defines an array of atomic variables containing at least
* @a num_bits bits.
*
* @note
* If used from file scope, the bits of the array are initialized to zero;
* if used from within a function, the bits are left uninitialized.
*
* @param name Name of array of atomic variables.
* @param num_bits Number of bits needed.
*/
#define ATOMIC_DEFINE(name, num_bits) \
atomic_t name[1 + ((num_bits) - 1) / ATOMIC_BITS]
/**
* @brief Atomically test a bit.
*
* This routine tests whether bit number @a bit of @a target is set or not.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_bit(const atomic_t *target, int bit)
{
atomic_val_t val = atomic_get(ATOMIC_ELEM(target, bit));
return (1 & (val >> (bit & (ATOMIC_BITS - 1))));
}
/**
* @brief Atomically test and clear a bit.
*
* Atomically clear bit number @a bit of @a target and return its old value.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_and_clear_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_val_t old;
old = atomic_and(ATOMIC_ELEM(target, bit), ~mask);
return (old & mask) != 0;
}
/**
* @brief Atomically set a bit.
*
* Atomically set bit number @a bit of @a target and return its old value.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return 1 if the bit was set, 0 if it wasn't.
*/
static inline int atomic_test_and_set_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_val_t old;
old = atomic_or(ATOMIC_ELEM(target, bit), mask);
return (old & mask) != 0;
}
/**
* @brief Atomically clear a bit.
*
* Atomically clear bit number @a bit of @a target.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return N/A
*/
static inline void atomic_clear_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_and(ATOMIC_ELEM(target, bit), ~mask);
}
/**
* @brief Atomically set a bit.
*
* Atomically set bit number @a bit of @a target.
* The target may be a single atomic variable or an array of them.
*
* @param target Address of atomic variable or array.
* @param bit Bit number (starting from 0).
*
* @return N/A
*/
static inline void atomic_set_bit(atomic_t *target, int bit)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_or(ATOMIC_ELEM(target, bit), mask);
}
static inline void atomic_set_bit_to(atomic_t *target, int bit, bool val)
{
atomic_val_t mask = ATOMIC_MASK(bit);
atomic_or(ATOMIC_ELEM(target, bit), mask);
if (val)
{
atomic_or(ATOMIC_ELEM(target, bit), mask);
}
else
{
atomic_and(ATOMIC_ELEM(target, bit), ~mask);
}
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __ATOMIC_H__ */
| YifuLiu/AliOS-Things | components/ble_host/include/atomic.h | C | apache-2.0 | 10,715 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef __BLE_CONFIG_H_
#define __BLE_CONFIG_H_
#include <ble_default_config.h>
#ifdef CONFIG_BT_MESH
#include "ble_mesh_default_config.h"
#endif
#endif //__BLE_CONFIG_H_ | YifuLiu/AliOS-Things | components/ble_host/include/ble_config.h | C | apache-2.0 | 238 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef _BLE_DEFAULT_CONFIG_H_
#define _BLE_DEFAULT_CONFIG_H_
#ifndef CONFIG_BT
#error "CONFIG_BT is not defined!!!"
#endif
#ifdef CONFIG_BT
#ifndef CONFIG_NET_BUF_USER_DATA_SIZE
#define CONFIG_NET_BUF_USER_DATA_SIZE 4
#endif
#ifndef CONFIG_BT_HCI
#define CONFIG_BT_HCI 1
#endif
#ifdef CONFIG_BT_HCI
#ifndef CONFIG_BT_H4
/* Bluetooth H:4 UART driver. Requires hardware flow control lines to be available. */
#define CONFIG_BT_H4 1
#endif
#ifdef CONFIG_BT_H5
#undef CONFIG_BT_H4
#endif
#ifdef CONFIG_BT_H4
//#define CONFIG_BT_RECV_IS_RX_THREAD 1
#endif
#ifndef CONFIG_BT_CENTRAL
//#define CONFIG_BT_CENTRAL 1
#endif
#ifndef CONFIG_BT_PERIPHERAL
#ifndef CONFIG_BT_CENTRAL
#define CONFIG_BT_PERIPHERAL 1
#endif
#endif
/* Select this for LE Peripheral role support. */
#ifdef CONFIG_BT_PERIPHERAL
#ifndef CONFIG_BT_BROADCASTER
#define CONFIG_BT_BROADCASTER 1
#endif
#ifndef CONFIG_BT_CONN
#define CONFIG_BT_CONN 1
#endif
#endif // CONFIG_BT_PERIPHERAL
/* Select this for LE Central role support. */
#ifdef CONFIG_BT_CENTRAL
#ifndef CONFIG_BT_OBSERVER
#define CONFIG_BT_OBSERVER 1
#endif
#ifndef CONFIG_BT_CONN
#define CONFIG_BT_CONN 1
#endif
#endif // CONFIG_BT_CENTRAL
/* Select this for LE Broadcaster role support. */
#ifndef CONFIG_BT_PERIPHERAL
#ifndef CONFIG_BT_OBSERVER
#ifndef CONFIG_BT_BROADCASTER
#define CONFIG_BT_BROADCASTER 1
#endif
#endif
#endif //!CONFIG_BT_PERIPHERAL
/* Select this for LE Observer role support. */
//#define CONFIG_BT_OBSERVER 1
/* Enable support for Bluetooth 5.0 PHY Update Procedure. */
#ifndef CONFIG_BT_PHY_UPDATE
#define CONFIG_BT_PHY_UPDATE 1
#endif
/* Enable support for Bluetooth 5.0 PHY Update Procedure. */
#ifndef CONFIG_BT_DATA_LEN_UPDATE
#define CONFIG_BT_DATA_LEN_UPDATE 1
#endif
#ifdef CONFIG_BT_CONN
/* Maximum number of simultaneous Bluetooth connections supported. */
#ifndef CONFIG_BT_MAX_CONN
#define CONFIG_BT_MAX_CONN 1
#endif
#ifndef CONFIG_BT_HCI_ACL_FLOW_CONTROL
//#define CONFIG_BT_HCI_ACL_FLOW_CONTROL 1
#endif
#endif //CONFIG_BT_CONN
#ifndef CONFIG_BT_HCI_HOST
#define CONFIG_BT_HCI_HOST 1
#endif
/* Number of buffers available for HCI commands. */
#ifndef CONFIG_BT_HCI_CMD_COUNT
#define CONFIG_BT_HCI_CMD_COUNT 2
#endif
/* Number of buffers available for incoming ACL packets or HCI events from the controller. */
#ifndef CONFIG_BT_RX_BUF_COUNT
#ifdef CONFIG_BT_RECV_IS_RX_THREAD
#define CONFIG_BT_RX_BUF_COUNT 3
#elif defined(CONFIG_BT_MESH)
#define CONFIG_BT_RX_BUF_COUNT 20
#else
#define CONFIG_BT_RX_BUF_COUNT 3
#endif
#endif
/* Number of discardable event buffers. */
#ifndef CONFIG_BT_DISCARDABLE_BUF_COUNT
#ifdef CONFIG_BT_MESH
#define CONFIG_BT_DISCARDABLE_BUF_COUNT 20
#else
#define CONFIG_BT_DISCARDABLE_BUF_COUNT 3
#endif
#endif
/* Size of discardable event buffers. */
#ifndef CONFIG_BT_DISCARDABLE_BUF_SIZE
#if defined(CONFIG_BT_BREDR) || defined(CONFIG_BT_EXT_ADV)
#define CONFIG_BT_DISCARDABLE_BUF_SIZE 257
#else
#define CONFIG_BT_DISCARDABLE_BUF_SIZE 45
#endif
#endif
/* GATT Service Changed support. */
#ifndef CONFIG_BT_GATT_SERVICE_CHANGED
#define CONFIG_BT_GATT_SERVICE_CHANGED 1
#endif
/* GATT dynamic database support. */
#ifndef CONFIG_BT_GATT_DYNAMIC_DB
#define CONFIG_BT_GATT_DYNAMIC_DB
#endif
/* Maximum data size for each HCI RX buffer. This size includes
everything starting with the ACL or HCI event headers. Note that
buffer sizes are always rounded up to the nearest multiple of 4,
so if this Kconfig value is something else then there will be some
wasted space. The minimum of 73 has been taken for LE SC which has
an L2CAP MTU of 65 bytes. On top of this there's the L2CAP header
(4 bytes) and the ACL header (also 4 bytes) which yields 73 bytes. */
#ifndef CONFIG_BT_RX_BUF_LEN
#ifdef CONFIG_BT_MESH_PROXY
#define CONFIG_BT_RX_BUF_LEN 77
#else
#define CONFIG_BT_RX_BUF_LEN 76
#endif
#endif
/* Stack size needed for executing bt_send with specified driver */
#ifndef CONFIG_BT_HCI_TX_STACK_SIZE
#define CONFIG_BT_HCI_TX_STACK_SIZE 1536
#endif
/* Stack size needed for executing bt_send with specified driver */
#ifndef CONFIG_BT_HCI_TX_PRIO
#define CONFIG_BT_HCI_TX_PRIO 7
#endif
/* Headroom that the driver needs for sending and receiving buffers. */
#ifndef CONFIG_BT_HCI_RESERVE
#if defined(CONFIG_BT_H4) || defined(CONFIG_BT_H5)
#define CONFIG_BT_HCI_RESERVE 1
#else
#define CONFIG_BT_HCI_RESERVE 1
#endif
#endif
/* Size of the receiving thread stack. This is the context from
which all event callbacks to the application occur. The
default value is sufficient for basic operation, but if the
application needs to do advanced things in its callbacks that
require extra stack space, this value can be increased to
accommodate for that. */
#ifndef CONFIG_BT_RX_STACK_SIZE
#define CONFIG_BT_RX_STACK_SIZE 2048
#endif
#ifndef CONFIG_BT_RX_PRIO
#define CONFIG_BT_RX_PRIO 8
#endif
#ifdef CONFIG_BT_HCI_HOST
/* Controller crypto feature */
#ifndef CONFIG_BT_CTLR_CRYPTO
//#define CONFIG_BT_CTLR_CRYPTO 1
#endif
/* Host crypto feature */
#ifndef CONFIG_BT_CTLR_CRYPTO
#define CONFIG_BT_HOST_CRYPTO 1
#endif
#ifndef CONFIG_BT_SETTINGS
#define CONFIG_BT_SETTINGS 1
#endif
/* Store Client Configuration Characteristic value right after it has
been updated.
By default, CCC is only stored on disconnection.
Choosing this option is safer for battery-powered devices or devices
that expect to be reset suddenly. However, it requires additional
workqueue stack space. */
#ifndef CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE
#ifdef CONFIG_BT_SETTINGS
//#define CONFIG_BT_SETTINGS_CCC_STORE_ON_WRITE 1
#endif
#endif
#ifdef CONFIG_BT_CONN
#ifdef CONFIG_BT_HCI_ACL_FLOW_CONTROL
#ifndef CONFIG_BT_ACL_RX_COUNT
#define CONFIG_BT_ACL_RX_COUNT 6
#endif
/* Maximum size of each incoming L2CAP PDU. */
#ifndef CONFIG_BT_L2CAP_RX_MTU
#ifdef CONFIG_BT_SMP
#define CONFIG_BT_L2CAP_RX_MTU 65
#else
#define CONFIG_BT_L2CAP_RX_MTU 23
#endif
#endif
#endif //CONFIG_BT_HCI_ACL_FLOW_CONTROL
/* Number of buffers available for outgoing L2CAP packets. */
#ifndef CONFIG_BT_L2CAP_TX_BUF_COUNT
#define CONFIG_BT_L2CAP_TX_BUF_COUNT 3
#endif
/* Maximum number of queued outgoing ATT PDUs. */
#ifndef CONFIG_BT_ATT_TX_MAX
#define CONFIG_BT_ATT_TX_MAX CONFIG_BT_L2CAP_TX_BUF_COUNT
#endif
/* Number of buffers available for fragments of TX buffers. Warning:
setting this to 0 means that the application must ensure that
queued TX buffers never need to be fragmented, i.e. that the
controller's buffer size is large enough. If this is not ensured,
and there are no dedicated fragment buffers, a deadlock may occur.
In most cases the default value of 2 is a safe bet. */
#ifndef CONFIG_BT_L2CAP_TX_FRAG_COUNT
#define CONFIG_BT_L2CAP_TX_FRAG_COUNT 2
#endif
/* Maximum L2CAP MTU for L2CAP TX buffers. */
#ifndef CONFIG_BT_L2CAP_TX_MTU
#ifdef CONFIG_BT_SMP
#define CONFIG_BT_L2CAP_TX_MTU 65
#else
#define CONFIG_BT_L2CAP_TX_MTU 23
#endif
#endif
/* Maximum number of pending TX buffers that have not yet been acknowledged by the controller.*/
#ifndef CONFIG_BT_CONN_TX_MAX
#define CONFIG_BT_CONN_TX_MAX 7
#endif
/* Initiate PHY Update Procedure on connection establishment.
Disable this if you want PHY Update Procedure feature supported but
want to rely on remote device to initiate the procedure at its
discretion.*/
#ifndef CONFIG_BT_AUTO_PHY_UPDATE
#ifdef CONFIG_BT_PHY_UPDATE
#define CONFIG_BT_AUTO_PHY_UPDATE 1
#endif
#endif
/* This option enables support for the Security Manager Protocol
(SMP), making it possible to pair devices over LE. */
#ifndef CONFIG_BT_SMP
//#define CONFIG_BT_SMP 1
#endif
#ifdef CONFIG_BT_SMP
#ifndef CONFIG_BT_RPA
#define CONFIG_BT_RPA 1
#endif
/* Enable local Privacy Feature support. This makes it possible
to use Resolvable Private Addresses (RPAs). */
#ifndef CONFIG_BT_PRIVACY
//#define CONFIG_BT_PRIVACY 1
#endif
/* This option defines how often resolvable private address is rotated.
Value is provided in seconds and defaults to 900 seconds (15 minutes). */
#ifdef CONFIG_BT_PRIVACY
#ifndef CONFIG_BT_RPA_TIMEOUT
#define CONFIG_BT_RPA_TIMEOUT 900
#endif
#endif
/*
Number of buffers in a separate buffer pool for events which
the HCI driver considers discardable. Examples of such events
could be e.g. Advertising Reports. The benefit of having such
a pool means that the if there is a heavy inflow of such events
it will not cause the allocation for other critical events to
block and may even eliminate deadlocks in some cases.
*/
#ifndef BT_DISCARDABLE_BUF_COUNT
#if defined(CONFIG_BT_MESH)
#define BT_DISCARDABLE_BUF_COUNT 20
#else
#define BT_DISCARDABLE_BUF_COUNT 3
#endif
#endif
/* This option enables data signing which is used for transferring
authenticated data in an unencrypted connection. */
#ifndef CONFIG_BT_SIGNING
//#define CONFIG_BT_SIGNING 1
#endif
/* This option enables support for Secure Connection Only Mode. In this
mode device shall only use Security Mode 1 Level 4 with exception
for services that only require Security Mode 1 Level 1 (no security).
Security Mode 1 Level 4 stands for authenticated LE Secure Connections
pairing with encryption. Enabling this option disables legacy pairing. */
#ifndef CONFIG_BT_SMP_SC_ONLY
//#define CONFIG_BT_SMP_SC_ONLY 1
#endif
/* This option disables LE legacy pairing and forces LE secure connection
pairing. All Security Mode 1 levels can be used with legacy pairing
disabled, but pairing with devices that do not support secure
connections pairing will not be supported.
To force a higher security level use "Secure Connections Only Mode"*/
#ifndef CONFIG_BT_SMP_SC_PAIR_ONLY
#ifdef CONFIG_BT_SMP_SC_ONLY
#define CONFIG_BT_SMP_SC_PAIR_ONLY 1
#endif
#endif
/* With this option enabled, the application will be able to call the
bt_passkey_set() API to set a fixed passkey. If set, the
pairing_confim() callback will be called for all incoming pairings. */
#ifndef CONFIG_BT_FIXED_PASSKEY
//#define CONFIG_BT_FIXED_PASSKEY 1
#endif
/* This option places Security Manager in a Debug Mode. In this mode
predefined Diffie-Hellman private/public key pair is used as described
in Core Specification Vol. 3, Part H, 2.3.5.6.1. This option should
only be enabled for debugging and should never be used in production.
If this option is enabled anyone is able to decipher encrypted air
traffic. */
#ifndef CONFIG_BT_USE_DEBUG_KEYS
//#define CONFIG_BT_USE_DEBUG_KEYS 1
#endif
/* This option enables support for Bondable Mode. In this mode,
Bonding flag in AuthReq of SMP Pairing Request/Response will be set
indicating the support for this mode. */
#ifndef CONFIG_BT_BONDABLE
#define CONFIG_BT_BONDABLE 1
#endif
/* With this option enabled, the Security Manager will set MITM option in
the Authentication Requirements Flags whenever local IO Capabilities
allow the generated key to be authenticated. */
#ifndef CONFIG_BT_SMP_ENFORCE_MITM
#define CONFIG_BT_SMP_ENFORCE_MITM 1
#endif
#endif //CONFIG_BT_SMP
/* This option enables support for LE Connection oriented Channels,
allowing the creation of dynamic L2CAP Channels. */
#ifndef CONFIG_BT_L2CAP_DYNAMIC_CHANNEL
//#define CONFIG_BT_L2CAP_DYNAMIC_CHANNEL 1
#endif
/* Enforce strict flow control semantics for incoming PDUs */
#ifndef CONFIG_BT_ATT_ENFORCE_FLOW
//#define CONFIG_BT_ATT_ENFORCE_FLOW 1
#endif
/* Number of buffers available for ATT prepare write, setting
this to 0 disables GATT long/reliable writes. */
#ifndef CONFIG_BT_ATT_PREPARE_COUNT
#define CONFIG_BT_ATT_PREPARE_COUNT 0
#endif
/* Number of ATT PDUs that can be at a single moment queued for
transmission. If the application tries to send more than this
amount the calls will block until an existing queued PDU gets
sent. */
#ifndef CONFIG_BT_ATT_TX_MAX
#define CONFIG_BT_ATT_TX_MAX 2
#endif
/* This option enables support for GATT Caching. When enabled the stack
will register Client Supported Features and Database Hash
characteristics which can be used by clients to detect if anything has
changed on the GATT database. */
#ifndef CONFIG_BT_GATT_CACHING
//#warning "CHECK CONFIG_BT_GATT_CACHING default config"
//#define CONFIG_BT_GATT_CACHING 1
#endif
/* When enable this option blocks notification and indications to client
to conform to the following statement from the Bluetooth 5.1
specification:
'...the server shall not send notifications and indications to such
a client until it becomes change-aware."
In case the service cannot deal with sudden errors (-EAGAIN) then it
shall not use this option. */
#ifndef CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE
#ifdef CONFIG_BT_GATT_CACHING
//#define CONFIG_BT_GATT_ENFORCE_CHANGE_UNAWARE 1
#endif
#endif
/* This option enables support for the GATT Client role. */
#ifndef CONFIG_BT_GATT_CLIENT
//#define CONFIG_BT_GATT_CLIENT 1
#endif
/* This option enables support for the GATT Read Multiple Characteristic
Values procedure. */
#ifndef CONFIG_BT_GATT_READ_MULTIPLE
#define CONFIG_BT_GATT_READ_MULTIPLE 1
#endif
/* Peripheral connection parameter update timeout in milliseconds. */
#ifndef CONFIG_BT_CONN_PARAM_UPDATE_TIMEOUT
#define CONFIG_BT_CONN_PARAM_UPDATE_TIMEOUT 5000
#endif
/* Maximum number of paired Bluetooth devices. The minimum (and
default) number is 1. */
#ifndef CONFIG_BT_MAX_PAIRED
#ifndef CONFIG_BT_SMP
#define CONFIG_BT_MAX_PAIRED 0
#else
#define CONFIG_BT_MAX_PAIRED 1
#endif
#endif
/* Configure peripheral preferred connection parameters */
#ifndef CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS
#ifdef CONFIG_BT_PERIPHERAL
#define CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS 1
#endif
#endif
#ifdef CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS
/* Peripheral preferred minimum connection interval in 1.25ms units */
#ifndef CONFIG_BT_PERIPHERAL_PREF_MIN_INT
#define CONFIG_BT_PERIPHERAL_PREF_MIN_INT 24
#endif
/* Peripheral preferred maximum connection interval in 1.25ms units */
#ifndef CONFIG_BT_PERIPHERAL_PREF_MAX_INT
#define CONFIG_BT_PERIPHERAL_PREF_MAX_INT 40
#endif
/* Peripheral preferred slave latency in Connection Intervals */
#ifndef CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY
#define CONFIG_BT_PERIPHERAL_PREF_SLAVE_LATENCY 0
#endif
/* Peripheral preferred supervision timeout in 10ms units */
#ifndef CONFIG_BT_PERIPHERAL_PREF_TIMEOUT
#define CONFIG_BT_PERIPHERAL_PREF_TIMEOUT 42
#endif
#endif //CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS
/* Timeout for pending LE Create Connection command in seconds */
#ifndef CONFIG_BT_CREATE_CONN_TIMEOUT
#define CONFIG_BT_CREATE_CONN_TIMEOUT 3
#endif
#endif //CONFIG_BT_CONN
#ifdef CONFIG_BT_OBSERVER
/* Scan interval used for background scanning in 0.625 ms units */
#ifndef CONFIG_BT_BACKGROUND_SCAN_INTERVAL
#define CONFIG_BT_BACKGROUND_SCAN_INTERVAL 2048
#endif
/* Scan window used for background scanning in 0.625 ms units */
#ifndef CONFIG_BT_BACKGROUND_SCAN_WINDOW
#define CONFIG_BT_BACKGROUND_SCAN_WINDOW 18
#endif
#endif //CONFIG_BT_OBSERVER
/* Enable this if you want to perform active scanning using the local
identity address as the scanner address. By default the stack will
always use a non-resolvable private address (NRPA) in order to avoid
disclosing local identity information. However, if the use case
requires disclosing it then enable this option. */
#ifndef CONFIG_BT_SCAN_WITH_IDENTITY
//#define CONFIG_BT_SCAN_WITH_IDENTITY 1
#endif
/* Enable this if you want to perform active scanning using the local
identity address as the scanner address. By default the stack will
always use a non-resolvable private address (NRPA) in order to avoid
disclosing local identity information. However, if the use case
requires disclosing it then enable this option. */
#ifndef CONFIG_BT_DEVICE_NAME_DYNAMIC
#define CONFIG_BT_DEVICE_NAME_DYNAMIC 1
#endif
/* Bluetooth device name storage size. Storage can be up to 248 bytes
long (excluding NULL termination). */
#ifndef CONFIG_BT_DEVICE_NAME_MAX
#ifdef CONFIG_BT_DEVICE_NAME_DYNAMIC
#define CONFIG_BT_DEVICE_NAME_MAX 28
#endif
#endif
/* Enabling this option allows remote GATT clients to write to device
name GAP characteristic. */
#ifndef CONFIG_BT_DEVICE_NAME_GATT_WRITABLE
#if defined(CONFIG_BT_DEVICE_NAME_DYNAMIC) && defined(CONFIG_BT_CONN)
#define CONFIG_BT_DEVICE_NAME_GATT_WRITABLE 28
#endif
#endif
/* Bluetooth device name. Name can be up to 248 bytes long (excluding
NULL termination). Can be empty string. */
#ifndef CONFIG_BT_DEVICE_NAME
#define CONFIG_BT_DEVICE_NAME "YoC Test"
#endif
/* Bluetooth device appearance. For the list of possible values please
consult the following link:
https://www.bluetooth.com/specifications/assigned-numbers */
#ifndef CONFIG_BT_DEVICE_APPEARANCE
#define CONFIG_BT_DEVICE_APPEARANCE 0
#endif
#ifndef CONFIG_BT_ID_MAX
#define CONFIG_BT_ID_MAX 1
#endif
#endif //CONFIG_BT_HCI_HOST
/* Enable ECDH key generation support */
#ifndef CONFIG_BT_ECC
//#define CONFIG_BT_ECC 1
#endif
#ifndef CONFIG_BT_TINYCRYPT_ECC
#define CONFIG_BT_TINYCRYPT_ECC 1
#endif
#ifdef CONFIG_BT_DEBUG
#ifndef CONFIG_BT_DEBUG_LOG
//#define CONFIG_BT_DEBUG_LOG 1
#endif
#ifndef CONFIG_BT_DEBUG_SETTINGS
//#define CONFIG_BT_DEBUG_SETTINGS 1
#endif
#ifndef CONFIG_BT_DEBUG_HCI_CORE
//#define CONFIG_BT_DEBUG_HCI_CORE 1
#endif
#ifndef CONFIG_BT_DEBUG_CONN
//#define CONFIG_BT_DEBUG_CONN 1
#endif
#ifndef CONFIG_BT_DEBUG_KEYS
//#define CONFIG_BT_DEBUG_KEYS 1
#endif
#ifndef CONFIG_BT_DEBUG_L2CAP
//#define CONFIG_BT_DEBUG_L2CAP 1
#endif
#ifndef CONFIG_BT_DEBUG_SMP
//#define CONFIG_BT_DEBUG_SMP 1
#endif
#ifndef CONFIG_BT_SMP_SELFTEST
//#define CONFIG_BT_SMP_SELFTEST 1
#endif
#ifndef CONFIG_BT_DEBUG_ATT
//#define CONFIG_BT_DEBUG_ATT 1
#endif
#ifndef CONFIG_BT_DEBUG_GATT
//#define CONFIG_BT_DEBUG_GATT 1
#endif
#endif //CONFIG_BT_DEBUG
#ifndef CONFIG_BT_SHELL
//#define CONFIG_BT_SHELL 1
#endif
#endif //CONFIG_BT_HCI
#endif //CONFIG_BT
#endif //_BLE_DEFAULT_CONFIG_H_
| YifuLiu/AliOS-Things | components/ble_host/include/ble_default_config.h | C | apache-2.0 | 17,912 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef _BLE_OS_H
#define _BLE_OS_H
#include <stddef.h>
#include <ble_types/types.h>
#include <misc/slist.h>
#include <misc/dlist.h>
#include <misc/__assert.h>
#include <atomic.h>
#include <k_api.h>
//#include <aos/osal_debug.h>
#include <ble_config.h>
#include <ble_os_port.h>
#include <net/buf.h>
#include <work.h>
#include <port/kport.h>
#endif /* _BLE_OS_H */
| YifuLiu/AliOS-Things | components/ble_host/include/ble_os.h | C | apache-2.0 | 431 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef _BLE_OS_PORT_H
#define _BLE_OS_PORT_H
#ifndef ASSERT
#define ASSERT __ASSERT
#endif
#include <k_api.h>
#include <misc/dlist.h>
#include <misc/slist.h>
#define _STRINGIFY(x) #x
#define ___in_section(a, b, c) \
__attribute__((section("." _STRINGIFY(a) \
"." _STRINGIFY(b) \
"." _STRINGIFY(c))))
//#define __in_section(a, b, c) ___in_section(a, b, c)
#define __in_section(a, b, c)
#define __in_section_unique(seg) ___in_section(seg, _FILE_PATH_HASH, \
__COUNTER__)
#define __in_btstack_section() __in_section(btstack, static, func)
#ifndef ARG_UNUSED
#define ARG_UNUSED(x) (void)(x)
#endif
#ifndef __packed
#define __packed __attribute__((__packed__))
#endif
#ifndef __printf_like
#define __printf_like(f, a) __attribute__((format (printf, f, a)))
#endif
#define STACK_ALIGN 4
#define __stack __aligned(STACK_ALIGN)
#define K_FOREVER -1
#define K_NO_WAIT 0
/* Unaligned access */
#define UNALIGNED_GET(p) \
__extension__ ({ \
struct __attribute__((__packed__)) { \
__typeof__(*(p)) __v; \
} *__p = (__typeof__(__p)) (p); \
__p->__v; \
})
#ifndef UNUSED
#define UNUSED(x) (void)x
#endif
enum _poll_types_bits {
_POLL_TYPE_IGNORE,
_POLL_TYPE_SIGNAL,
_POLL_TYPE_SEM_AVAILABLE,
_POLL_TYPE_DATA_AVAILABLE,
_POLL_NUM_TYPES
};
#define _POLL_TYPE_BIT(type) (1 << ((type)-1))
enum _poll_states_bits {
_POLL_STATE_NOT_READY,
_POLL_STATE_SIGNALED,
_POLL_STATE_SEM_AVAILABLE,
_POLL_STATE_DATA_AVAILABLE,
_POLL_NUM_STATES
};
#define _POLL_STATE_BIT(state) (1 << ((state)-1))
#define _POLL_EVENT_NUM_UNUSED_BITS \
(32 - (0 + 8 /* tag */ \
+ _POLL_NUM_TYPES + _POLL_NUM_STATES + 1 /* modes */ \
))
#define K_POLL_SIGNAL_INITIALIZER(obj) \
{ \
.poll_events = SYS_DLIST_STATIC_INIT(&obj.poll_events), .signaled = 0, \
.result = 0, \
}
struct k_poll_event {
sys_dnode_t _node;
struct _poller *poller;
uint32_t tag : 8;
uint32_t type :
_POLL_NUM_TYPES;
uint32_t state :
_POLL_NUM_STATES;
uint32_t mode : 1;
uint32_t unused :
_POLL_EVENT_NUM_UNUSED_BITS;
union {
void *obj;
struct k_poll_signal *signal;
struct k_sem *sem;
struct kfifo *fifo;
struct k_queue *queue;
};
};
struct k_poll_signal {
sys_dlist_t poll_events;
unsigned int signaled;
int result;
};
#define K_POLL_STATE_NOT_READY 0
#define K_POLL_STATE_EADDRINUSE 1
#define K_POLL_STATE_SIGNALED 2
#define K_POLL_STATE_SEM_AVAILABLE 3
#define K_POLL_STATE_DATA_AVAILABLE 4
#define K_POLL_STATE_FIFO_DATA_AVAILABLE K_POLL_STATE_DATA_AVAILABLE
#define K_POLL_STATE_DATA_RECV 5
#define K_POLL_STATE_TX_SYNC_DONE 6
#define K_POLL_TYPE_IGNORE 0
#define K_POLL_TYPE_SIGNAL 1
#define K_POLL_TYPE_SEM_AVAILABLE 2
#define K_POLL_TYPE_DATA_AVAILABLE 3
#define K_POLL_TYPE_FIFO_DATA_AVAILABLE K_POLL_TYPE_DATA_AVAILABLE
#define K_POLL_TYPE_DATA_RECV 5
#define K_POLL_TYPE_EARLIER_WORK 6
#define K_POLL_EVENT_STATIC_INITIALIZER(event_type, event_mode, event_obj, \
event_tag) \
{ \
.type = event_type, .tag = event_tag, .state = K_POLL_STATE_NOT_READY, \
.mode = event_mode, .unused = 0, { .obj = event_obj }, \
}
extern void k_poll_signal_raise(struct k_poll_signal *signal, int result);
#if 0 //YULONG
extern int k_poll(struct k_poll_event *events, int num_events,
int32_t timeout);
extern void k_poll_event_init(struct k_poll_event *event, uint32_t type,
int mode, void *obj);
extern void _handle_obj_poll_events(sys_dlist_t *events, uint32_t state);
#endif
/* public - polling modes */
enum k_poll_modes {
/* polling thread does not take ownership of objects when available */
K_POLL_MODE_NOTIFY_ONLY = 0,
K_POLL_NUM_MODES
};
#define BT_STACK(name, size) \
k_thread_stack_t name[(size) / sizeof(k_thread_stack_t)];
#define BT_STACK_NOINIT(name, size) \
k_thread_stack_t name[(size) / sizeof(k_thread_stack_t)];
static inline void k_call_stacks_analyze()
{
return;
}
static inline char *K_THREAD_STACK_BUFFER(uint32_t *sym)
{
return NULL;
}
#define k_oops() while(1)
void *k_current_get(void);
uint32_t k_get_tick(void);
uint32_t k_tick2ms(uint32_t tick);
void k_sleep(int32_t ms);
uint32_t k_uptime_get_32();
#define _DO_CONCAT(x, y) x ## y
#define _CONCAT(x, y) _DO_CONCAT(x, y)
#ifndef BUILD_ASSERT
/* compile-time assertion that makes the build fail */
#define BUILD_ASSERT(EXPR) \
enum _CONCAT(__build_assert_enum, __COUNTER__) { \
_CONCAT(__build_assert, __COUNTER__) = 1 / !!(EXPR) \
}
#endif
#ifndef BUILD_ASSERT_MSG
/* build assertion with message -- common implementation swallows message. */
#define BUILD_ASSERT_MSG(EXPR, MSG) BUILD_ASSERT(EXPR)
#endif
#ifndef MSEC_PER_SEC
#define MSEC_PER_SEC 1000
#endif
/**
* @brief Generate timeout delay from milliseconds.
*
* This macro generates a timeout delay that that instructs a kernel API
* to wait up to @a ms milliseconds to perform the requested operation.
*
* @param ms Duration in milliseconds.
*
* @return Timeout delay value.
*/
#define K_MSEC(ms) (ms)
/**
* @brief Generate timeout delay from seconds.
*
* This macro generates a timeout delay that that instructs a kernel API
* to wait up to @a s seconds to perform the requested operation.
*
* @param s Duration in seconds.
*
* @return Timeout delay value.
*/
#define K_SECONDS(s) K_MSEC((s) * MSEC_PER_SEC)
/**
* @brief Generate timeout delay from minutes.
*
* This macro generates a timeout delay that that instructs a kernel API
* to wait up to @a m minutes to perform the requested operation.
*
* @param m Duration in minutes.
*
* @return Timeout delay value.
*/
#define K_MINUTES(m) K_SECONDS((m) * 60)
/**
* @brief Generate timeout delay from hours.
*
* This macro generates a timeout delay that that instructs a kernel API
* to wait up to @a h hours to perform the requested operation.
*
* @param h Duration in hours.
*
* @return Timeout delay value.
*/
#define K_HOURS(h) K_MINUTES((h) * 60)
#define popcount(x) __builtin_popcount(x)
static inline unsigned int find_msb_set(uint32_t op)
{
if (op == 0) {
return 0;
}
return 32 - __builtin_clz(op);
}
static inline unsigned int find_lsb_set(uint32_t op)
{
return __builtin_ffs(op);
}
#define k_thread_foreach(...)
#define k_free free
#define snprintk snprintf
#ifndef __aligned
#define __aligned(x) __attribute__((__aligned__(x)))
#endif
#ifndef BIT
#define BIT(nr) (1UL << (nr))
#endif
#define __noinit
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) \
((unsigned long) (sizeof(array) / sizeof((array)[0])))
#endif
typedef kbuf_queue_t _queue_t;
typedef ksem_t _sem_t;
typedef ktask_t _task_t;
typedef cpu_stack_t _stack_element_t;
typedef kmutex_t _mutex_t;
/* Log define*/
enum {
LOG_LEVEL_NONE = 0,
LOG_LEVEL_FATAL,
LOG_LEVEL_ERROR,
LOG_LEVEL_WARN,
LOG_LEVEL_INFO,
LOG_LEVEL_DEBUG,
LOG_LEVEL_MAX_BIT
};
#define BT_TAG "AOSBT"
#define BT_LOG_DBG 1
#if BT_LOG_DBG
#define SYS_LOG_DBG(fmt,...) LOGD(BT_TAG, "%s:"fmt, __FUNCTION__, ##__VA_ARGS__)
#define SYS_LOG_INF(fmt,...) LOGI(BT_TAG, "%s:"fmt, __FUNCTION__, ##__VA_ARGS__)
#define SYS_LOG_WRN(fmt,...) LOGW(BT_TAG, "%s:"fmt, __FUNCTION__, ##__VA_ARGS__)
#define SYS_LOG_ERR(fmt,...) LOGE(BT_TAG, "%s:"fmt, __FUNCTION__, ##__VA_ARGS__)
#else
#define SYS_LOG_DBG(fmt,...) LOGD(BT_TAG, fmt, ##__VA_ARGS__)
#define SYS_LOG_INF(fmt,...) LOGI(BT_TAG, fmt, ##__VA_ARGS__)
#define SYS_LOG_WRN(fmt,...) LOGW(BT_TAG, fmt, ##__VA_ARGS__)
#define SYS_LOG_ERR(fmt,...) LOGE(BT_TAG, fmt, ##__VA_ARGS__)
#endif
struct k_queue {
_sem_t sem;
sys_slist_t queue_list;
sys_dlist_t poll_events;
};
extern void k_queue_init(struct k_queue *queue);
extern void k_queue_uninit(struct k_queue *queue);
extern void k_queue_cancel_wait(struct k_queue *queue);
extern void k_queue_append(struct k_queue *queue, void *data);
extern void k_queue_prepend(struct k_queue *queue, void *data);
extern void k_queue_insert(struct k_queue *queue, void *prev, void *data);
extern void k_queue_append_list(struct k_queue *queue, void *head, void *tail);
extern void *k_queue_get(struct k_queue *queue, int32_t timeout);
extern int k_queue_is_empty(struct k_queue *queue);
extern int k_queue_count(struct k_queue *queue);
static inline bool k_queue_remove(struct k_queue *queue, void *data)
{
return sys_slist_find_and_remove(&queue->queue_list, (sys_snode_t *)data);
}
static inline void *k_queue_first_entry(struct k_queue *queue)
{
return sys_slist_peek_head(&queue->queue_list);
}
/* lifo define*/
struct k_lifo {
struct k_queue _queue;
};
#define k_lifo_init(lifo) k_queue_init((struct k_queue *)lifo)
#define k_lifo_put(lifo, data) k_queue_prepend((struct k_queue *)lifo, data)
#define k_lifo_get(lifo, timeout) k_queue_get((struct k_queue *)lifo, timeout)
#define k_lifo_num_get(lifo) k_queue_count((struct k_queue *)lifo)
struct kfifo {
struct k_queue _queue;
};
#define k_fifo_init(fifo) k_queue_init((struct k_queue *)fifo)
#define k_fifo_cancel_wait(fifo) k_queue_cancel_wait((struct k_queue *)fifo)
#define k_fifo_put(fifo, data) k_queue_append((struct k_queue *)fifo, data)
#define k_fifo_put_list(fifo, head, tail) \
k_queue_append_list((struct k_queue *)fifo, head, tail)
#define k_fifo_get(fifo, timeout) k_queue_get((struct k_queue *)fifo, timeout)
#define k_fifo_num_get(fifo) k_queue_count((struct k_queue *)fifo)
/* sem define*/
struct k_sem {
_sem_t sem;
sys_dlist_t poll_events;
};
/**
* @brief Initialize a semaphore.
*
* This routine initializes a semaphore object, prior to its first use.
*
* @param sem Address of the semaphore.
* @param initial_count Initial semaphore count.
* @param limit Maximum permitted semaphore count.
*
* @return 0 Creat a semaphore succcess
*/
int k_sem_init(struct k_sem *sem, unsigned int initial_count,
unsigned int limit);
/**
* @brief Take a semaphore.
*
* This routine takes @a sem.
*
* @note Can be called by ISRs, but @a timeout must be set to K_NO_WAIT.
*
* @param sem Address of the semaphore.
* @param timeout Waiting period to take the semaphore (in milliseconds),
* or one of the special values K_NO_WAIT and K_FOREVER.
*
* @note When porting code from the nanokernel legacy API to the new API, be
* careful with the return value of this function. The return value is the
* reverse of the one of nano_sem_take family of APIs: 0 means success, and
* non-zero means failure, while the nano_sem_take family returns 1 for success
* and 0 for failure.
*
* @retval 0 Semaphore taken.
* @retval -EBUSY Returned without waiting.
* @retval -EAGAIN Waiting period timed out.
*/
int k_sem_take(struct k_sem *sem, uint32_t timeout);
/**
* @brief Give a semaphore.
*
* This routine gives @a sem, unless the semaphore is already at its maximum
* permitted count.
*
* @note Can be called by ISRs.
*
* @param sem Address of the semaphore.
*
* @return 0 Give semaphore success
*/
int k_sem_give(struct k_sem *sem);
/**
* @brief Delete a semaphore.
*
* This routine delete @a sem,
*
* @note Can be called by ISRs.
*
* @param sem Address of the semaphore.
*
* @return 0 delete semaphore success
*/
int k_sem_delete(struct k_sem *sem);
/**
* @brief Get a semaphore's count.
*
* This routine returns the current count of @a sem.
*
* @param sem Address of the semaphore.
*
* @return Current semaphore count.
*/
unsigned int k_sem_count_get(struct k_sem *sem);
/* mutex define*/
struct k_mutex {
_mutex_t mutex;
sys_dlist_t poll_events;
};
typedef void (*k_timer_handler_t)(void *timer, void *args);
typedef struct k_timer {
ktimer_t timer;
k_timer_handler_t handler;
void *args;
uint32_t timeout;
uint32_t start_ms;
} k_timer_t;
/**
* @brief Initialize a timer.
*
* This routine initializes a timer, prior to its first use.
*
* @param timer Address of timer.
* @param handle Function to invoke each time the timer expires.
* @param args Arguments sent to handle.
*
* @return N/A
*/
void k_timer_init(k_timer_t *timer, k_timer_handler_t handle, void *args);
/**
* @brief Start a timer.
*
* @param timer Address of timer.
* @param timeout time before timeout happen(in milliseconds).
*
* @return N/A
*/
void k_timer_start(k_timer_t *timer, uint32_t timeout);
/**
* @brief Stop a timer.
*
* @param timer Address of timer.
*
* @return N/A
*/
void k_timer_stop(k_timer_t *timer);
/**
* @brief Get time now.
*
* @return time(in milliseconds)
*/
int64_t k_uptime_get(void);
/**
* @brief Get time now.
*
* @return time(in milliseconds)
*/
uint32_t k_uptime_get_32(void);
/**
* @brief Judge if a timer started.
*
* @param timer Address of timer.
*
* @return N/A
*/
bool k_timer_is_started(k_timer_t *timer);
void k_sleep(int32_t duration);
void k_mutex_init(struct k_mutex *mutex);
int k_mutex_lock(struct k_mutex *mutex, bt_s32_t timeout);
void k_mutex_unlock(struct k_mutex *mutex);
const char *log_strdup(const char *str);
#define __DEPRECATED_MACRO
#endif /* KPORT_H */
| YifuLiu/AliOS-Things | components/ble_host/include/ble_os_port.h | C | apache-2.0 | 14,581 |
/*
* Copyright (c) 2017 Linaro Limited
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BLE_TYPES_H__
#define __BLE_TYPES_H__
#include <stdint.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef bool
#define bool unsigned char
#endif
typedef signed char s8_t;
typedef signed short s16_t;
typedef signed int bt_s32_t;
typedef signed long long s64_t;
typedef unsigned char u8_t;
typedef unsigned short u16_t;
typedef unsigned int bt_u32_t;
typedef unsigned long long u64_t;
typedef bt_s32_t k_timeout_t;
#define __deprecated
#ifdef __packed
#undef __packed
#define __packed __attribute__((packed))
#else
#define __packed __attribute__((packed))
#endif
#ifdef __aligned
#undef __aligned
#define __aligned(x) __attribute__((__aligned__(x)))
#else
#define __aligned(x) __attribute__((__aligned__(x)))
#endif
#ifdef __cplusplus
}
#endif
#endif /* __Z_TYPES_H__ */
| YifuLiu/AliOS-Things | components/ble_host/include/ble_types/types.h | C | apache-2.0 | 959 |
/*
* Copyright (C) 2016 YunOS Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _HCI_API_
#define _HCI_API_
#include <stdint.h>
struct hci_debug_counter_t {
uint32_t acl_in_count;
uint32_t acl_out_count;
uint32_t hci_in_is_null_count;
uint32_t cmd_out_count;
uint32_t event_in_count;
uint32_t event_discard_count;
uint32_t event_in_is_null_count;
uint32_t att_in_count;
uint32_t att_out_count;
uint32_t hci_in_err_count;
};
extern struct hci_debug_counter_t g_hci_debug_counter;
int hci_api_init();
int hci_api_le_scan_enable(uint8_t enable, uint8_t filter_dup);
int hci_api_le_scan_param_set(uint8_t scan_type, uint16_t interval, uint16_t window, uint8_t addr_type, uint8_t filter_policy);
int hci_api_le_get_max_data_len(uint16_t *tx_octets, uint16_t *tx_time);
int hci_api_le_get_default_data_len(uint16_t *tx_octets, uint16_t *tx_time);
int hci_api_le_set_default_data_len(uint16_t tx_octets, uint16_t tx_time);
int hci_api_le_set_data_len(int16_t conn_handle, uint16_t tx_octets, uint16_t tx_time);
int hci_api_le_adv_enable(uint8_t enable);
int hci_api_le_set_random_addr(const uint8_t addr[6]);
int hci_api_le_create_conn(uint16_t scan_interval,
uint16_t scan_window,
uint8_t filter_policy,
uint8_t peer_addr_type,
const uint8_t peer_addr[6],
uint8_t own_addr_type,
uint16_t conn_interval_min,
uint16_t conn_interval_max,
uint16_t conn_latency,
uint16_t supervision_timeout,
uint16_t min_ce_len,
uint16_t max_ce_len);
int hci_api_set_host_buffer_size(uint16_t acl_mtu, uint8_t sco_mtu,
uint16_t acl_pkts, uint16_t sco_pkts);
int hci_api_set_host_flow_enable(uint8_t enable);
int hci_api_le_set_bdaddr(uint8_t bdaddr[6]);
int hci_api_reset();
int hci_api_read_local_feature(uint8_t feature[8]);
int hci_api_read_local_version_info(uint8_t *hci_version,
uint8_t *lmp_version,
uint16_t *hci_revision,
uint16_t *lmp_subversion,
uint16_t *manufacturer);
int hci_api_read_bdaddr(uint8_t bdaddr[6]);
int hci_api_read_local_support_command(uint8_t supported_commands[64]);
int hci_api_le_set_event_mask(uint64_t mask);
int hci_api_le_read_local_feature(uint8_t feature[8]);
int hci_api_le_read_buffer_size_complete(uint16_t *le_max_len, uint8_t *le_max_num);
int hci_api_le_read_support_states(uint64_t *states);
int hci_api_le_read_rl_size(uint8_t *rl_size);
int hci_api_set_event_mask(uint64_t mask);
int hci_api_vs_init();
int hci_api_le_set_ad_data(uint8_t len, uint8_t data[31]);
int hci_api_le_set_sd_data(uint8_t len, uint8_t data[31]);
int hci_api_le_adv_param(uint16_t min_interval,
uint16_t max_interval,
uint8_t type,
uint8_t own_addr_type,
uint8_t direct_addr_type,
uint8_t direct_addr[6],
uint8_t channel_map,
uint8_t filter_policy);
int hci_api_le_create_conn_cancel();
int hci_api_le_read_remote_features(uint16_t conn_handle);
int hci_api_le_read_remote_version(uint16_t conn_handle);
int hci_api_le_disconnect(uint16_t conn_handle, uint8_t reason);
struct handle_count {
uint16_t handle;
uint16_t count;
};
int hci_api_host_num_complete_packets(uint8_t num_handles, struct handle_count *phc);
int hci_api_le_conn_updata(uint16_t conn_handle,
uint16_t conn_interval_min,
uint16_t conn_interval_max,
uint16_t conn_latency,
uint16_t supervision_timeout,
uint16_t min_ce_len,
uint16_t max_ce_len);
int hci_api_le_start_encrypt(uint16_t conn_handle,
uint8_t rand[8],
uint8_t ediv[2],
uint8_t ltk[16]);
int hci_api_le_enctypt_ltk_req_reply(uint16_t conn_handle, uint8_t ltk[16]);
int hci_api_le_enctypt_ltk_req_neg_reply(uint16_t conn_handle);
int hci_api_le_rand(uint8_t random_data[8]);
int hci_api_le_enc(uint8_t key[16], uint8_t plaintext[16], uint8_t ciphertext[16]);
int hci_api_le_set_phy(uint16_t handle,
uint8_t all_phys,
uint8_t tx_phys,
uint8_t rx_phys,
uint16_t phy_opts);
int hci_api_le_conn_param_req_reply(uint16_t handle,
uint16_t interval_min,
uint16_t interval_max,
uint16_t latency,
uint16_t timeout,
uint16_t min_ce_len,
uint16_t max_ce_len);
int hci_api_le_conn_param_neg_reply(uint16_t handle, uint8_t reason);
int hci_api_le_add_dev_to_rl(uint8_t type,
uint8_t peer_id_addr[6],
uint8_t peer_irk[16],
uint8_t local_irk[16]);
int hci_api_le_remove_dev_from_rl(uint8_t type, const uint8_t peer_id_addr[6]);
int hci_api_le_clear_rl();
int hci_api_le_set_addr_res_enable(uint8_t enable);
int hci_api_le_set_privacy_mode(uint8_t type, uint8_t id_addr[6], uint8_t mode);
int hci_api_le_gen_p256_pubkey();
int hci_api_le_gen_dhkey(uint8_t remote_pk[64]);
int hci_api_read_buffer_size(uint16_t *acl_max_len,
uint8_t *sco_max_len,
uint16_t *acl_max_num,
uint16_t *sco_max_num);
int hci_api_le_write_host_supp(uint8_t le, uint8_t simul);
int hci_api_num_complete_packets(uint8_t num_handles,
uint16_t *handles,
uint16_t *counts);
int hci_api_white_list_size(uint8_t *size);
int hci_api_white_list_add(uint8_t peer_addr_type, uint8_t peer_addr[6]);
int hci_api_white_list_remove(uint8_t peer_addr_type, uint8_t peer_addr[6]);
int hci_api_white_list_clear();
int hci_api_le_event_dhkey_complete(uint8_t status, uint8_t dhkey[32]);
int hci_api_le_event_pkey_complete(uint8_t status, uint8_t key[64]);
int hci_api_le_ext_adv_param_set (uint8_t handle,
uint16_t props,
uint32_t prim_min_interval,
uint32_t prim_max_interval,
uint8_t prim_channel_map,
uint8_t own_addr_type,
uint8_t peer_addr_type,
uint8_t peer_addr[6],
uint8_t filter_policy,
int8_t tx_power,
uint8_t prim_adv_phy,
uint8_t sec_adv_max_skip,
uint8_t sec_adv_phy,
uint8_t sid,
uint8_t scan_req_notify_enable,
int8_t *ret_txpower);
struct ext_adv_set_t {
uint8_t adv_handle;
uint16_t duration;
uint8_t max_ext_adv_evts;
};
int hci_api_le_ext_adv_enable( uint8_t enable, uint16_t set_num, struct ext_adv_set_t adv_sets[]);
int hci_api_le_set_adv_random_addr(uint8_t handle, const uint8_t addr[6]);
int hci_api_le_ext_scan_enable(uint8_t enable,uint8_t filter_dup,uint16_t duration, uint16_t period);
struct ext_scan_param_t {
uint8_t type;
uint16_t interval;
uint16_t window;
};
int hci_api_le_ext_scan_param_set(uint8_t own_addr_type,uint8_t filter_policy,uint8_t scan_phys, struct ext_scan_param_t params[]);
struct ext_conn_phy_params_t {
uint16_t scan_interval;
uint16_t scan_window;
uint16_t conn_interval_min;
uint16_t conn_interval_max;
uint16_t conn_latency;
uint16_t supervision_timeout;
uint16_t min_ce_len;
uint16_t max_ce_len;
};
int hci_api_le_create_conn_ext(uint8_t filter_policy,
uint8_t own_addr_type,
uint8_t peer_addr_type,
uint8_t peer_addr[6],
uint8_t init_phys,
struct ext_conn_phy_params_t params[]);
int hci_api_le_read_phy(uint16_t conn_handle, uint8_t *tx_phy , uint8_t *rx_phy);
int hci_api_le_rpa_timeout_set(uint16_t timeout);
int hci_api_le_set_ext_ad_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[251]);
int hci_api_le_set_ext_sd_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[251]);
int hci_api_le_remove_adv_set(uint8_t handle);
int hci_api_le_set_host_chan_classif(uint8_t ch_map[5]);
#endif
| YifuLiu/AliOS-Things | components/ble_host/include/hci_api.h | C | apache-2.0 | 10,017 |
/*
* Copyright (c) 2013-2015 Wind River Systems, Inc.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file
* @brief Doubly-linked list implementation
*
* Doubly-linked list implementation using inline macros/functions.
* This API is not thread safe, and thus if a list is used across threads,
* calls to functions must be protected with synchronization primitives.
*
* The lists are expected to be initialized such that both the head and tail
* pointers point to the list itself. Initializing the lists in such a fashion
* simplifies the adding and removing of nodes to/from the list.
*/
#ifndef _misc_dlist__h_
#define _misc_dlist__h_
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
struct _dnode {
union {
struct _dnode *head; /* ptr to head of list (sys_dlist_t) */
struct _dnode *next; /* ptr to next node (sys_dnode_t) */
};
union {
struct _dnode *tail; /* ptr to tail of list (sys_dlist_t) */
struct _dnode *prev; /* ptr to previous node (sys_dnode_t) */
};
};
typedef struct _dnode sys_dlist_t;
typedef struct _dnode sys_dnode_t;
/**
* @brief Provide the primitive to iterate on a list
* Note: the loop is unsafe and thus __dn should not be removed
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_DLIST_FOR_EACH_NODE(l, n) {
* <user code>
* }
*
* This and other SYS_DLIST_*() macros are not thread safe.
*
* @param __dl A pointer on a sys_dlist_t to iterate on
* @param __dn A sys_dnode_t pointer to peek each node of the list
*/
#define SYS_DLIST_FOR_EACH_NODE(__dl, __dn) \
for (__dn = sys_dlist_peek_head(__dl); __dn; \
__dn = sys_dlist_peek_next(__dl, __dn))
/**
* @brief Provide the primitive to iterate on a list, from a node in the list
* Note: the loop is unsafe and thus __dn should not be removed
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_DLIST_ITERATE_FROM_NODE(l, n) {
* <user code>
* }
*
* Like SYS_DLIST_FOR_EACH_NODE(), but __dn already contains a node in the list
* where to start searching for the next entry from. If NULL, it starts from
* the head.
*
* This and other SYS_DLIST_*() macros are not thread safe.
*
* @param __dl A pointer on a sys_dlist_t to iterate on
* @param __dn A sys_dnode_t pointer to peek each node of the list;
* it contains the starting node, or NULL to start from the head
*/
#define SYS_DLIST_ITERATE_FROM_NODE(__dl, __dn) \
for (__dn = __dn ? sys_dlist_peek_next_no_check(__dl, __dn) \
: sys_dlist_peek_head(__dl); \
__dn; \
__dn = sys_dlist_peek_next(__dl, __dn))
/**
* @brief Provide the primitive to safely iterate on a list
* Note: __dn can be removed, it will not break the loop.
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_DLIST_FOR_EACH_NODE_SAFE(l, n, s) {
* <user code>
* }
*
* This and other SYS_DLIST_*() macros are not thread safe.
*
* @param __dl A pointer on a sys_dlist_t to iterate on
* @param __dn A sys_dnode_t pointer to peek each node of the list
* @param __dns A sys_dnode_t pointer for the loop to run safely
*/
#define SYS_DLIST_FOR_EACH_NODE_SAFE(__dl, __dn, __dns) \
for (__dn = sys_dlist_peek_head(__dl), \
__dns = sys_dlist_peek_next(__dl, __dn); \
__dn; __dn = __dns, \
__dns = sys_dlist_peek_next(__dl, __dn))
/*
* @brief Provide the primitive to resolve the container of a list node
* Note: it is safe to use with NULL pointer nodes
*
* @param __dn A pointer on a sys_dnode_t to get its container
* @param __cn Container struct type pointer
* @param __n The field name of sys_dnode_t within the container struct
*/
#define SYS_DLIST_CONTAINER(__dn, __cn, __n) \
(__dn ? CONTAINER_OF(__dn, __typeof__(*__cn), __n) : NULL)
/*
* @brief Provide the primitive to peek container of the list head
*
* @param __dl A pointer on a sys_dlist_t to peek
* @param __cn Container struct type pointer
* @param __n The field name of sys_dnode_t within the container struct
*/
#define SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n) \
SYS_DLIST_CONTAINER(sys_dlist_peek_head(__dl), __cn, __n)
/*
* @brief Provide the primitive to peek the next container
*
* @param __dl A pointer on a sys_dlist_t to peek
* @param __cn Container struct type pointer
* @param __n The field name of sys_dnode_t within the container struct
*/
#define SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n) \
((__cn) ? SYS_DLIST_CONTAINER(sys_dlist_peek_next(__dl, &(__cn->__n)), \
__cn, __n) : NULL)
/**
* @brief Provide the primitive to iterate on a list under a container
* Note: the loop is unsafe and thus __cn should not be detached
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_DLIST_FOR_EACH_CONTAINER(l, c, n) {
* <user code>
* }
*
* @param __dl A pointer on a sys_dlist_t to iterate on
* @param __cn A pointer to peek each entry of the list
* @param __n The field name of sys_dnode_t within the container struct
*/
#define SYS_DLIST_FOR_EACH_CONTAINER(__dl, __cn, __n) \
for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n); __cn; \
__cn = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n))
/**
* @brief Provide the primitive to safely iterate on a list under a container
* Note: __cn can be detached, it will not break the loop.
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_DLIST_FOR_EACH_CONTAINER_SAFE(l, c, cn, n) {
* <user code>
* }
*
* @param __dl A pointer on a sys_dlist_t to iterate on
* @param __cn A pointer to peek each entry of the list
* @param __cns A pointer for the loop to run safely
* @param __n The field name of sys_dnode_t within the container struct
*/
#define SYS_DLIST_FOR_EACH_CONTAINER_SAFE(__dl, __cn, __cns, __n) \
for (__cn = SYS_DLIST_PEEK_HEAD_CONTAINER(__dl, __cn, __n), \
__cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n); __cn; \
__cn = __cns, \
__cns = SYS_DLIST_PEEK_NEXT_CONTAINER(__dl, __cn, __n))
/**
* @brief initialize list
*
* @param list the doubly-linked list
*
* @return N/A
*/
static inline void sys_dlist_init(sys_dlist_t *list)
{
list->head = (sys_dnode_t *)list;
list->tail = (sys_dnode_t *)list;
}
#define SYS_DLIST_STATIC_INIT(ptr_to_list) {{(ptr_to_list)}, {(ptr_to_list)}}
/**
* @brief check if a node is the list's head
*
* @param list the doubly-linked list to operate on
* @param node the node to check
*
* @return 1 if node is the head, 0 otherwise
*/
static inline int sys_dlist_is_head(sys_dlist_t *list, sys_dnode_t *node)
{
return list->head == node;
}
/**
* @brief check if a node is the list's tail
*
* @param list the doubly-linked list to operate on
* @param node the node to check
*
* @return 1 if node is the tail, 0 otherwise
*/
static inline int sys_dlist_is_tail(sys_dlist_t *list, sys_dnode_t *node)
{
return list->tail == node;
}
/**
* @brief check if the list is empty
*
* @param list the doubly-linked list to operate on
*
* @return 1 if empty, 0 otherwise
*/
static inline int sys_dlist_is_empty(sys_dlist_t *list)
{
return list->head == list;
}
/**
* @brief check if more than one node present
*
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
*
* @return 1 if multiple nodes, 0 otherwise
*/
static inline int sys_dlist_has_multiple_nodes(sys_dlist_t *list)
{
return list->head != list->tail;
}
/**
* @brief get a reference to the head item in the list
*
* @param list the doubly-linked list to operate on
*
* @return a pointer to the head element, NULL if list is empty
*/
static inline sys_dnode_t *sys_dlist_peek_head(sys_dlist_t *list)
{
return sys_dlist_is_empty(list) ? NULL : list->head;
}
/**
* @brief get a reference to the head item in the list
*
* The list must be known to be non-empty.
*
* @param list the doubly-linked list to operate on
*
* @return a pointer to the head element
*/
static inline sys_dnode_t *sys_dlist_peek_head_not_empty(sys_dlist_t *list)
{
return list->head;
}
/**
* @brief get a reference to the next item in the list, node is not NULL
*
* Faster than sys_dlist_peek_next() if node is known not to be NULL.
*
* @param list the doubly-linked list to operate on
* @param node the node from which to get the next element in the list
*
* @return a pointer to the next element from a node, NULL if node is the tail
*/
static inline sys_dnode_t *sys_dlist_peek_next_no_check(sys_dlist_t *list,
sys_dnode_t *node)
{
return (node == list->tail) ? NULL : node->next;
}
/**
* @brief get a reference to the next item in the list
*
* @param list the doubly-linked list to operate on
* @param node the node from which to get the next element in the list
*
* @return a pointer to the next element from a node, NULL if node is the tail
* or NULL (when node comes from reading the head of an empty list).
*/
static inline sys_dnode_t *sys_dlist_peek_next(sys_dlist_t *list,
sys_dnode_t *node)
{
return node ? sys_dlist_peek_next_no_check(list, node) : NULL;
}
/**
* @brief get a reference to the tail item in the list
*
* @param list the doubly-linked list to operate on
*
* @return a pointer to the tail element, NULL if list is empty
*/
static inline sys_dnode_t *sys_dlist_peek_tail(sys_dlist_t *list)
{
return sys_dlist_is_empty(list) ? NULL : list->tail;
}
/**
* @brief add node to tail of list
*
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
* @param node the element to append
*
* @return N/A
*/
static inline void sys_dlist_append(sys_dlist_t *list, sys_dnode_t *node)
{
node->next = list;
node->prev = list->tail;
list->tail->next = node;
list->tail = node;
}
/**
* @brief add node to head of list
*
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
* @param node the element to append
*
* @return N/A
*/
static inline void sys_dlist_prepend(sys_dlist_t *list, sys_dnode_t *node)
{
node->next = list->head;
node->prev = list;
list->head->prev = node;
list->head = node;
}
/**
* @brief insert node after a node
*
* Insert a node after a specified node in a list.
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
* @param insert_point the insert point in the list: if NULL, insert at head
* @param node the element to append
*
* @return N/A
*/
static inline void sys_dlist_insert_after(sys_dlist_t *list,
sys_dnode_t *insert_point, sys_dnode_t *node)
{
if (!insert_point) {
sys_dlist_prepend(list, node);
} else {
node->next = insert_point->next;
node->prev = insert_point;
insert_point->next->prev = node;
insert_point->next = node;
}
}
/**
* @brief insert node before a node
*
* Insert a node before a specified node in a list.
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
* @param insert_point the insert point in the list: if NULL, insert at tail
* @param node the element to insert
*
* @return N/A
*/
static inline void sys_dlist_insert_before(sys_dlist_t *list,
sys_dnode_t *insert_point, sys_dnode_t *node)
{
if (!insert_point) {
sys_dlist_append(list, node);
} else {
node->prev = insert_point->prev;
node->next = insert_point;
insert_point->prev->next = node;
insert_point->prev = node;
}
}
/**
* @brief insert node at position
*
* Insert a node in a location depending on a external condition. The cond()
* function checks if the node is to be inserted _before_ the current node
* against which it is checked.
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
* @param node the element to insert
* @param cond a function that determines if the current node is the correct
* insert point
* @param data parameter to cond()
*
* @return N/A
*/
static inline void sys_dlist_insert_at(sys_dlist_t *list, sys_dnode_t *node,
int (*cond)(sys_dnode_t *, void *), void *data)
{
if (sys_dlist_is_empty(list)) {
sys_dlist_append(list, node);
} else {
sys_dnode_t *pos = sys_dlist_peek_head(list);
while (pos && !cond(pos, data)) {
pos = sys_dlist_peek_next(list, pos);
}
sys_dlist_insert_before(list, pos, node);
}
}
/**
* @brief remove a specific node from a list
*
* The list is implicit from the node. The node must be part of a list.
* This and other sys_dlist_*() functions are not thread safe.
*
* @param node the node to remove
*
* @return N/A
*/
static inline void sys_dlist_remove(sys_dnode_t *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
}
/**
* @brief get the first node in a list
*
* This and other sys_dlist_*() functions are not thread safe.
*
* @param list the doubly-linked list to operate on
*
* @return the first node in the list, NULL if list is empty
*/
static inline sys_dnode_t *sys_dlist_get(sys_dlist_t *list)
{
sys_dnode_t *node;
if (sys_dlist_is_empty(list)) {
return NULL;
}
node = list->head;
sys_dlist_remove(node);
return node;
}
/**
* @brief get node number in dlist
*
* @param list the doubly-linked list to operate on
*
* @return number
*/
static inline int sys_dlist_node_number(sys_dlist_t *list)
{
int number = 0;
sys_dnode_t *node;
if (sys_dlist_is_empty(list))
return number;
node = list->head;
while (node) {
number++;
if (node == list->tail)
break;
node = node->next;
}
return number;
}
#ifdef __cplusplus
}
#endif
#endif /* _misc_dlist__h_ */
| YifuLiu/AliOS-Things | components/ble_host/include/misc/dlist.h | C | apache-2.0 | 13,859 |
/*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file
*
* @brief Header where single linked list utility code is found
*/
#ifndef __SLIST_H__
#define __SLIST_H__
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
struct _snode {
struct _snode *next;
};
typedef struct _snode sys_snode_t;
struct _slist {
sys_snode_t *head;
sys_snode_t *tail;
};
typedef struct _slist sys_slist_t;
/**
* @brief Provide the primitive to iterate on a list
* Note: the loop is unsafe and thus __sn should not be removed
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_SLIST_FOR_EACH_NODE(l, n) {
* <user code>
* }
*
* @param __sl A pointer on a sys_slist_t to iterate on
* @param __sn A sys_snode_t pointer to peek each node of the list
*/
#define SYS_SLIST_FOR_EACH_NODE(__sl, __sn) \
for (__sn = sys_slist_peek_head(__sl); __sn; \
__sn = sys_slist_peek_next(__sn))
/**
* @brief Provide the primitive to iterate on a list, from a node in the list
* Note: the loop is unsafe and thus __sn should not be removed
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_SLIST_ITERATE_FROM_NODE(l, n) {
* <user code>
* }
*
* Like SYS_SLIST_FOR_EACH_NODE(), but __dn already contains a node in the list
* where to start searching for the next entry from. If NULL, it starts from
* the head.
*
* @param __sl A pointer on a sys_slist_t to iterate on
* @param __sn A sys_snode_t pointer to peek each node of the list
* it contains the starting node, or NULL to start from the head
*/
#define SYS_SLIST_ITERATE_FROM_NODE(__sl, __sn) \
for (__sn = __sn ? sys_slist_peek_next_no_check(__sn) \
: sys_slist_peek_head(__sl); \
__sn; \
__sn = sys_slist_peek_next(__sn))
/**
* @brief Provide the primitive to safely iterate on a list
* Note: __sn can be removed, it will not break the loop.
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_SLIST_FOR_EACH_NODE_SAFE(l, n, s) {
* <user code>
* }
*
* @param __sl A pointer on a sys_slist_t to iterate on
* @param __sn A sys_snode_t pointer to peek each node of the list
* @param __sns A sys_snode_t pointer for the loop to run safely
*/
#define SYS_SLIST_FOR_EACH_NODE_SAFE(__sl, __sn, __sns) \
for (__sn = sys_slist_peek_head(__sl), \
__sns = sys_slist_peek_next(__sn); \
__sn; __sn = __sns, \
__sns = sys_slist_peek_next(__sn))
/*
* @brief Provide the primitive to resolve the container of a list node
* Note: it is safe to use with NULL pointer nodes
*
* @param __ln A pointer on a sys_node_t to get its container
* @param __cn Container struct type pointer
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_CONTAINER(__ln, __cn, __n) \
((__ln) ? CONTAINER_OF((__ln), __typeof__(*(__cn)), __n) : NULL)
/*
* @brief Provide the primitive to peek container of the list head
*
* @param __sl A pointer on a sys_slist_t to peek
* @param __cn Container struct type pointer
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n) \
SYS_SLIST_CONTAINER(sys_slist_peek_head(__sl), __cn, __n)
/*
* @brief Provide the primitive to peek container of the list tail
*
* @param __sl A pointer on a sys_slist_t to peek
* @param __cn Container struct type pointer
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_PEEK_TAIL_CONTAINER(__sl, __cn, __n) \
SYS_SLIST_CONTAINER(sys_slist_peek_tail(__sl), __cn, __n)
/*
* @brief Provide the primitive to peek the next container
*
* @param __cn Container struct type pointer
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n) \
((__cn) ? SYS_SLIST_CONTAINER(sys_slist_peek_next(&((__cn)->__n)), \
__cn, __n) : NULL)
/**
* @brief Provide the primitive to iterate on a list under a container
* Note: the loop is unsafe and thus __cn should not be detached
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_SLIST_FOR_EACH_CONTAINER(l, c, n) {
* <user code>
* }
*
* @param __sl A pointer on a sys_slist_t to iterate on
* @param __cn A pointer to peek each entry of the list
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_FOR_EACH_CONTAINER(__sl, __cn, __n) \
for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n); __cn; \
__cn = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n))
/**
* @brief Provide the primitive to safely iterate on a list under a container
* Note: __cn can be detached, it will not break the loop.
*
* User _MUST_ add the loop statement curly braces enclosing its own code:
*
* SYS_SLIST_FOR_EACH_NODE_SAFE(l, c, cn, n) {
* <user code>
* }
*
* @param __sl A pointer on a sys_slist_t to iterate on
* @param __cn A pointer to peek each entry of the list
* @param __cns A pointer for the loop to run safely
* @param __n The field name of sys_node_t within the container struct
*/
#define SYS_SLIST_FOR_EACH_CONTAINER_SAFE(__sl, __cn, __cns, __n) \
for (__cn = SYS_SLIST_PEEK_HEAD_CONTAINER(__sl, __cn, __n), \
__cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n); __cn; \
__cn = __cns, __cns = SYS_SLIST_PEEK_NEXT_CONTAINER(__cn, __n))
/**
* @brief Initialize a list
*
* @param list A pointer on the list to initialize
*/
static inline void sys_slist_init(sys_slist_t *list)
{
list->head = NULL;
list->tail = NULL;
}
#define SYS_SLIST_STATIC_INIT(ptr_to_list) {NULL, NULL}
/**
* @brief Test if the given list is empty
*
* @param list A pointer on the list to test
*
* @return a boolean, true if it's empty, false otherwise
*/
static inline bool sys_slist_is_empty(sys_slist_t *list)
{
return (!list->head);
}
/**
* @brief Peek the first node from the list
*
* @param list A point on the list to peek the first node from
*
* @return A pointer on the first node of the list (or NULL if none)
*/
static inline sys_snode_t *sys_slist_peek_head(sys_slist_t *list)
{
return list->head;
}
/**
* @brief Peek the last node from the list
*
* @param list A point on the list to peek the last node from
*
* @return A pointer on the last node of the list (or NULL if none)
*/
static inline sys_snode_t *sys_slist_peek_tail(sys_slist_t *list)
{
return list->tail;
}
/**
* @brief Peek the next node from current node, node is not NULL
*
* Faster then sys_slist_peek_next() if node is known not to be NULL.
*
* @param node A pointer on the node where to peek the next node
*
* @return a pointer on the next node (or NULL if none)
*/
static inline sys_snode_t *sys_slist_peek_next_no_check(sys_snode_t *node)
{
return node->next;
}
/**
* @brief Peek the next node from current node
*
* @param node A pointer on the node where to peek the next node
*
* @return a pointer on the next node (or NULL if none)
*/
static inline sys_snode_t *sys_slist_peek_next(sys_snode_t *node)
{
return node ? sys_slist_peek_next_no_check(node) : NULL;
}
/**
* @brief Prepend a node to the given list
*
* @param list A pointer on the list to affect
* @param node A pointer on the node to prepend
*/
static inline void sys_slist_prepend(sys_slist_t *list,
sys_snode_t *node)
{
node->next = list->head;
list->head = node;
if (!list->tail) {
list->tail = list->head;
}
}
/**
* @brief Append a node to the given list
*
* @param list A pointer on the list to affect
* @param node A pointer on the node to append
*/
static inline void sys_slist_append(sys_slist_t *list,
sys_snode_t *node)
{
node->next = NULL;
if (!list->tail) {
list->tail = node;
list->head = node;
} else {
list->tail->next = node;
list->tail = node;
}
}
/**
* @brief Append a list to the given list
*
* Append a singly-linked, NULL-terminated list consisting of nodes containing
* the pointer to the next node as the first element of a node, to @a list.
*
* @param list A pointer on the list to affect
* @param head A pointer to the first element of the list to append
* @param tail A pointer to the last element of the list to append
*/
static inline void sys_slist_append_list(sys_slist_t *list,
void *head, void *tail)
{
if (!list->tail) {
list->head = (sys_snode_t *)head;
list->tail = (sys_snode_t *)tail;
} else {
list->tail->next = (sys_snode_t *)head;
list->tail = (sys_snode_t *)tail;
}
}
/**
* @brief merge two slists, appending the second one to the first
*
* When the operation is completed, the appending list is empty.
*
* @param list A pointer on the list to affect
* @param list_to_append A pointer to the list to append.
*/
static inline void sys_slist_merge_slist(sys_slist_t *list,
sys_slist_t *list_to_append)
{
sys_slist_append_list(list, list_to_append->head,
list_to_append->tail);
sys_slist_init(list_to_append);
}
/**
* @brief Insert a node to the given list
*
* @param list A pointer on the list to affect
* @param prev A pointer on the previous node
* @param node A pointer on the node to insert
*/
static inline void sys_slist_insert(sys_slist_t *list,
sys_snode_t *prev,
sys_snode_t *node)
{
if (!prev) {
sys_slist_prepend(list, node);
} else if (!prev->next) {
sys_slist_append(list, node);
} else {
node->next = prev->next;
prev->next = node;
}
}
/**
* @brief Fetch and remove the first node of the given list
*
* List must be known to be non-empty.
*
* @param list A pointer on the list to affect
*
* @return A pointer to the first node of the list
*/
static inline sys_snode_t *sys_slist_get_not_empty(sys_slist_t *list)
{
sys_snode_t *node = list->head;
list->head = node->next;
if (list->tail == node) {
list->tail = list->head;
}
return node;
}
/**
* @brief Fetch and remove the first node of the given list
*
* @param list A pointer on the list to affect
*
* @return A pointer to the first node of the list (or NULL if empty)
*/
static inline sys_snode_t *sys_slist_get(sys_slist_t *list)
{
return sys_slist_is_empty(list) ? NULL : sys_slist_get_not_empty(list);
}
/**
* @brief Remove a node
*
* @param list A pointer on the list to affect
* @param prev_node A pointer on the previous node
* (can be NULL, which means the node is the list's head)
* @param node A pointer on the node to remove
*/
static inline void sys_slist_remove(sys_slist_t *list,
sys_snode_t *prev_node,
sys_snode_t *node)
{
if (!prev_node) {
list->head = node->next;
/* Was node also the tail? */
if (list->tail == node) {
list->tail = list->head;
}
} else {
prev_node->next = node->next;
/* Was node the tail? */
if (list->tail == node) {
list->tail = prev_node;
}
}
node->next = NULL;
}
/**
* @brief Find and remove a node from a list
*
* @param list A pointer on the list to affect
* @param node A pointer on the node to remove from the list
*
* @return true if node was removed
*/
static inline bool sys_slist_find_and_remove(sys_slist_t *list,
sys_snode_t *node)
{
sys_snode_t *prev = NULL;
sys_snode_t *test;
SYS_SLIST_FOR_EACH_NODE(list, test) {
if (test == node) {
sys_slist_remove(list, prev, node);
return true;
}
prev = test;
}
return false;
}
#ifdef __cplusplus
}
#endif
#endif /* __SLIST_H__ */
| YifuLiu/AliOS-Things | components/ble_host/include/misc/slist.h | C | apache-2.0 | 11,598 |
/** @file
* @brief Buffer management.
*/
/*
* Copyright (c) 2015 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __NET_BUF_H
#define __NET_BUF_H
#include <ble_types/types.h>
#include <ble_os_port.h>
#include <ble_default_config.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Network buffer library
* @defgroup net_buf Network Buffer Library
* @ingroup networking
* @{
*/
/* Alignment needed for various parts of the buffer definition */
#define __net_buf_align __aligned(sizeof(void *))
/**
* @def NET_BUF_SIMPLE_DEFINE
* @brief Define a net_buf_simple stack variable.
*
* This is a helper macro which is used to define a net_buf_simple object
* on the stack.
*
* @param _name Name of the net_buf_simple object.
* @param _size Maximum data storage for the buffer.
*/
#define NET_BUF_SIMPLE_DEFINE(_name, _size) \
u8_t net_buf_data_##_name[_size]; \
struct net_buf_simple _name = { \
.data = net_buf_data_##_name, \
.len = 0, \
.size = _size, \
.__buf = net_buf_data_##_name, \
}
/**
* @def NET_BUF_SIMPLE_DEFINE_STATIC
* @brief Define a static net_buf_simple variable.
*
* This is a helper macro which is used to define a static net_buf_simple
* object.
*
* @param _name Name of the net_buf_simple object.
* @param _size Maximum data storage for the buffer.
*/
#define NET_BUF_SIMPLE_DEFINE_STATIC(_name, _size) \
static __noinit u8_t net_buf_data_##_name[_size]; \
static struct net_buf_simple _name = { \
.data = net_buf_data_##_name, \
.len = 0, \
.size = _size, \
.__buf = net_buf_data_##_name, \
}
/**
* @brief Simple network buffer representation.
*
* This is a simpler variant of the net_buf object (in fact net_buf uses
* net_buf_simple internally). It doesn't provide any kind of reference
* counting, user data, dynamic allocation, or in general the ability to
* pass through kernel objects such as FIFOs.
*
* The main use of this is for scenarios where the meta-data of the normal
* net_buf isn't needed and causes too much overhead. This could be e.g.
* when the buffer only needs to be allocated on the stack or when the
* access to and lifetime of the buffer is well controlled and constrained.
*/
struct net_buf_simple {
/** Pointer to the start of data in the buffer. */
u8_t *data;
/** Length of the data behind the data pointer. */
u16_t len;
/** Amount of data that this buffer can store. */
u16_t size;
/** Start of the data storage. Not to be accessed directly
* (the data pointer should be used instead).
*/
u8_t *__buf;
};
/**
* @def NET_BUF_SIMPLE
* @brief Define a net_buf_simple stack variable and get a pointer to it.
*
* This is a helper macro which is used to define a net_buf_simple object on
* the stack and the get a pointer to it as follows:
*
* struct net_buf_simple *my_buf = NET_BUF_SIMPLE(10);
*
* After creating the object it needs to be initialized by calling
* net_buf_simple_init().
*
* @param _size Maximum data storage for the buffer.
*
* @return Pointer to stack-allocated net_buf_simple object.
*/
#define NET_BUF_SIMPLE(_size) \
((struct net_buf_simple *)(&(struct { \
struct net_buf_simple buf; \
u8_t data[_size]; \
}) { \
.buf.size = _size, \
}))
/**
* @brief Initialize a net_buf_simple object.
*
* This needs to be called after creating a net_buf_simple object using
* the NET_BUF_SIMPLE macro.
*
* @param buf Buffer to initialize.
* @param reserve_head Headroom to reserve.
*/
static inline void net_buf_simple_init(struct net_buf_simple *buf,
size_t reserve_head)
{
if (!buf->__buf) {
buf->__buf = (u8_t *)buf + sizeof(*buf);
}
buf->data = buf->__buf + reserve_head;
buf->len = 0U;
}
/**
* @brief Initialize a net_buf_simple object with data.
*
* Initialized buffer object with external data.
*
* @param buf Buffer to initialize.
* @param data External data pointer
* @param size Amount of data the pointed data buffer if able to fit.
*/
void net_buf_simple_init_with_data(struct net_buf_simple *buf,
void *data, size_t size);
/**
* @brief Reset buffer
*
* Reset buffer data so it can be reused for other purposes.
*
* @param buf Buffer to reset.
*/
static inline void net_buf_simple_reset(struct net_buf_simple *buf)
{
buf->len = 0U;
buf->data = buf->__buf;
}
/**
* Clone buffer state, using the same data buffer.
*
* Initializes a buffer to point to the same data as an existing buffer.
* Allows operations on the same data without altering the length and
* offset of the original.
*
* @param original Buffer to clone.
* @param clone The new clone.
*/
void net_buf_simple_clone(const struct net_buf_simple *original,
struct net_buf_simple *clone);
/**
* @brief Prepare data to be added at the end of the buffer
*
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param len Number of bytes to increment the length with.
*
* @return The original tail of the buffer.
*/
void *net_buf_simple_add(struct net_buf_simple *buf, size_t len);
/**
* @brief Copy given number of bytes from memory to the end of the buffer
*
* Increments the data length of the buffer to account for more data at the
* end.
*
* @param buf Buffer to update.
* @param mem Location of data to be added.
* @param len Length of data to be added
*
* @return The original tail of the buffer.
*/
void *net_buf_simple_add_mem(struct net_buf_simple *buf, const void *mem,
size_t len);
/**
* @brief Add (8-bit) byte at the end of the buffer
*
* Increments the data length of the buffer to account for more data at the
* end.
*
* @param buf Buffer to update.
* @param val byte value to be added.
*
* @return Pointer to the value added
*/
u8_t *net_buf_simple_add_u8(struct net_buf_simple *buf, u8_t val);
/**
* @brief Add 16-bit value at the end of the buffer
*
* Adds 16-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 16-bit value to be added.
*/
void net_buf_simple_add_le16(struct net_buf_simple *buf, u16_t val);
/**
* @brief Add 16-bit value at the end of the buffer
*
* Adds 16-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 16-bit value to be added.
*/
void net_buf_simple_add_be16(struct net_buf_simple *buf, u16_t val);
/**
* @brief Add 24-bit value at the end of the buffer
*
* Adds 24-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 24-bit value to be added.
*/
void net_buf_simple_add_le24(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Add 24-bit value at the end of the buffer
*
* Adds 24-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 24-bit value to be added.
*/
void net_buf_simple_add_be24(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Add 32-bit value at the end of the buffer
*
* Adds 32-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 32-bit value to be added.
*/
void net_buf_simple_add_le32(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Add 32-bit value at the end of the buffer
*
* Adds 32-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 32-bit value to be added.
*/
void net_buf_simple_add_be32(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Add 48-bit value at the end of the buffer
*
* Adds 48-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 48-bit value to be added.
*/
void net_buf_simple_add_le48(struct net_buf_simple *buf, u64_t val);
/**
* @brief Add 48-bit value at the end of the buffer
*
* Adds 48-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 48-bit value to be added.
*/
void net_buf_simple_add_be48(struct net_buf_simple *buf, u64_t val);
/**
* @brief Add 64-bit value at the end of the buffer
*
* Adds 64-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 64-bit value to be added.
*/
void net_buf_simple_add_le64(struct net_buf_simple *buf, u64_t val);
/**
* @brief Add 64-bit value at the end of the buffer
*
* Adds 64-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 64-bit value to be added.
*/
void net_buf_simple_add_be64(struct net_buf_simple *buf, u64_t val);
/**
* @brief Push data to the beginning of the buffer.
*
* Modifies the data pointer and buffer length to account for more data
* in the beginning of the buffer.
*
* @param buf Buffer to update.
* @param len Number of bytes to add to the beginning.
*
* @return The new beginning of the buffer data.
*/
void *net_buf_simple_push(struct net_buf_simple *buf, size_t len);
/**
* @brief Push 16-bit value to the beginning of the buffer
*
* Adds 16-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 16-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_le16(struct net_buf_simple *buf, u16_t val);
/**
* @brief Push 16-bit value to the beginning of the buffer
*
* Adds 16-bit value in big endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 16-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_be16(struct net_buf_simple *buf, u16_t val);
/**
* @brief Push 8-bit value to the beginning of the buffer
*
* Adds 8-bit value the beginning of the buffer.
*
* @param buf Buffer to update.
* @param val 8-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_u8(struct net_buf_simple *buf, u8_t val);
/**
* @brief Push 24-bit value to the beginning of the buffer
*
* Adds 24-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 24-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_le24(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Push 24-bit value to the beginning of the buffer
*
* Adds 24-bit value in big endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 24-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_be24(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Push 32-bit value to the beginning of the buffer
*
* Adds 32-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 32-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_le32(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Push 32-bit value to the beginning of the buffer
*
* Adds 32-bit value in big endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 32-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_be32(struct net_buf_simple *buf, bt_u32_t val);
/**
* @brief Push 48-bit value to the beginning of the buffer
*
* Adds 48-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 48-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_le48(struct net_buf_simple *buf, u64_t val);
/**
* @brief Push 48-bit value to the beginning of the buffer
*
* Adds 48-bit value in big endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 48-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_be48(struct net_buf_simple *buf, u64_t val);
/**
* @brief Push 64-bit value to the beginning of the buffer
*
* Adds 64-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 64-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_le64(struct net_buf_simple *buf, u64_t val);
/**
* @brief Push 64-bit value to the beginning of the buffer
*
* Adds 64-bit value in big endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 64-bit value to be pushed to the buffer.
*/
void net_buf_simple_push_be64(struct net_buf_simple *buf, u64_t val);
/**
* @brief Remove data from the beginning of the buffer.
*
* Removes data from the beginning of the buffer by modifying the data
* pointer and buffer length.
*
* @param buf Buffer to update.
* @param len Number of bytes to remove.
*
* @return New beginning of the buffer data.
*/
void *net_buf_simple_pull(struct net_buf_simple *buf, size_t len);
/**
* @brief Remove data from the beginning of the buffer.
*
* Removes data from the beginning of the buffer by modifying the data
* pointer and buffer length.
*
* @param buf Buffer to update.
* @param len Number of bytes to remove.
*
* @return Pointer to the old location of the buffer data.
*/
void *net_buf_simple_pull_mem(struct net_buf_simple *buf, size_t len);
/**
* @brief Remove a 8-bit value from the beginning of the buffer
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 8-bit values.
*
* @param buf A valid pointer on a buffer.
*
* @return The 8-bit removed value
*/
u8_t net_buf_simple_pull_u8(struct net_buf_simple *buf);
/**
* @brief Remove and convert 16 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 16-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 16-bit value converted from little endian to host endian.
*/
u16_t net_buf_simple_pull_le16(struct net_buf_simple *buf);
/**
* @brief Remove and convert 16 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 16-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 16-bit value converted from big endian to host endian.
*/
u16_t net_buf_simple_pull_be16(struct net_buf_simple *buf);
/**
* @brief Remove and convert 24 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 24-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 24-bit value converted from little endian to host endian.
*/
bt_u32_t net_buf_simple_pull_le24(struct net_buf_simple *buf);
/**
* @brief Remove and convert 24 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 24-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 24-bit value converted from big endian to host endian.
*/
bt_u32_t net_buf_simple_pull_be24(struct net_buf_simple *buf);
/**
* @brief Remove and convert 32 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 32-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 32-bit value converted from little endian to host endian.
*/
bt_u32_t net_buf_simple_pull_le32(struct net_buf_simple *buf);
/**
* @brief Remove and convert 32 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 32-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 32-bit value converted from big endian to host endian.
*/
bt_u32_t net_buf_simple_pull_be32(struct net_buf_simple *buf);
/**
* @brief Remove and convert 48 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 48-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 48-bit value converted from little endian to host endian.
*/
u64_t net_buf_simple_pull_le48(struct net_buf_simple *buf);
/**
* @brief Remove and convert 48 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 48-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 48-bit value converted from big endian to host endian.
*/
u64_t net_buf_simple_pull_be48(struct net_buf_simple *buf);
/**
* @brief Remove and convert 64 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 64-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 64-bit value converted from little endian to host endian.
*/
u64_t net_buf_simple_pull_le64(struct net_buf_simple *buf);
/**
* @brief Remove and convert 64 bits from the beginning of the buffer.
*
* Same idea as with net_buf_simple_pull(), but a helper for operating
* on 64-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 64-bit value converted from big endian to host endian.
*/
u64_t net_buf_simple_pull_be64(struct net_buf_simple *buf);
/**
* @brief Get the tail pointer for a buffer.
*
* Get a pointer to the end of the data in a buffer.
*
* @param buf Buffer.
*
* @return Tail pointer for the buffer.
*/
static inline u8_t *net_buf_simple_tail(struct net_buf_simple *buf)
{
return buf->data + buf->len;
}
/**
* @brief Check buffer headroom.
*
* Check how much free space there is in the beginning of the buffer.
*
* buf A valid pointer on a buffer
*
* @return Number of bytes available in the beginning of the buffer.
*/
size_t net_buf_simple_headroom(struct net_buf_simple *buf);
/**
* @brief Check buffer tailroom.
*
* Check how much free space there is at the end of the buffer.
*
* @param buf A valid pointer on a buffer
*
* @return Number of bytes available at the end of the buffer.
*/
size_t net_buf_simple_tailroom(struct net_buf_simple *buf);
/**
* @brief Parsing state of a buffer.
*
* This is used for temporarily storing the parsing state of a buffer
* while giving control of the parsing to a routine which we don't
* control.
*/
struct net_buf_simple_state {
/** Offset of the data pointer from the beginning of the storage */
u16_t offset;
/** Length of data */
u16_t len;
};
/**
* @brief Save the parsing state of a buffer.
*
* Saves the parsing state of a buffer so it can be restored later.
*
* @param buf Buffer from which the state should be saved.
* @param state Storage for the state.
*/
static inline void net_buf_simple_save(struct net_buf_simple *buf,
struct net_buf_simple_state *state)
{
state->offset = net_buf_simple_headroom(buf);
state->len = buf->len;
}
/**
* @brief Restore the parsing state of a buffer.
*
* Restores the parsing state of a buffer from a state previously stored
* by net_buf_simple_save().
*
* @param buf Buffer to which the state should be restored.
* @param state Stored state.
*/
static inline void net_buf_simple_restore(struct net_buf_simple *buf,
struct net_buf_simple_state *state)
{
buf->data = buf->__buf + state->offset;
buf->len = state->len;
}
/**
* Flag indicating that the buffer has associated fragments. Only used
* internally by the buffer handling code while the buffer is inside a
* FIFO, meaning this never needs to be explicitly set or unset by the
* net_buf API user. As long as the buffer is outside of a FIFO, i.e.
* in practice always for the user for this API, the buf->frags pointer
* should be used instead.
*/
#define NET_BUF_FRAGS BIT(0)
/**
* Flag indicating that the buffer's associated data pointer, points to
* externally allocated memory. Therefore once ref goes down to zero, the
* pointed data will not need to be deallocated. This never needs to be
* explicitly set or unet by the net_buf API user. Such net_buf is
* exclusively instantiated via net_buf_alloc_with_data() function.
* Reference count mechanism however will behave the same way, and ref
* count going to 0 will free the net_buf but no the data pointer in it.
*/
#define NET_BUF_EXTERNAL_DATA BIT(1)
/**
* @brief Network buffer representation.
*
* This struct is used to represent network buffers. Such buffers are
* normally defined through the NET_BUF_POOL_*_DEFINE() APIs and allocated
* using the net_buf_alloc() API.
*/
struct net_buf {
union {
/** Allow placing the buffer into sys_slist_t */
sys_snode_t node;
/** Fragments associated with this buffer. */
struct net_buf *frags;
};
/** Reference count. */
u8_t ref;
/** Bit-field of buffer flags. */
u8_t flags;
/** Where the buffer should go when freed up. */
u8_t pool_id;
/* Union for convenience access to the net_buf_simple members, also
* preserving the old API.
*/
union {
/* The ABI of this struct must match net_buf_simple */
struct {
/** Pointer to the start of data in the buffer. */
u8_t *data;
/** Length of the data behind the data pointer. */
u16_t len;
/** Amount of data that this buffer can store. */
u16_t size;
/** Start of the data storage. Not to be accessed
* directly (the data pointer should be used
* instead).
*/
u8_t *__buf;
};
struct net_buf_simple b;
};
/** System metadata for this buffer. */
u8_t user_data[CONFIG_NET_BUF_USER_DATA_SIZE] __net_buf_align;
};
struct net_buf_data_cb {
u8_t * (*alloc)(struct net_buf *buf, size_t *size, k_timeout_t timeout);
u8_t * (*ref)(struct net_buf *buf, u8_t *data);
void (*unref)(struct net_buf *buf, u8_t *data);
};
struct net_buf_data_alloc {
const struct net_buf_data_cb *cb;
void *alloc_data;
};
/**
* @brief Network buffer pool representation.
*
* This struct is used to represent a pool of network buffers.
*/
struct net_buf_pool {
/** LIFO to place the buffer into when free */
struct k_lifo free;
/** Number of buffers in pool */
const u16_t buf_count;
/** Number of uninitialized buffers */
u16_t uninit_count;
#if defined(CONFIG_NET_BUF_POOL_USAGE)
/** Amount of available buffers in the pool. */
s16_t avail_count;
/** Total size of the pool. */
const u16_t pool_size;
/** Name of the pool. Used when printing pool information. */
const char *name;
#endif /* CONFIG_NET_BUF_POOL_USAGE */
/** Optional destroy callback when buffer is freed. */
void (*const destroy)(struct net_buf *buf);
/** Data allocation handlers. */
const struct net_buf_data_alloc *alloc;
/** Start of buffer storage array */
struct net_buf * const __bufs;
};
int net_buf_pool_init(struct net_buf_pool *pool);
#define NET_BUF_POOL_INIT(_name)\
net_buf_pool_init(&_name)
/** @cond INTERNAL_HIDDEN */
#if defined(CONFIG_NET_BUF_POOL_USAGE)
#define NET_BUF_POOL_INITIALIZER(_pool, _alloc, _bufs, _count, _destroy) \
{ \
.alloc = _alloc, \
.free = _K_LIFO_INITIALIZER(_pool.free), \
.__bufs = _bufs, \
.buf_count = _count, \
.uninit_count = _count, \
.avail_count = _count, \
.destroy = _destroy, \
.name = STRINGIFY(_pool), \
}
#else
#define NET_BUF_POOL_INITIALIZER(_pool, _alloc, _bufs, _count, _destroy) \
{ \
.alloc = _alloc, \
.free = _K_LIFO_INITIALIZER(_pool.free), \
.__bufs = _bufs, \
.buf_count = _count, \
.uninit_count = _count, \
.destroy = _destroy, \
}
#endif /* CONFIG_NET_BUF_POOL_USAGE */
extern const struct net_buf_data_alloc net_buf_heap_alloc;
/** @endcond */
/**
* @def NET_BUF_POOL_HEAP_DEFINE
* @brief Define a new pool for buffers using the heap for the data.
*
* Defines a net_buf_pool struct and the necessary memory storage (array of
* structs) for the needed amount of buffers. After this, the buffers can be
* accessed from the pool through net_buf_alloc. The pool is defined as a
* static variable, so if it needs to be exported outside the current module
* this needs to happen with the help of a separate pointer rather than an
* extern declaration.
*
* The data payload of the buffers will be allocated from the heap using
* k_malloc, so CONFIG_HEAP_MEM_POOL_SIZE must be set to a positive value.
* This kind of pool does not support blocking on the data allocation, so
* the timeout passed to net_buf_alloc will be always treated as K_NO_WAIT
* when trying to allocate the data. This means that allocation failures,
* i.e. NULL returns, must always be handled cleanly.
*
* If provided with a custom destroy callback, this callback is
* responsible for eventually calling net_buf_destroy() to complete the
* process of returning the buffer to the pool.
*
* @param _name Name of the pool variable.
* @param _count Number of buffers in the pool.
* @param _destroy Optional destroy callback when buffer is freed.
*/
#define NET_BUF_POOL_HEAP_DEFINE(_name, _count, _destroy) \
static struct net_buf net_buf_##_name[_count] __noinit; \
struct net_buf_pool _name __net_buf_align \
__in_section(_net_buf_pool, static, _name) = \
NET_BUF_POOL_INITIALIZER(_name, &net_buf_heap_alloc, \
net_buf_##_name, _count, _destroy)
struct net_buf_pool_fixed {
size_t data_size;
u8_t *data_pool;
};
/** @cond INTERNAL_HIDDEN */
extern const struct net_buf_data_cb net_buf_fixed_cb;
/** @endcond */
/**
* @def NET_BUF_POOL_FIXED_DEFINE
* @brief Define a new pool for buffers based on fixed-size data
*
* Defines a net_buf_pool struct and the necessary memory storage (array of
* structs) for the needed amount of buffers. After this, the buffers can be
* accessed from the pool through net_buf_alloc. The pool is defined as a
* static variable, so if it needs to be exported outside the current module
* this needs to happen with the help of a separate pointer rather than an
* extern declaration.
*
* The data payload of the buffers will be allocated from a byte array
* of fixed sized chunks. This kind of pool does not support blocking on
* the data allocation, so the timeout passed to net_buf_alloc will be
* always treated as K_NO_WAIT when trying to allocate the data. This means
* that allocation failures, i.e. NULL returns, must always be handled
* cleanly.
*
* If provided with a custom destroy callback, this callback is
* responsible for eventually calling net_buf_destroy() to complete the
* process of returning the buffer to the pool.
*
* @param _name Name of the pool variable.
* @param _count Number of buffers in the pool.
* @param _data_size Maximum data payload per buffer.
* @param _destroy Optional destroy callback when buffer is freed.
*/
#ifdef CONFIG_BT_USE_MM
#define NET_BUF_POOL_FIXED_DEFINE(_name, _count, _data_size, _destroy) \
static struct net_buf net_buf_##_name[_count] __noinit; \
static const struct net_buf_pool_fixed net_buf_fixed_##_name = { \
.data_size = _data_size, \
.data_pool = NULL, \
}; \
static const struct net_buf_data_alloc net_buf_fixed_alloc_##_name = {\
.cb = &net_buf_fixed_cb, \
.alloc_data = (void *)&net_buf_fixed_##_name, \
}; \
struct net_buf_pool _name __net_buf_align \
__in_section(_net_buf_pool, static, _name) = \
NET_BUF_POOL_INITIALIZER(_name, &net_buf_fixed_alloc_##_name, \
net_buf_##_name, _count, _destroy)
#else
#define NET_BUF_POOL_FIXED_DEFINE(_name, _count, _data_size, _destroy) \
static struct net_buf net_buf_##_name[_count] __noinit; \
static u8_t __noinit net_buf_data_##_name[_count][_data_size]; \
static const struct net_buf_pool_fixed net_buf_fixed_##_name = { \
.data_size = _data_size, \
.data_pool = (u8_t *)net_buf_data_##_name, \
}; \
static const struct net_buf_data_alloc net_buf_fixed_alloc_##_name = {\
.cb = &net_buf_fixed_cb, \
.alloc_data = (void *)&net_buf_fixed_##_name, \
}; \
struct net_buf_pool _name __net_buf_align \
__in_section(_net_buf_pool, static, _name) = \
NET_BUF_POOL_INITIALIZER(_name, &net_buf_fixed_alloc_##_name, \
net_buf_##_name, _count, _destroy)
#endif
/** @cond INTERNAL_HIDDEN */
extern const struct net_buf_data_cb net_buf_var_cb;
/** @endcond */
/**
* @def NET_BUF_POOL_VAR_DEFINE
* @brief Define a new pool for buffers with variable size payloads
*
* Defines a net_buf_pool struct and the necessary memory storage (array of
* structs) for the needed amount of buffers. After this, the buffers can be
* accessed from the pool through net_buf_alloc. The pool is defined as a
* static variable, so if it needs to be exported outside the current module
* this needs to happen with the help of a separate pointer rather than an
* extern declaration.
*
* The data payload of the buffers will be based on a memory pool from which
* variable size payloads may be allocated.
*
* If provided with a custom destroy callback, this callback is
* responsible for eventually calling net_buf_destroy() to complete the
* process of returning the buffer to the pool.
*
* @param _name Name of the pool variable.
* @param _count Number of buffers in the pool.
* @param _data_size Total amount of memory available for data payloads.
* @param _destroy Optional destroy callback when buffer is freed.
*/
#define NET_BUF_POOL_VAR_DEFINE(_name, _count, _data_size, _destroy) \
static struct net_buf _net_buf_##_name[_count] __noinit; \
K_MEM_POOL_DEFINE(net_buf_mem_pool_##_name, 16, _data_size, 1, 4); \
static const struct net_buf_data_alloc net_buf_data_alloc_##_name = { \
.cb = &net_buf_var_cb, \
.alloc_data = &net_buf_mem_pool_##_name, \
}; \
struct net_buf_pool _name __net_buf_align \
__in_section(_net_buf_pool, static, _name) = \
NET_BUF_POOL_INITIALIZER(_name, &net_buf_data_alloc_##_name, \
_net_buf_##_name, _count, _destroy)
/**
* @def NET_BUF_POOL_DEFINE
* @brief Define a new pool for buffers
*
* Defines a net_buf_pool struct and the necessary memory storage (array of
* structs) for the needed amount of buffers. After this,the buffers can be
* accessed from the pool through net_buf_alloc. The pool is defined as a
* static variable, so if it needs to be exported outside the current module
* this needs to happen with the help of a separate pointer rather than an
* extern declaration.
*
* If provided with a custom destroy callback this callback is
* responsible for eventually calling net_buf_destroy() to complete the
* process of returning the buffer to the pool.
*
* @param _name Name of the pool variable.
* @param _count Number of buffers in the pool.
* @param _size Maximum data size for each buffer.
* @param _ud_size Amount of user data space to reserve.
* @param _destroy Optional destroy callback when buffer is freed.
*/
#define NET_BUF_POOL_DEFINE(_name, _count, _size, _ud_size, _destroy) \
BUILD_ASSERT(_ud_size <= CONFIG_NET_BUF_USER_DATA_SIZE); \
NET_BUF_POOL_FIXED_DEFINE(_name, _count, _size, _destroy)
/**
* @brief Looks up a pool based on its ID.
*
* @param id Pool ID (e.g. from buf->pool_id).
*
* @return Pointer to pool.
*/
struct net_buf_pool *net_buf_pool_get(int id);
/**
* @brief Get a zero-based index for a buffer.
*
* This function will translate a buffer into a zero-based index,
* based on its placement in its buffer pool. This can be useful if you
* want to associate an external array of meta-data contexts with the
* buffers of a pool.
*
* @param buf Network buffer.
*
* @return Zero-based index for the buffer.
*/
int net_buf_id(struct net_buf *buf);
/**
* @brief Allocate a new fixed buffer from a pool.
*
* @param pool Which pool to allocate the buffer from.
* @param timeout Affects the action taken should the pool be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then
* wait as long as necessary. Otherwise, wait until the specified
* timeout. Note that some types of data allocators do not support
* blocking (such as the HEAP type). In this case it's still possible
* for net_buf_alloc() to fail (return NULL) even if it was given
* K_FOREVER.
*
* @return New buffer or NULL if out of buffers.
*/
#if defined(CONFIG_NET_BUF_LOG)
struct net_buf *net_buf_alloc_fixed_debug(struct net_buf_pool *pool,
k_timeout_t timeout, const char *func,
int line);
#define net_buf_alloc_fixed(_pool, _timeout) \
net_buf_alloc_fixed_debug(_pool, _timeout, __func__, __LINE__)
#else
struct net_buf *net_buf_alloc_fixed(struct net_buf_pool *pool,
k_timeout_t timeout);
#endif
/**
* @def net_buf_alloc
*
* @copydetails net_buf_alloc_fixed
*/
#define net_buf_alloc(pool, timeout) net_buf_alloc_fixed(pool, timeout)
/**
* @brief Allocate a new variable length buffer from a pool.
*
* @param pool Which pool to allocate the buffer from.
* @param size Amount of data the buffer must be able to fit.
* @param timeout Affects the action taken should the pool be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then
* wait as long as necessary. Otherwise, wait until the specified
* timeout. Note that some types of data allocators do not support
* blocking (such as the HEAP type). In this case it's still possible
* for net_buf_alloc() to fail (return NULL) even if it was given
* K_FOREVER.
*
* @return New buffer or NULL if out of buffers.
*/
#if defined(CONFIG_NET_BUF_LOG)
struct net_buf *net_buf_alloc_len_debug(struct net_buf_pool *pool, size_t size,
k_timeout_t timeout, const char *func,
int line);
#define net_buf_alloc_len(_pool, _size, _timeout) \
net_buf_alloc_len_debug(_pool, _size, _timeout, __func__, __LINE__)
#else
struct net_buf *net_buf_alloc_len(struct net_buf_pool *pool, size_t size,
k_timeout_t timeout);
#endif
/**
* @brief Allocate a new buffer from a pool but with external data pointer.
*
* Allocate a new buffer from a pool, where the data pointer comes from the
* user and not from the pool.
*
* @param pool Which pool to allocate the buffer from.
* @param data External data pointer
* @param size Amount of data the pointed data buffer if able to fit.
* @param timeout Affects the action taken should the pool be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then
* wait as long as necessary. Otherwise, wait until the specified
* timeout. Note that some types of data allocators do not support
* blocking (such as the HEAP type). In this case it's still possible
* for net_buf_alloc() to fail (return NULL) even if it was given
* K_FOREVER.
*
* @return New buffer or NULL if out of buffers.
*/
#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,
k_timeout_t timeout,
const char *func, int line);
#define net_buf_alloc_with_data(_pool, _data_, _size, _timeout) \
net_buf_alloc_with_data_debug(_pool, _data_, _size, _timeout, \
__func__, __LINE__)
#else
struct net_buf *net_buf_alloc_with_data(struct net_buf_pool *pool,
void *data, size_t size,
k_timeout_t timeout);
#endif
/**
* @brief Get a buffer from a FIFO.
*
* @param fifo Which FIFO to take the buffer from.
* @param timeout Affects the action taken should the FIFO be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then wait as
* long as necessary. Otherwise, wait until the specified timeout.
*
* @return New buffer or NULL if the FIFO is empty.
*/
#if defined(CONFIG_NET_BUF_LOG)
struct net_buf *net_buf_get_debug(struct kfifo *fifo, k_timeout_t timeout,
const char *func, int line);
#define net_buf_get(_fifo, _timeout) \
net_buf_get_debug(_fifo, _timeout, __func__, __LINE__)
#else
struct net_buf *net_buf_get(struct kfifo *fifo, k_timeout_t timeout);
#endif
/**
* @brief Destroy buffer from custom destroy callback
*
* This helper is only intended to be used from custom destroy callbacks.
* If no custom destroy callback is given to NET_BUF_POOL_*_DEFINE() then
* there is no need to use this API.
*
* @param buf Buffer to destroy.
*/
static inline void net_buf_destroy(struct net_buf *buf)
{
struct net_buf_pool *pool = net_buf_pool_get(buf->pool_id);
k_lifo_put(&pool->free, buf);
}
/**
* @brief Reset buffer
*
* Reset buffer data and flags so it can be reused for other purposes.
*
* @param buf Buffer to reset.
*/
void net_buf_reset(struct net_buf *buf);
/**
* @brief Initialize buffer with the given headroom.
*
* The buffer is not expected to contain any data when this API is called.
*
* @param buf Buffer to initialize.
* @param reserve How much headroom to reserve.
*/
void net_buf_simple_reserve(struct net_buf_simple *buf, size_t reserve);
/**
* @brief Put a buffer into a list
*
* If the buffer contains follow-up fragments this function will take care of
* inserting them as well into the list.
*
* @param list Which list to append the buffer to.
* @param buf Buffer.
*/
void net_buf_slist_put(sys_slist_t *list, struct net_buf *buf);
/**
* @brief Get a buffer from a list.
*
* If the buffer had any fragments, these will automatically be recovered from
* the list as well and be placed to the buffer's fragment list.
*
* @param list Which list to take the buffer from.
*
* @return New buffer or NULL if the FIFO is empty.
*/
struct net_buf *net_buf_slist_get(sys_slist_t *list);
/**
* @brief Put a buffer to the end of a FIFO.
*
* If the buffer contains follow-up fragments this function will take care of
* inserting them as well into the FIFO.
*
* @param fifo Which FIFO to put the buffer to.
* @param buf Buffer.
*/
void net_buf_put(struct kfifo *fifo, struct net_buf *buf);
/**
* @brief Decrements the reference count of a buffer.
*
* The buffer is put back into the pool if the reference count reaches zero.
*
* @param buf A valid pointer on a buffer
*/
#if defined(CONFIG_NET_BUF_LOG)
void net_buf_unref_debug(struct net_buf *buf, const char *func, int line);
#define net_buf_unref(_buf) \
net_buf_unref_debug(_buf, __func__, __LINE__)
#else
void net_buf_unref(struct net_buf *buf);
#endif
/**
* @brief Increment the reference count of a buffer.
*
* @param buf A valid pointer on a buffer
*
* @return the buffer newly referenced
*/
struct net_buf *net_buf_ref(struct net_buf *buf);
/**
* @brief Clone buffer
*
* Duplicate given buffer including any data and headers currently stored.
*
* @param buf A valid pointer on a buffer
* @param timeout Affects the action taken should the pool be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then
* wait as long as necessary. Otherwise, wait until the specified
* timeout.
*
* @return Cloned buffer or NULL if out of buffers.
*/
struct net_buf *net_buf_clone(struct net_buf *buf, k_timeout_t timeout);
/**
* @brief Get a pointer to the user data of a buffer.
*
* @param buf A valid pointer on a buffer
*
* @return Pointer to the user data of the buffer.
*/
static inline void *net_buf_user_data(const struct net_buf *buf)
{
return (void *)buf->user_data;
}
/**
* @def net_buf_reserve
* @brief Initialize buffer with the given headroom.
*
* The buffer is not expected to contain any data when this API is called.
*
* @param buf Buffer to initialize.
* @param reserve How much headroom to reserve.
*/
#define net_buf_reserve(buf, reserve) net_buf_simple_reserve(&(buf)->b, \
reserve)
/**
* @def net_buf_add
* @brief Prepare data to be added at the end of the buffer
*
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param len Number of bytes to increment the length with.
*
* @return The original tail of the buffer.
*/
#define net_buf_add(buf, len) net_buf_simple_add(&(buf)->b, len)
/**
* @def net_buf_add_mem
* @brief Copies the given number of bytes to the end of the buffer
*
* Increments the data length of the buffer to account for more data at
* the end.
*
* @param buf Buffer to update.
* @param mem Location of data to be added.
* @param len Length of data to be added
*
* @return The original tail of the buffer.
*/
#define net_buf_add_mem(buf, mem, len) net_buf_simple_add_mem(&(buf)->b, \
mem, len)
/**
* @def net_buf_add_u8
* @brief Add (8-bit) byte at the end of the buffer
*
* Increments the data length of the buffer to account for more data at
* the end.
*
* @param buf Buffer to update.
* @param val byte value to be added.
*
* @return Pointer to the value added
*/
#define net_buf_add_u8(buf, val) net_buf_simple_add_u8(&(buf)->b, val)
/**
* @def net_buf_add_le16
* @brief Add 16-bit value at the end of the buffer
*
* Adds 16-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 16-bit value to be added.
*/
#define net_buf_add_le16(buf, val) net_buf_simple_add_le16(&(buf)->b, val)
/**
* @def net_buf_add_be16
* @brief Add 16-bit value at the end of the buffer
*
* Adds 16-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 16-bit value to be added.
*/
#define net_buf_add_be16(buf, val) net_buf_simple_add_be16(&(buf)->b, val)
/**
* @def net_buf_add_le24
* @brief Add 24-bit value at the end of the buffer
*
* Adds 24-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 24-bit value to be added.
*/
#define net_buf_add_le24(buf, val) net_buf_simple_add_le24(&(buf)->b, val)
/**
* @def net_buf_add_be24
* @brief Add 24-bit value at the end of the buffer
*
* Adds 24-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 24-bit value to be added.
*/
#define net_buf_add_be24(buf, val) net_buf_simple_add_be24(&(buf)->b, val)
/**
* @def net_buf_add_le32
* @brief Add 32-bit value at the end of the buffer
*
* Adds 32-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 32-bit value to be added.
*/
#define net_buf_add_le32(buf, val) net_buf_simple_add_le32(&(buf)->b, val)
/**
* @def net_buf_add_be32
* @brief Add 32-bit value at the end of the buffer
*
* Adds 32-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 32-bit value to be added.
*/
#define net_buf_add_be32(buf, val) net_buf_simple_add_be32(&(buf)->b, val)
/**
* @def net_buf_add_le48
* @brief Add 48-bit value at the end of the buffer
*
* Adds 48-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 48-bit value to be added.
*/
#define net_buf_add_le48(buf, val) net_buf_simple_add_le48(&(buf)->b, val)
/**
* @def net_buf_add_be48
* @brief Add 48-bit value at the end of the buffer
*
* Adds 48-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 48-bit value to be added.
*/
#define net_buf_add_be48(buf, val) net_buf_simple_add_be48(&(buf)->b, val)
/**
* @def net_buf_add_le64
* @brief Add 64-bit value at the end of the buffer
*
* Adds 64-bit value in little endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 64-bit value to be added.
*/
#define net_buf_add_le64(buf, val) net_buf_simple_add_le64(&(buf)->b, val)
/**
* @def net_buf_add_be64
* @brief Add 64-bit value at the end of the buffer
*
* Adds 64-bit value in big endian format at the end of buffer.
* Increments the data length of a buffer to account for more data
* at the end.
*
* @param buf Buffer to update.
* @param val 64-bit value to be added.
*/
#define net_buf_add_be64(buf, val) net_buf_simple_add_be64(&(buf)->b, val)
/**
* @def net_buf_push
* @brief Push data to the beginning of the buffer.
*
* Modifies the data pointer and buffer length to account for more data
* in the beginning of the buffer.
*
* @param buf Buffer to update.
* @param len Number of bytes to add to the beginning.
*
* @return The new beginning of the buffer data.
*/
#define net_buf_push(buf, len) net_buf_simple_push(&(buf)->b, len)
/**
* @def net_buf_push_le16
* @brief Push 16-bit value to the beginning of the buffer
*
* Adds 16-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 16-bit value to be pushed to the buffer.
*/
#define net_buf_push_le16(buf, val) net_buf_simple_push_le16(&(buf)->b, val)
/**
* @def net_buf_push_be16
* @brief Push 16-bit value to the beginning of the buffer
*
* Adds 16-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 16-bit value to be pushed to the buffer.
*/
#define net_buf_push_be16(buf, val) net_buf_simple_push_be16(&(buf)->b, val)
/**
* @def net_buf_push_u8
* @brief Push 8-bit value to the beginning of the buffer
*
* Adds 8-bit value the beginning of the buffer.
*
* @param buf Buffer to update.
* @param val 8-bit value to be pushed to the buffer.
*/
#define net_buf_push_u8(buf, val) net_buf_simple_push_u8(&(buf)->b, val)
/**
* @def net_buf_push_le24
* @brief Push 24-bit value to the beginning of the buffer
*
* Adds 24-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 24-bit value to be pushed to the buffer.
*/
#define net_buf_push_le24(buf, val) net_buf_simple_push_le24(&(buf)->b, val)
/**
* @def net_buf_push_be24
* @brief Push 24-bit value to the beginning of the buffer
*
* Adds 24-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 24-bit value to be pushed to the buffer.
*/
#define net_buf_push_be24(buf, val) net_buf_simple_push_be24(&(buf)->b, val)
/**
* @def net_buf_push_le32
* @brief Push 32-bit value to the beginning of the buffer
*
* Adds 32-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 32-bit value to be pushed to the buffer.
*/
#define net_buf_push_le32(buf, val) net_buf_simple_push_le32(&(buf)->b, val)
/**
* @def net_buf_push_be32
* @brief Push 32-bit value to the beginning of the buffer
*
* Adds 32-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 32-bit value to be pushed to the buffer.
*/
#define net_buf_push_be32(buf, val) net_buf_simple_push_be32(&(buf)->b, val)
/**
* @def net_buf_push_le48
* @brief Push 48-bit value to the beginning of the buffer
*
* Adds 48-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 48-bit value to be pushed to the buffer.
*/
#define net_buf_push_le48(buf, val) net_buf_simple_push_le48(&(buf)->b, val)
/**
* @def net_buf_push_be48
* @brief Push 48-bit value to the beginning of the buffer
*
* Adds 48-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 48-bit value to be pushed to the buffer.
*/
#define net_buf_push_be48(buf, val) net_buf_simple_push_be48(&(buf)->b, val)
/**
* @def net_buf_push_le64
* @brief Push 64-bit value to the beginning of the buffer
*
* Adds 64-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 64-bit value to be pushed to the buffer.
*/
#define net_buf_push_le64(buf, val) net_buf_simple_push_le64(&(buf)->b, val)
/**
* @def net_buf_push_be64
* @brief Push 64-bit value to the beginning of the buffer
*
* Adds 64-bit value in little endian format to the beginning of the
* buffer.
*
* @param buf Buffer to update.
* @param val 64-bit value to be pushed to the buffer.
*/
#define net_buf_push_be64(buf, val) net_buf_simple_push_be64(&(buf)->b, val)
/**
* @def net_buf_pull
* @brief Remove data from the beginning of the buffer.
*
* Removes data from the beginning of the buffer by modifying the data
* pointer and buffer length.
*
* @param buf Buffer to update.
* @param len Number of bytes to remove.
*
* @return New beginning of the buffer data.
*/
#define net_buf_pull(buf, len) net_buf_simple_pull(&(buf)->b, len)
/**
* @def net_buf_pull_mem
* @brief Remove data from the beginning of the buffer.
*
* Removes data from the beginning of the buffer by modifying the data
* pointer and buffer length.
*
* @param buf Buffer to update.
* @param len Number of bytes to remove.
*
* @return Pointer to the old beginning of the buffer data.
*/
#define net_buf_pull_mem(buf, len) net_buf_simple_pull_mem(&(buf)->b, len)
/**
* @def net_buf_pull_u8
* @brief Remove a 8-bit value from the beginning of the buffer
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 8-bit values.
*
* @param buf A valid pointer on a buffer.
*
* @return The 8-bit removed value
*/
#define net_buf_pull_u8(buf) net_buf_simple_pull_u8(&(buf)->b)
/**
* @def net_buf_pull_le16
* @brief Remove and convert 16 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 16-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 16-bit value converted from little endian to host endian.
*/
#define net_buf_pull_le16(buf) net_buf_simple_pull_le16(&(buf)->b)
/**
* @def net_buf_pull_be16
* @brief Remove and convert 16 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 16-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 16-bit value converted from big endian to host endian.
*/
#define net_buf_pull_be16(buf) net_buf_simple_pull_be16(&(buf)->b)
/**
* @def net_buf_pull_le24
* @brief Remove and convert 24 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 24-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 24-bit value converted from little endian to host endian.
*/
#define net_buf_pull_le24(buf) net_buf_simple_pull_le24(&(buf)->b)
/**
* @def net_buf_pull_be24
* @brief Remove and convert 24 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 24-bit big endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 24-bit value converted from big endian to host endian.
*/
#define net_buf_pull_be24(buf) net_buf_simple_pull_be24(&(buf)->b)
/**
* @def net_buf_pull_le32
* @brief Remove and convert 32 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 32-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 32-bit value converted from little endian to host endian.
*/
#define net_buf_pull_le32(buf) net_buf_simple_pull_le32(&(buf)->b)
/**
* @def net_buf_pull_be32
* @brief Remove and convert 32 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 32-bit big endian data.
*
* @param buf A valid pointer on a buffer
*
* @return 32-bit value converted from big endian to host endian.
*/
#define net_buf_pull_be32(buf) net_buf_simple_pull_be32(&(buf)->b)
/**
* @def net_buf_pull_le48
* @brief Remove and convert 48 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 48-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 48-bit value converted from little endian to host endian.
*/
#define net_buf_pull_le48(buf) net_buf_simple_pull_le48(&(buf)->b)
/**
* @def net_buf_pull_be48
* @brief Remove and convert 48 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 48-bit big endian data.
*
* @param buf A valid pointer on a buffer
*
* @return 48-bit value converted from big endian to host endian.
*/
#define net_buf_pull_be48(buf) net_buf_simple_pull_be48(&(buf)->b)
/**
* @def net_buf_pull_le64
* @brief Remove and convert 64 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 64-bit little endian data.
*
* @param buf A valid pointer on a buffer.
*
* @return 64-bit value converted from little endian to host endian.
*/
#define net_buf_pull_le64(buf) net_buf_simple_pull_le64(&(buf)->b)
/**
* @def net_buf_pull_be64
* @brief Remove and convert 64 bits from the beginning of the buffer.
*
* Same idea as with net_buf_pull(), but a helper for operating on
* 64-bit big endian data.
*
* @param buf A valid pointer on a buffer
*
* @return 64-bit value converted from big endian to host endian.
*/
#define net_buf_pull_be64(buf) net_buf_simple_pull_be64(&(buf)->b)
/**
* @def net_buf_tailroom
* @brief Check buffer tailroom.
*
* Check how much free space there is at the end of the buffer.
*
* @param buf A valid pointer on a buffer
*
* @return Number of bytes available at the end of the buffer.
*/
#define net_buf_tailroom(buf) net_buf_simple_tailroom(&(buf)->b)
/**
* @def net_buf_headroom
* @brief Check buffer headroom.
*
* Check how much free space there is in the beginning of the buffer.
*
* buf A valid pointer on a buffer
*
* @return Number of bytes available in the beginning of the buffer.
*/
#define net_buf_headroom(buf) net_buf_simple_headroom(&(buf)->b)
/**
* @def net_buf_tail
* @brief Get the tail pointer for a buffer.
*
* Get a pointer to the end of the data in a buffer.
*
* @param buf Buffer.
*
* @return Tail pointer for the buffer.
*/
#define net_buf_tail(buf) net_buf_simple_tail(&(buf)->b)
/**
* @brief Find the last fragment in the fragment list.
*
* @return Pointer to last fragment in the list.
*/
struct net_buf *net_buf_frag_last(struct net_buf *frags);
/**
* @brief Insert a new fragment to a chain of bufs.
*
* Insert a new fragment into the buffer fragments list after the parent.
*
* Note: This function takes ownership of the fragment reference so the
* caller is not required to unref.
*
* @param parent Parent buffer/fragment.
* @param frag Fragment to insert.
*/
void net_buf_frag_insert(struct net_buf *parent, struct net_buf *frag);
/**
* @brief Add a new fragment to the end of a chain of bufs.
*
* Append a new fragment into the buffer fragments list.
*
* Note: This function takes ownership of the fragment reference so the
* caller is not required to unref.
*
* @param head Head of the fragment chain.
* @param frag Fragment to add.
*
* @return New head of the fragment chain. Either head (if head
* was non-NULL) or frag (if head was NULL).
*/
struct net_buf *net_buf_frag_add(struct net_buf *head, struct net_buf *frag);
/**
* @brief Delete existing fragment from a chain of bufs.
*
* @param parent Parent buffer/fragment, or NULL if there is no parent.
* @param frag Fragment to delete.
*
* @return Pointer to the buffer following the fragment, or NULL if it
* had no further fragments.
*/
#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);
#define net_buf_frag_del(_parent, _frag) \
net_buf_frag_del_debug(_parent, _frag, __func__, __LINE__)
#else
struct net_buf *net_buf_frag_del(struct net_buf *parent, struct net_buf *frag);
#endif
/**
* @brief Copy bytes from net_buf chain starting at offset to linear buffer
*
* Copy (extract) @a len bytes from @a src net_buf chain, starting from @a
* offset in it, to a linear buffer @a dst. Return number of bytes actually
* copied, which may be less than requested, if net_buf chain doesn't have
* enough data, or destination buffer is too small.
*
* @param dst Destination buffer
* @param dst_len Destination buffer length
* @param src Source net_buf chain
* @param offset Starting offset to copy from
* @param len Number of bytes to copy
* @return number of bytes actually copied
*/
size_t net_buf_linearize(void *dst, size_t dst_len,
struct net_buf *src, size_t offset, size_t len);
/**
* @typedef net_buf_allocator_cb
* @brief Network buffer allocator callback.
*
* @details The allocator callback is called when net_buf_append_bytes
* needs to allocate a new net_buf.
*
* @param timeout Affects the action taken should the net buf pool be empty.
* If K_NO_WAIT, then return immediately. If K_FOREVER, then
* wait as long as necessary. Otherwise, wait until the specified
* timeout.
* @param user_data The user data given in net_buf_append_bytes call.
* @return pointer to allocated net_buf or NULL on error.
*/
typedef struct net_buf *(*net_buf_allocator_cb)(k_timeout_t timeout,
void *user_data);
/**
* @brief Append data to a list of net_buf
*
* @details Append data to a net_buf. If there is not enough space in the
* net_buf then more net_buf will be added, unless there are no free net_buf
* and timeout occurs.
*
* @param buf Network buffer.
* @param len Total length of input data
* @param value Data to be added
* @param timeout Timeout is passed to the net_buf allocator callback.
* @param allocate_cb When a new net_buf is required, use this callback.
* @param user_data A user data pointer to be supplied to the allocate_cb.
* This pointer is can be anything from a mem_pool or a net_pkt, the
* logic is left up to the allocate_cb function.
*
* @return Length of data actually added. This may be less than input
* length if other timeout than K_FOREVER was used, and there
* were no free fragments in a pool to accommodate all data.
*/
size_t net_buf_append_bytes(struct net_buf *buf, size_t len,
const void *value, k_timeout_t timeout,
net_buf_allocator_cb allocate_cb, void *user_data);
/**
* @brief Skip N number of bytes in a net_buf
*
* @details Skip N number of bytes starting from fragment's offset. If the total
* length of data is placed in multiple fragments, this function will skip from
* all fragments until it reaches N number of bytes. Any fully skipped buffers
* are removed from the net_buf list.
*
* @param buf Network buffer.
* @param len Total length of data to be skipped.
*
* @return Pointer to the fragment or
* NULL and pos is 0 after successful skip,
* NULL and pos is 0xffff otherwise.
*/
static inline struct net_buf *net_buf_skip(struct net_buf *buf, size_t len)
{
while (buf && len--) {
net_buf_pull_u8(buf);
if (!buf->len) {
buf = net_buf_frag_del(NULL, buf);
}
}
return buf;
}
/**
* @brief Calculate amount of bytes stored in fragments.
*
* Calculates the total amount of data stored in the given buffer and the
* fragments linked to it.
*
* @param buf Buffer to start off with.
*
* @return Number of bytes in the buffer and its fragments.
*/
static inline size_t net_buf_frags_len(struct net_buf *buf)
{
size_t bytes = 0;
while (buf) {
bytes += buf->len;
buf = buf->frags;
}
return bytes;
}
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __NET_BUF_H */
| YifuLiu/AliOS-Things | components/ble_host/include/net/buf.h | C | apache-2.0 | 62,366 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef WORK_H
#define WORK_H
#if defined(__cplusplus)
extern "C"
{
#endif
#include "ble_os.h"
struct k_work_q {
struct k_queue queue;
};
int k_work_q_start();
enum {
K_WORK_STATE_PENDING,
};
struct k_work;
/* work define*/
typedef void (*k_work_handler_t)(struct k_work *work);
struct k_work {
void *_reserved;
k_work_handler_t handler;
atomic_t flags[1];
uint32_t start_ms;
uint32_t timeout;
int index;
};
#define _K_WORK_INITIALIZER(work_handler) \
{ \
._reserved = NULL, \
.handler = work_handler, \
.flags = { 0 } \
}
#define K_WORK_INITIALIZER DEPRECATED_MACRO _K_WORK_INITIALIZER
int k_work_init(struct k_work *work, k_work_handler_t handler);
void k_work_submit(struct k_work *work);
/*delay work define*/
struct k_delayed_work {
struct k_work work;
};
void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler);
int k_delayed_work_submit(struct k_delayed_work *work, uint32_t delay);
int k_delayed_work_cancel(struct k_delayed_work *work);
int k_delayed_work_remaining_get(struct k_delayed_work *work);
#ifdef __cplusplus
}
#endif
#endif /* WORK_H */
| YifuLiu/AliOS-Things | components/ble_host/include/work.h | C | apache-2.0 | 1,242 |
#!/usr/bin/env python
# Copyright (c) 2018, Ulf Magnusson
# SPDX-License-Identifier: ISC
# Generates a C header from the configuration, matching the format of
# include/generated/autoconf.h in the kernel.
#
# Optionally generates a directory structure with one file per symbol that can
# be used to implement incremental builds. See the docstring for
# Kconfig.sync_deps() in Kconfiglib.
#
# Usage (see argument help texts for more information):
#
# genconfig.py [-h] [--header-path HEADER_FILE]
# [--sync-deps [OUTPUT_DIR]] [--config-out CONFIG_FILE]
# [KCONFIG_FILENAME]
import argparse
import kconfiglib
DESCRIPTION = """
Generates a header file with defines from the configuration. Optionally
creates/updates a directory with incremental build information as well (see the
docstring for the Kconfig.sync_deps() function in Kconfiglib). The .config file
to generate the configuration from can be specified by setting the
KCONFIG_CONFIG environment variable.
"""
DEFAULT_HEADER_PATH = "config.h"
DEFAULT_SYNC_DEPS_PATH = "deps/"
def main():
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
"--header-path",
metavar="HEADER_FILE",
default=DEFAULT_HEADER_PATH,
help="Path for the generated header file (default: {})"
.format(DEFAULT_HEADER_PATH))
parser.add_argument(
"--sync-deps",
dest="sync_deps_path",
metavar="OUTPUT_DIR",
nargs="?",
const=DEFAULT_SYNC_DEPS_PATH,
help="Enable generation of build dependency information for "
"incremental builds, optionally specifying the output path "
"(default: {})".format(DEFAULT_SYNC_DEPS_PATH))
parser.add_argument(
"--config-out",
dest="config_path",
metavar="CONFIG_FILE",
help="Write the configuration to the specified filename. "
"This is useful if you include .config files in Makefiles, as "
"the generated configuration file will be a full .config file "
"even if .config is outdated. The generated configuration "
"matches what olddefconfig would produce. If you use "
"--sync-deps, you can include deps/auto.conf instead. "
"--config-out is meant for cases where incremental build "
"information isn't needed.")
parser.add_argument(
"kconfig_filename",
metavar="KCONFIG_FILENAME",
nargs="?",
default="Kconfig",
help="Top-level Kconfig file (default: Kconfig)")
parser.add_argument(
"--defconfig-file",
dest="defconfig_file",
metavar="DEFCONFIG_FILENAME",
nargs="?",
default=".config",
help="defconfig")
args = parser.parse_args()
kconf = kconfiglib.Kconfig(args.kconfig_filename)
kconf.load_config(args.defconfig_file)
kconf.write_autoconf(args.header_path)
if args.sync_deps_path is not None:
kconf.sync_deps(args.sync_deps_path)
if args.config_path is not None:
kconf.write_config(args.config_path)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/ble_host/script/Kconfiglib-10.21.0/genconfig.py | Python | apache-2.0 | 3,161 |
# Copyright (c) 2011-2018, Ulf Magnusson
# SPDX-License-Identifier: ISC
"""
Overview
========
Kconfiglib is a Python 2/3 library for scripting and extracting information
from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
configuration systems.
See the homepage at https://github.com/ulfalizer/Kconfiglib for a longer
overview.
Using Kconfiglib on the Linux kernel with the Makefile targets
==============================================================
For the Linux kernel, a handy interface is provided by the
scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
the 'patch' utility:
$ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | git am
$ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | patch -p1
Warning: Not passing -p1 to patch will cause the wrong file to be patched.
Please tell me if the patch does not apply. It should be trivial to apply
manually, as it's just a block of text that needs to be inserted near the other
*conf: targets in scripts/kconfig/Makefile.
Look further down for a motivation for the Makefile patch and for instructions
on how you can use Kconfiglib without it.
If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
so that you can also just clone Kconfiglib into the kernel root:
$ git clone git://github.com/ulfalizer/Kconfiglib.git
$ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
Warning: The directory name Kconfiglib/ is significant in this case, because
it's added to PYTHONPATH by the new targets in makefile.patch.
The targets added by the Makefile patch are described in the following
sections.
make kmenuconfig
----------------
This target runs the curses menuconfig interface with Python 3 (Python 2 is
currently not supported for the menuconfig).
make [ARCH=<arch>] iscriptconfig
--------------------------------
This target gives an interactive Python prompt where a Kconfig instance has
been preloaded and is available in 'kconf'. To change the Python interpreter
used, pass PYTHONCMD=<executable> to make. The default is "python".
To get a feel for the API, try evaluating and printing the symbols in
kconf.defined_syms, and explore the MenuNode menu tree starting at
kconf.top_node by following 'next' and 'list' pointers.
The item contained in a menu node is found in MenuNode.item (note that this can
be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
symbols and choices have a 'nodes' attribute containing their menu nodes
(usually only one). Printing a menu node will print its item, in Kconfig
format.
If you want to look up a symbol by name, use the kconf.syms dictionary.
make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
----------------------------------------------------
This target runs the Python script given by the SCRIPT parameter on the
configuration. sys.argv[1] holds the name of the top-level Kconfig file
(currently always "Kconfig" in practice), and sys.argv[2] holds the SCRIPT_ARG
argument, if given.
See the examples/ subdirectory for example scripts.
make dumpvarsconfig
-------------------
This target prints a list of all environment variables referenced from the
Kconfig files, together with their values. See the
Kconfiglib/examples/dumpvars.py script.
Only environment variables that are referenced via the Kconfig preprocessor
$(FOO) syntax are included. The preprocessor was added in Linux 4.18.
Using Kconfiglib without the Makefile targets
=============================================
The make targets are only needed to pick up environment variables exported from
the Kbuild makefiles and referenced inside Kconfig files, via e.g.
'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
These variables are referenced as of writing (Linux 4.18), together with sample
values:
srctree (.)
ARCH (x86)
SRCARCH (x86)
KERNELVERSION (4.18.0)
CC (gcc)
HOSTCC (gcc)
HOSTCXX (g++)
CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
If your kernel is recent enough (4.18+), you can get a list of referenced
environment variables via 'make dumpvarsconfig' (see above). Note that this
command is added by the Makefile patch.
To run Kconfiglib without the Makefile patch, set the environment variables
manually:
$ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
>>> import kconfiglib
>>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
Search the top-level Makefile for "Additional ARCH settings" to see other
possibilities for ARCH and SRCARCH.
Intro to symbol values
======================
Kconfiglib has the same assignment semantics as the C implementation.
Any symbol can be assigned a value by the user (via Kconfig.load_config() or
Symbol.set_value()), but this user value is only respected if the symbol is
visible, which corresponds to it (currently) being visible in the menuconfig
interface.
For symbols with prompts, the visibility of the symbol is determined by the
condition on the prompt. Symbols without prompts are never visible, so setting
a user value on them is pointless. A warning will be printed by default if
Symbol.set_value() is called on a promptless symbol. Assignments to promptless
symbols are normal within a .config file, so no similar warning will be printed
by load_config().
Dependencies from parents and 'if'/'depends on' are propagated to properties,
including prompts, so these two configurations are logically equivalent:
(1)
menu "menu"
depends on A
if B
config FOO
tristate "foo" if D
default y
depends on C
endif
endmenu
(2)
menu "menu"
depends on A
config FOO
tristate "foo" if A && B && C && D
default y if A && B && C
endmenu
In this example, A && B && C && D (the prompt condition) needs to be non-n for
FOO to be visible (assignable). If its value is m, the symbol can only be
assigned the value m: The visibility sets an upper bound on the value that can
be assigned by the user, and any higher user value will be truncated down.
'default' properties are independent of the visibility, though a 'default' will
often get the same condition as the prompt due to dependency propagation.
'default' properties are used if the symbol is not visible or has no user
value.
Symbols with no user value (or that have a user value but are not visible) and
no (active) 'default' default to n for bool/tristate symbols, and to the empty
string for other symbol types.
'select' works similarly to symbol visibility, but sets a lower bound on the
value of the symbol. The lower bound is determined by the value of the
select*ing* symbol. 'select' does not respect visibility, so non-visible
symbols can be forced to a particular (minimum) value by a select as well.
For non-bool/tristate symbols, it only matters whether the visibility is n or
non-n: m visibility acts the same as y visibility.
Conditions on 'default' and 'select' work in mostly intuitive ways. If the
condition is n, the 'default' or 'select' is disabled. If it is m, the
'default' or 'select' value (the value of the selecting symbol) is truncated
down to m.
When writing a configuration with Kconfig.write_config(), only symbols that are
visible, have an (active) default, or are selected will get written out (note
that this includes all symbols that would accept user values). Kconfiglib
matches the .config format produced by the C implementations down to the
character. This eases testing.
For a visible bool/tristate symbol FOO with value n, this line is written to
.config:
# CONFIG_FOO is not set
The point is to remember the user n selection (which might differ from the
default value the symbol would get), while at the same sticking to the rule
that undefined corresponds to n (.config uses Makefile format, making the line
above a comment). When the .config file is read back in, this line will be
treated the same as the following assignment:
CONFIG_FOO=n
In Kconfiglib, the set of (currently) assignable values for a bool/tristate
symbol appear in Symbol.assignable. For other symbol types, just check if
sym.visibility is non-0 (non-n) to see whether the user value will have an
effect.
Intro to the menu tree
======================
The menu structure, as seen in e.g. menuconfig, is represented by a tree of
MenuNode objects. The top node of the configuration corresponds to an implicit
top-level menu, the title of which is shown at the top in the standard
menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
Kconfiglib.)
The top node is found in Kconfig.top_node. From there, you can visit child menu
nodes by following the 'list' pointer, and any following menu nodes by
following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
pointer too due to submenus created implicitly from dependencies.
MenuNode.item is either a Symbol or a Choice object, or one of the constants
MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
which also holds the title for menus and comments. For Symbol and Choice,
MenuNode.help holds the help text (if any, otherwise None).
Most symbols will only have a single menu node. A symbol defined in multiple
locations will have one menu node for each location. The list of menu nodes for
a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
Note that prompts and help texts for symbols and choices are stored in their
menu node(s) rather than in the Symbol or Choice objects themselves. This makes
it possible to define a symbol in multiple locations with a different prompt or
help text in each location. To get the help text or prompt for a symbol with a
single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
The prompt is a (text, condition) tuple, where condition determines the
visibility (see 'Intro to expressions' below).
This organization mirrors the C implementation. MenuNode is called
'struct menu' there, but I thought "menu" was a confusing name.
It is possible to give a Choice a name and define it in multiple locations,
hence why Choice.nodes is also a list.
As a convenience, the properties added at a particular definition location are
available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
when generating documentation, so that symbols/choices defined in multiple
locations can be shown with the correct properties at each location.
Intro to expressions
====================
Expressions can be evaluated with the expr_value() function and printed with
the expr_str() function (these are used internally as well). Evaluating an
expression always yields a tristate value, where n, m, and y are represented as
0, 1, and 2, respectively.
The following table should help you figure out how expressions are represented.
A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
constant, etc.
Expression Representation
---------- --------------
A A
"A" A (constant symbol)
!A (NOT, A)
A && B (AND, A, B)
A && B && C (AND, A, (AND, B, C))
A || B (OR, A, B)
A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
A = B (EQUAL, A, B)
A != "foo" (UNEQUAL, A, foo (constant symbol))
A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
n Kconfig.n (constant symbol)
m Kconfig.m (constant symbol)
y Kconfig.y (constant symbol)
"y" Kconfig.y (constant symbol)
Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
represented as constant symbols, so the only values that appear in expressions
are symbols***. This mirrors the C implementation.
***For choice symbols, the parent Choice will appear in expressions as well,
but it's usually invisible as the value interfaces of Symbol and Choice are
identical. This mirrors the C implementation and makes different choice modes
"just work".
Manual evaluation examples:
- The value of A && B is min(A.tri_value, B.tri_value)
- The value of A || B is max(A.tri_value, B.tri_value)
- The value of !A is 2 - A.tri_value
- The value of A = B is 2 (y) if A.str_value == B.str_value, and 0 (n)
otherwise. Note that str_value is used here instead of tri_value.
For constant (as well as undefined) symbols, str_value matches the name of
the symbol. This mirrors the C implementation and explains why
'depends on SYM = "foo"' above works as expected.
n/m/y are automatically converted to the corresponding constant symbols
"n"/"m"/"y" (Kconfig.n/m/y) during parsing.
Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
If a condition is missing (e.g., <cond> when the 'if <cond>' is removed from
'default A if <cond>'), it is actually Kconfig.y. The standard __str__()
functions just avoid printing 'if y' conditions to give cleaner output.
Kconfig extensions
==================
Kconfiglib includes a couple of Kconfig extensions:
'source' with relative path
---------------------------
The 'rsource' statement sources Kconfig files with a path relative to directory
of the Kconfig file containing the 'rsource' statement, instead of relative to
the project root.
Consider following directory tree:
Project
+--Kconfig
|
+--src
+--Kconfig
|
+--SubSystem1
+--Kconfig
|
+--ModuleA
+--Kconfig
In this example, assume that src/SubSystem1/Kconfig wants to source
src/SubSystem1/ModuleA/Kconfig.
With 'source', this statement would be used:
source "src/SubSystem1/ModuleA/Kconfig"
With 'rsource', this turns into
rsource "ModuleA/Kconfig"
If an absolute path is given to 'rsource', it acts the same as 'source'.
'rsource' can be used to create "position-independent" Kconfig trees that can
be moved around freely.
Globbing 'source'
-----------------
'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
files. They require at least one matching file, throwing a KconfigError
otherwise.
For example, the following statement might source sub1/foofoofoo and
sub2/foobarfoo:
source "sub[12]/foo*foo"
The glob patterns accepted are the same as for the standard glob.glob()
function.
Two additional statements are provided for cases where it's acceptable for a
pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
For example, the following statements will be no-ops if neither "foo" nor any
files matching "bar*" exist:
osource "foo"
osource "bar*"
'orsource' does a relative optional source.
'source' and 'osource' are analogous to 'include' and '-include' in Make.
Generalized def_* keywords
--------------------------
def_int, def_hex, and def_string are available in addition to def_bool and
def_tristate, allowing int, hex, and string symbols to be given a type and a
default at the same time.
Extra optional warnings
-----------------------
Some optional warnings can be controlled via environment variables:
- KCONFIG_WARN_UNDEF: If set to 'y', warnings will be generated for all
references to undefined symbols within Kconfig files. The only gotcha is
that all hex literals must be prefixed with "0x" or "0X", to make it
possible to distinguish them from symbol references.
Some projects (e.g. the Linux kernel) use multiple Kconfig trees with many
shared Kconfig files, leading to some safe undefined symbol references.
KCONFIG_WARN_UNDEF is useful in projects that only have a single Kconfig
tree though.
KCONFIG_STRICT is an older alias for this environment variable, supported
for backwards compatibility.
- KCONFIG_WARN_UNDEF_ASSIGN: If set to 'y', warnings will be generated for
all assignments to undefined symbols within .config files. By default, no
such warnings are generated.
This warning can also be enabled/disabled via
Kconfig.enable/disable_undef_warnings().
Preprocessor user functions defined in Python
---------------------------------------------
Preprocessor functions can be defined in Python, which makes it simple to
integrate information from existing Python tools into Kconfig (e.g. to have
Kconfig symbols depend on hardware information stored in some other format).
Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
sys.path can be customized via PYTHONPATH, and includes the directory of the
module being run by default, as well as installation directories.
If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
module name to use instead of 'kconfigfunctions'.
The imported module is expected to define a dictionary named 'functions', with
the following format:
functions = {
"my-fn": (my_fn, <min.args>, <max.args>/None),
"my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
...
}
def my_fn(kconf, name, arg_1, arg_2, ...):
# kconf:
# Kconfig instance
#
# name:
# Name of the user-defined function ("my-fn"). Think argv[0].
#
# arg_1, arg_2, ...:
# Arguments passed to the function from Kconfig (strings)
#
# Returns a string to be substituted as the result of calling the
# function
...
def my_other_fn(kconf, name, arg_1, arg_2, ...):
...
...
<min.args> and <max.args> are the minimum and maximum number of arguments
expected by the function (excluding the implicit 'name' argument). If
<max.args> is None, there is no upper limit to the number of arguments. Passing
an invalid number of arguments will generate a KconfigError exception.
Once defined, user functions can be called from Kconfig in the same way as
other preprocessor functions:
config FOO
...
depends on $(my-fn,arg1,arg2)
If my_fn() returns "n", this will result in
config FOO
...
depends on n
Warning
*******
User-defined preprocessor functions are called as they're encountered at parse
time, before all Kconfig files have been processed, and before the menu tree
has been finalized. There are no guarantees that accessing Kconfig symbols or
the menu tree via the 'kconf' parameter will work, and it could potentially
lead to a crash. The 'kconf' parameter is provided for future extension (and
because the predefined functions take it anyway).
Preferably, user-defined functions should be stateless.
Feedback
========
Send bug reports, suggestions, and questions to ulfalizer a.t Google's email
service, or open a ticket on the GitHub page.
"""
import errno
import glob
import importlib
import os
import platform
import re
import subprocess
import sys
import textwrap
# File layout:
#
# Public classes
# Public functions
# Internal functions
# Public global constants
# Internal global constants
# Line length: 79 columns
#
# Public classes
#
class Kconfig(object):
"""
Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
symbols, choices, and menu nodes appearing in the configuration. Creating
any number of Kconfig objects (including for different architectures) is
safe. Kconfiglib doesn't keep any global state.
The following attributes are available. They should be treated as
read-only, and some are implemented through @property magic.
syms:
A dictionary with all symbols in the configuration, indexed by name. Also
includes all symbols that are referenced in expressions but never
defined, except for constant (quoted) symbols.
Undefined symbols can be recognized by Symbol.nodes being empty -- see
the 'Intro to the menu tree' section in the module docstring.
const_syms:
A dictionary like 'syms' for constant (quoted) symbols
named_choices:
A dictionary like 'syms' for named choices (choice FOO)
defined_syms:
A list with all defined symbols, in the same order as they appear in the
Kconfig files. Symbols defined in multiple locations appear multiple
times.
Note: You probably want to use 'unique_defined_syms' instead. This
attribute is mostly maintained for backwards compatibility.
unique_defined_syms:
A list like 'defined_syms', but with duplicates removed. Just the first
instance is kept for symbols defined in multiple locations. Kconfig order
is preserved otherwise.
Using this attribute instead of 'defined_syms' can save work, and
automatically gives reasonable behavior when writing configuration output
(symbols defined in multiple locations only generate output once, while
still preserving Kconfig order for readability).
choices:
A list with all choices, in the same order as they appear in the Kconfig
files.
Note: You probably want to use 'unique_choices' instead. This attribute
is mostly maintained for backwards compatibility.
unique_choices:
Analogous to 'unique_defined_syms', for choices. Named choices can have
multiple definition locations.
menus:
A list with all menus, in the same order as they appear in the Kconfig
files
comments:
A list with all comments, in the same order as they appear in the Kconfig
files
kconfig_filenames:
A list with the filenames of all Kconfig files included in the
configuration, relative to $srctree (or relative to the current directory
if $srctree isn't set).
The files are listed in the order they are source'd, starting with the
top-level Kconfig file. If a file is source'd multiple times, it will
appear multiple times. Use set() to get unique filenames.
Note: Using this for incremental builds is redundant. Kconfig.sync_deps()
already indirectly catches any file modifications that change the
configuration output.
env_vars:
A set() with the names of all environment variables referenced in the
Kconfig files.
Only environment variables referenced with the preprocessor $(FOO) syntax
will be registered. The older $FOO syntax is only supported for backwards
compatibility.
Also note that $(FOO) won't be registered unless the environment variable
$FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
preprocessor variable (which gives the empty string).
Another gotcha is that environment variables referenced in the values of
recursively expanded preprocessor variables (those defined with =) will
only be registered if the variable is actually used (expanded) somewhere.
The note from the 'kconfig_filenames' documentation applies here too.
n/m/y:
The predefined constant symbols n/m/y. Also available in const_syms.
modules:
The Symbol instance for the modules symbol. Currently hardcoded to
MODULES, which is backwards compatible. Kconfiglib will warn if
'option modules' is set on some other symbol. Tell me if you need proper
'option modules' support.
'modules' is never None. If the MODULES symbol is not explicitly defined,
its tri_value will be 0 (n), as expected.
A simple way to enable modules is to do 'kconf.modules.set_value(2)'
(provided the MODULES symbol is defined and visible). Modules are
disabled by default in the kernel Kconfig files as of writing, though
nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
defconfig_list:
The Symbol instance for the 'option defconfig_list' symbol, or None if no
defconfig_list symbol exists. The defconfig filename derived from this
symbol can be found in Kconfig.defconfig_filename.
defconfig_filename:
The filename given by the defconfig_list symbol. This is taken from the
first 'default' with a satisfied condition where the specified file
exists (can be opened for reading). If a defconfig file foo/defconfig is
not found and $srctree was set when the Kconfig was created,
$srctree/foo/defconfig is looked up as well.
'defconfig_filename' is None if either no defconfig_list symbol exists,
or if the defconfig_list symbol has no 'default' with a satisfied
condition that specifies a file that exists.
Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
scripts/kconfig/conf when running e.g. 'make defconfig'. This option
overrides the defconfig_list symbol, meaning defconfig_filename might not
always match what 'make defconfig' would use.
top_node:
The menu node (see the MenuNode class) of the implicit top-level menu.
Acts as the root of the menu tree.
mainmenu_text:
The prompt (title) of the top menu (top_node). Defaults to "Main menu".
Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
variables:
A dictionary with all preprocessor variables, indexed by name. See the
Variable class.
warnings:
A list of strings containing all warnings that have been generated. This
allows flexibility in how warnings are printed and processed.
See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
Kconfig.enable/disable_stderr_warnings() functions as well. Note that
warnings still get added to Kconfig.warnings when 'warn_to_stderr' is
True.
Just as for warnings printed to stderr, only optional warnings that are
enabled will get added to Kconfig.warnings. See the various
Kconfig.enable/disable_*_warnings() functions.
srctree:
The value of the $srctree environment variable when the configuration was
loaded, or the empty string if $srctree wasn't set. This gives nice
behavior with os.path.join(), which treats "" as the current directory,
without adding "./".
Kconfig files are looked up relative to $srctree (unless absolute paths
are used), and .config files are looked up relative to $srctree if they
are not found in the current directory. This is used to support
out-of-tree builds. The C tools use this environment variable in the same
way.
Changing $srctree after creating the Kconfig instance has no effect. Only
the value when the configuration is loaded matters. This avoids surprises
if multiple configurations are loaded with different values for $srctree.
config_prefix:
The value of the $CONFIG_ environment variable when the configuration was
loaded. This is the prefix used (and expected) on symbol names in .config
files and C headers. Defaults to "CONFIG_". Used in the same way in the C
tools.
Like for srctree, only the value of $CONFIG_ when the configuration is
loaded matters.
"""
__slots__ = (
"_encoding",
"_functions",
"_set_match",
"_unset_match",
"_warn_for_no_prompt",
"_warn_for_redun_assign",
"_warn_for_undef_assign",
"_warn_to_stderr",
"_warnings_enabled",
"choices",
"comments",
"config_prefix",
"const_syms",
"defconfig_list",
"defined_syms",
"env_vars",
"kconfig_filenames",
"m",
"mainmenu_text",
"menus",
"modules",
"n",
"named_choices",
"srctree",
"syms",
"top_node",
"unique_choices",
"unique_defined_syms",
"variables",
"warnings",
"y",
# Parsing-related
"_parsing_kconfigs",
"_file",
"_filename",
"_linenr",
"_include_path",
"_filestack",
"_line",
"_tokens",
"_tokens_i",
"_reuse_tokens",
)
#
# Public interface
#
def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
encoding="utf-8"):
"""
Creates a new Kconfig object by parsing Kconfig files.
Note that Kconfig files are not the same as .config files (which store
configuration symbol values).
See the module docstring for some environment variables that influence
default warning settings (KCONFIG_WARN_UNDEF and
KCONFIG_WARN_UNDEF_ASSIGN).
Raises KconfigError on syntax errors, and (possibly a subclass of)
IOError on IO errors ('errno', 'strerror', and 'filename' are
available). Note that IOError can be caught as OSError on Python 3.
filename (default: "Kconfig"):
The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
from the top-level directory, as environment variables will make sure
the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
writing).
If $srctree is set, 'filename' will be looked up relative to it.
$srctree is also used to look up source'd files within Kconfig files.
See the class documentation.
If you are using Kconfiglib via 'make scriptconfig', the filename of
the base base Kconfig file will be in sys.argv[1]. It's currently
always "Kconfig" in practice.
warn (default: True):
True if warnings related to this configuration should be generated.
This can be changed later with Kconfig.enable/disable_warnings(). It
is provided as a constructor argument since warnings might be
generated during parsing.
See the other Kconfig.enable_*_warnings() functions as well, which
enable or suppress certain warnings when warnings are enabled.
All generated warnings are added to the Kconfig.warnings list. See
the class documentation.
warn_to_stderr (default: True):
True if warnings should be printed to stderr in addition to being
added to Kconfig.warnings.
This can be changed later with
Kconfig.enable/disable_stderr_warnings().
encoding (default: "utf-8"):
The encoding to use when reading and writing files. If None, the
encoding specified in the current locale will be used.
The "utf-8" default avoids exceptions on systems that are configured
to use the C locale, which implies an ASCII encoding.
This parameter has no effect on Python 2, due to implementation
issues (regular strings turning into Unicode strings, which are
distinct in Python 2). Python 2 doesn't decode regular strings
anyway.
Related PEP: https://www.python.org/dev/peps/pep-0538/
"""
self.srctree = os.environ.get("srctree", "")
self.config_prefix = os.environ.get("CONFIG_", "CONFIG_")
# Regular expressions for parsing .config files
self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
self._unset_match = \
_re_match(r"# {}([^ ]+) is not set".format(self.config_prefix))
self.warnings = []
self._warnings_enabled = warn
self._warn_to_stderr = warn_to_stderr
self._warn_for_undef_assign = \
os.environ.get("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
self._warn_for_redun_assign = True
self._encoding = encoding
self.syms = {}
self.const_syms = {}
self.defined_syms = []
self.named_choices = {}
self.choices = []
self.menus = []
self.comments = []
for nmy in "n", "m", "y":
sym = Symbol()
sym.kconfig = self
sym.name = nmy
sym.is_constant = True
sym.orig_type = TRISTATE
sym._cached_tri_val = STR_TO_TRI[nmy]
self.const_syms[nmy] = sym
self.n = self.const_syms["n"]
self.m = self.const_syms["m"]
self.y = self.const_syms["y"]
# Make n/m/y well-formed symbols
for nmy in "n", "m", "y":
sym = self.const_syms[nmy]
sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
# Maps preprocessor variables names to Variable instances
self.variables = {}
# Predefined preprocessor functions, with min/max number of arguments
self._functions = {
"info": (_info_fn, 1, 1),
"error-if": (_error_if_fn, 2, 2),
"filename": (_filename_fn, 0, 0),
"lineno": (_lineno_fn, 0, 0),
"shell": (_shell_fn, 1, 1),
"warning-if": (_warning_if_fn, 2, 2),
}
# Add any user-defined preprocessor functions
try:
self._functions.update(
importlib.import_module(
os.environ.get("KCONFIG_FUNCTIONS", "kconfigfunctions")
).functions)
except ImportError:
pass
# This is used to determine whether previously unseen symbols should be
# registered. They shouldn't be if we parse expressions after parsing,
# as part of Kconfig.eval_string().
self._parsing_kconfigs = True
self.modules = self._lookup_sym("MODULES")
self.defconfig_list = None
self.top_node = MenuNode()
self.top_node.kconfig = self
self.top_node.item = MENU
self.top_node.is_menuconfig = True
self.top_node.visibility = self.y
self.top_node.prompt = ("Main menu", self.y)
self.top_node.parent = None
self.top_node.dep = self.y
self.top_node.filename = filename
self.top_node.linenr = 1
self.top_node.include_path = ()
# Parse the Kconfig files
# Not used internally. Provided as a convenience.
self.kconfig_filenames = [filename]
self.env_vars = set()
# Used to avoid retokenizing lines when we discover that they're not
# part of the construct currently being parsed. This is kinda like an
# unget operation.
self._reuse_tokens = False
# Keeps track of the location in the parent Kconfig files. Kconfig
# files usually source other Kconfig files. See _enter_file().
self._filestack = []
self._include_path = ()
# The current parsing location
self._filename = filename
self._linenr = 0
# Open the top-level Kconfig file
try:
self._file = self._open(os.path.join(self.srctree, filename), "r")
except IOError as e:
if self.srctree:
print(textwrap.fill(
_INIT_SRCTREE_NOTE.format(self.srctree), 80))
raise
try:
# Parse everything
self._parse_block(None, self.top_node, self.top_node)
except UnicodeDecodeError as e:
_decoding_error(e, self._filename)
# Close the top-level Kconfig file
self._file.close()
self.top_node.list = self.top_node.next
self.top_node.next = None
self._parsing_kconfigs = False
self.unique_defined_syms = _ordered_unique(self.defined_syms)
self.unique_choices = _ordered_unique(self.choices)
# Do various post-processing of the menu tree
self._finalize_tree(self.top_node, self.y)
# Do sanity checks. Some of these depend on everything being finalized.
self._check_sym_sanity()
self._check_choice_sanity()
# KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
# for backwards compatibility
if os.environ.get("KCONFIG_WARN_UNDEF") == "y" or \
os.environ.get("KCONFIG_STRICT") == "y":
self._check_undef_syms()
# Build Symbol._dependents for all symbols and choices
self._build_dep()
# Check for dependency loops
check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
for sym in self.unique_defined_syms:
check_dep_loop_sym(sym, False)
# Add extra dependencies from choices to choice symbols that get
# awkward during dependency loop detection
self._add_choice_deps()
self._warn_for_no_prompt = True
self.mainmenu_text = self.top_node.prompt[0]
@property
def defconfig_filename(self):
"""
See the class documentation.
"""
if self.defconfig_list:
for filename, cond in self.defconfig_list.defaults:
if expr_value(cond):
try:
with self._open_config(filename.str_value) as f:
return f.name
except IOError:
continue
return None
def load_config(self, filename, replace=True):
"""
Loads symbol values from a file in the .config format. Equivalent to
calling Symbol.set_value() to set each of the values.
"# CONFIG_FOO is not set" within a .config file sets the user value of
FOO to n. The C tools work the same way.
The Symbol.user_value attribute can be inspected afterwards to see what
value the symbol was assigned in the .config file (if any). The user
value might differ from Symbol.str/tri_value if there are unsatisfied
dependencies.
Raises (possibly a subclass of) IOError on IO errors ('errno',
'strerror', and 'filename' are available). Note that IOError can be
caught as OSError on Python 3.
filename:
The file to load. Respects $srctree if set (see the class
documentation).
replace (default: True):
True if all existing user values should be cleared before loading the
.config. Pass False to merge configurations.
"""
# Disable the warning about assigning to symbols without prompts. This
# is normal and expected within a .config file.
self._warn_for_no_prompt = False
# This stub only exists to make sure _warn_for_no_prompt gets reenabled
try:
self._load_config(filename, replace)
except UnicodeDecodeError as e:
_decoding_error(e, filename)
finally:
self._warn_for_no_prompt = True
def _load_config(self, filename, replace):
with self._open_config(filename) as f:
if replace:
# If we're replacing the configuration, keep track of which
# symbols and choices got set so that we can unset the rest
# later. This avoids invalidating everything and is faster.
# Another benefit is that invalidation must be rock solid for
# it to work, making it a good test.
for sym in self.unique_defined_syms:
sym._was_set = False
for choice in self.unique_choices:
choice._was_set = False
# Small optimizations
set_match = self._set_match
unset_match = self._unset_match
syms = self.syms
for linenr, line in enumerate(f, 1):
# The C tools ignore trailing whitespace
line = line.rstrip()
match = set_match(line)
if match:
name, val = match.groups()
if name not in syms:
self._warn_undef_assign_load(name, val, filename,
linenr)
continue
sym = syms[name]
if not sym.nodes:
self._warn_undef_assign_load(name, val, filename,
linenr)
continue
if sym.orig_type in (BOOL, TRISTATE):
# The C implementation only checks the first character
# to the right of '=', for whatever reason
if not ((sym.orig_type is BOOL and
val.startswith(("n", "y"))) or
(sym.orig_type is TRISTATE and
val.startswith(("n", "m", "y")))):
self._warn("'{}' is not a valid value for the {} "
"symbol {}. Assignment ignored."
.format(val, TYPE_TO_STR[sym.orig_type],
_name_and_loc(sym)),
filename, linenr)
continue
val = val[0]
if sym.choice and val != "n":
# During .config loading, we infer the mode of the
# choice from the kind of values that are assigned
# to the choice symbols
prev_mode = sym.choice.user_value
if prev_mode is not None and \
TRI_TO_STR[prev_mode] != val:
self._warn("both m and y assigned to symbols "
"within the same choice",
filename, linenr)
# Set the choice's mode
sym.choice.set_value(val)
elif sym.orig_type is STRING:
match = _conf_string_match(val)
if not match:
self._warn("malformed string literal in "
"assignment to {}. Assignment ignored."
.format(_name_and_loc(sym)),
filename, linenr)
continue
val = unescape(match.group(1))
else:
match = unset_match(line)
if not match:
# Print a warning for lines that match neither
# set_match() nor unset_match() and that are not blank
# lines or comments. 'line' has already been
# rstrip()'d, so blank lines show up as "" here.
if line and not line.lstrip().startswith("#"):
self._warn("ignoring malformed line '{}'"
.format(line),
filename, linenr)
continue
name = match.group(1)
if name not in syms:
self._warn_undef_assign_load(name, "n", filename,
linenr)
continue
sym = syms[name]
if sym.orig_type not in (BOOL, TRISTATE):
continue
val = "n"
# Done parsing the assignment. Set the value.
if sym._was_set:
# Use strings for bool/tristate user values in the warning
if sym.orig_type in (BOOL, TRISTATE):
display_user_val = TRI_TO_STR[sym.user_value]
else:
display_user_val = sym.user_value
warn_msg = '{} set more than once. Old value: "{}", new value: "{}".'.format(
_name_and_loc(sym), display_user_val, val
)
if display_user_val == val:
self._warn_redun_assign(warn_msg, filename, linenr)
else:
self._warn( warn_msg, filename, linenr)
sym.set_value(val)
if replace:
# If we're replacing the configuration, unset the symbols that
# didn't get set
for sym in self.unique_defined_syms:
if not sym._was_set:
sym.unset_value()
for choice in self.unique_choices:
if not choice._was_set:
choice.unset_value()
def write_autoconf(self, filename,
header="/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
r"""
Writes out symbol values as a C header file, matching the format used
by include/generated/autoconf.h in the kernel.
The ordering of the #defines matches the one generated by
write_config(). The order in the C implementation depends on the hash
table implementation as of writing, and so won't match.
filename:
Self-explanatory.
header (default: "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want it enclosed in '/* */' to make it a C comment,
and include a final terminating newline.
"""
with self._open(filename, "w") as f:
f.write(header)
for sym in self.unique_defined_syms:
# Note: _write_to_conf is determined when the value is
# calculated. This is a hidden function call due to
# property magic.
val = sym.str_value
if sym._write_to_conf:
if sym.orig_type in (BOOL, TRISTATE):
if val != "n":
f.write("#define {}{}{} 1\n"
.format(self.config_prefix, sym.name,
"_MODULE" if val == "m" else ""))
elif sym.orig_type is STRING:
f.write('#define {}{} "{}"\n'
.format(self.config_prefix, sym.name,
escape(val)))
elif sym.orig_type in (INT, HEX):
if sym.orig_type is HEX and \
not val.startswith(("0x", "0X")):
val = "0x" + val
f.write("#define {}{} {}\n"
.format(self.config_prefix, sym.name, val))
else:
_internal_error("Internal error while creating C "
'header: unknown type "{}".'
.format(sym.orig_type))
def write_config(self, filename,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including ordering.
Symbols appear in the same order in generated .config files as they do
in the Kconfig files. For symbols defined in multiple locations, a
single assignment is written out corresponding to the first location
where the symbol is defined.
See the 'Intro to symbol values' section in the module docstring to
understand which symbols get written out.
filename:
Self-explanatory.
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
"""
with self._open(filename, "w") as f:
f.write(header)
for node in self.node_iter(unique_syms=True):
item = node.item
if isinstance(item, Symbol):
f.write(item.config_string)
elif expr_value(node.dep) and \
((item is MENU and expr_value(node.visibility)) or
item is COMMENT):
f.write("\n#\n# {}\n#\n".format(node.prompt[0]))
def write_min_config(self, filename,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
"""
Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'make savedefconfig'.
The resulting configuration file is incomplete, but a complete
configuration can be derived from it by loading it. Minimal
configuration files can serve as a more manageable configuration format
compared to a "full" .config file, especially when configurations files
are merged or edited by hand.
filename:
Self-explanatory.
header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
Text that will be inserted verbatim at the beginning of the file. You
would usually want each line to start with '#' to make it a comment,
and include a final terminating newline.
"""
with self._open(filename, "w") as f:
f.write(header)
for sym in self.unique_defined_syms:
# Skip symbols that cannot be changed. Only check
# non-choice symbols, as selects don't affect choice
# symbols.
if not sym.choice and \
sym.visibility <= expr_value(sym.rev_dep):
continue
# Skip symbols whose value matches their default
if sym.str_value == sym._str_default():
continue
# Skip symbols that would be selected by default in a
# choice, unless the choice is optional or the symbol type
# isn't bool (it might be possible to set the choice mode
# to n or the symbol to m in those cases).
if sym.choice and \
not sym.choice.is_optional and \
sym.choice._get_selection_from_defaults() is sym and \
sym.orig_type is BOOL and \
sym.tri_value == 2:
continue
f.write(sym.config_string)
def sync_deps(self, path):
"""
Creates or updates a directory structure that can be used to avoid
doing a full rebuild whenever the configuration is changed, mirroring
include/config/ in the kernel.
This function is intended to be called during each build, before
compiling source files that depend on configuration symbols.
path:
Path to directory
sync_deps(path) does the following:
1. If the directory <path> does not exist, it is created.
2. If <path>/auto.conf exists, old symbol values are loaded from it,
which are then compared against the current symbol values. If a
symbol has changed value (would generate different output in
autoconf.h compared to before), the change is signaled by
touch'ing a file corresponding to the symbol.
The first time sync_deps() is run on a directory, <path>/auto.conf
won't exist, and no old symbol values will be available. This
logically has the same effect as updating the entire
configuration.
The path to a symbol's file is calculated from the symbol's name
by replacing all '_' with '/' and appending '.h'. For example, the
symbol FOO_BAR_BAZ gets the file <path>/foo/bar/baz.h, and FOO
gets the file <path>/foo.h.
This scheme matches the C tools. The point is to avoid having a
single directory with a huge number of files, which the underlying
filesystem might not handle well.
3. A new auto.conf with the current symbol values is written, to keep
track of them for the next build.
The last piece of the puzzle is knowing what symbols each source file
depends on. Knowing that, dependencies can be added from source files
to the files corresponding to the symbols they depends on. The source
file will then get recompiled (only) when the symbol value changes
(provided sync_deps() is run first during each build).
The tool in the kernel that extracts symbol dependencies from source
files is scripts/basic/fixdep.c. Missing symbol files also correspond
to "not changed", which fixdep deals with by using the $(wildcard) Make
function when adding symbol prerequisites to source files.
In case you need a different scheme for your project, the sync_deps()
implementation can be used as a template."""
if not os.path.exists(path):
os.mkdir(path, 0o755)
# This setup makes sure that at least the current working directory
# gets reset if things fail
prev_dir = os.getcwd()
try:
# cd'ing into the symbol file directory simplifies
# _sync_deps() and saves some work
os.chdir(path)
self._sync_deps()
finally:
os.chdir(prev_dir)
def _sync_deps(self):
# Load old values from auto.conf, if any
self._load_old_vals()
for sym in self.unique_defined_syms:
# Note: _write_to_conf is determined when the value is
# calculated. This is a hidden function call due to
# property magic.
val = sym.str_value
# Note: n tristate values do not get written to auto.conf and
# autoconf.h, making a missing symbol logically equivalent to n
if sym._write_to_conf:
if sym._old_val is None and \
sym.orig_type in (BOOL, TRISTATE) and \
val == "n":
# No old value (the symbol was missing or n), new value n.
# No change.
continue
if val == sym._old_val:
# New value matches old. No change.
continue
elif sym._old_val is None:
# The symbol wouldn't appear in autoconf.h (because
# _write_to_conf is false), and it wouldn't have appeared in
# autoconf.h previously either (because it didn't appear in
# auto.conf). No change.
continue
# 'sym' has a new value. Flag it.
sym_path = sym.name.lower().replace("_", os.sep) + ".h"
sym_path_dir = os.path.dirname(sym_path)
if sym_path_dir and not os.path.exists(sym_path_dir):
os.makedirs(sym_path_dir, 0o755)
# A kind of truncating touch, mirroring the C tools
os.close(os.open(
sym_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644))
# Remember the current values as the "new old" values.
#
# This call could go anywhere after the call to _load_old_vals(), but
# putting it last means _sync_deps() can be safely rerun if it fails
# before this point.
self._write_old_vals()
def _write_old_vals(self):
# Helper for writing auto.conf. Basically just a simplified
# write_config() that doesn't write any comments (including
# '# CONFIG_FOO is not set' comments). The format matches the C
# implementation, though the ordering is arbitrary there (depends on
# the hash table implementation).
#
# A separate helper function is neater than complicating write_config()
# by passing a flag to it, plus we only need to look at symbols here.
with self._open("auto.conf", "w") as f:
for sym in self.unique_defined_syms:
if not (sym.orig_type in (BOOL, TRISTATE) and
not sym.tri_value):
f.write(sym.config_string)
def _load_old_vals(self):
# Loads old symbol values from auto.conf into a dedicated
# Symbol._old_val field. Mirrors load_config().
#
# The extra field could be avoided with some trickery involving dumping
# symbol values and restoring them later, but this is simpler and
# faster. The C tools also use a dedicated field for this purpose.
for sym in self.unique_defined_syms:
sym._old_val = None
if not os.path.exists("auto.conf"):
# No old values
return
with self._open("auto.conf", "r") as f:
for line in f:
match = self._set_match(line)
if not match:
# We only expect CONFIG_FOO=... (and possibly a header
# comment) in auto.conf
continue
name, val = match.groups()
if name in self.syms:
sym = self.syms[name]
if sym.orig_type is STRING:
match = _conf_string_match(val)
if not match:
continue
val = unescape(match.group(1))
self.syms[name]._old_val = val
def node_iter(self, unique_syms=False):
"""
Returns a generator for iterating through all MenuNode's in the Kconfig
tree. The iteration is done in Kconfig definition order (each node is
visited before its children, and the children of a node are visited
before the next node).
The Kconfig.top_node menu node is skipped. It contains an implicit menu
that holds the top-level items.
As an example, the following code will produce a list equal to
Kconfig.defined_syms:
defined_syms = [node.item for node in kconf.node_iter()
if isinstance(node.item, Symbol)]
unique_syms (default: False):
If True, only the first MenuNode will be included for symbols defined
in multiple locations.
Using kconf.node_iter(True) in the example above would give a list
equal to unique_defined_syms.
"""
if unique_syms:
for sym in self.unique_defined_syms:
sym._visited = False
node = self.top_node
while 1:
# Jump to the next node with an iterative tree walk
if node.list:
node = node.list
elif node.next:
node = node.next
else:
while node.parent:
node = node.parent
if node.next:
node = node.next
break
else:
# No more nodes
return
if unique_syms and isinstance(node.item, Symbol):
if node.item._visited:
continue
node.item._visited = True
yield node
def eval_string(self, s):
"""
Returns the tristate value of the expression 's', represented as 0, 1,
and 2 for n, m, and y, respectively. Raises KconfigError if syntax
errors are detected in 's'. Warns if undefined symbols are referenced.
As an example, if FOO and BAR are tristate symbols at least one of
which has the value y, then config.eval_string("y && (FOO || BAR)")
returns 2 (y).
To get the string value of non-bool/tristate symbols, use
Symbol.str_value. eval_string() always returns a tristate value, and
all non-bool/tristate symbols have the tristate value 0 (n).
The expression parsing is consistent with how parsing works for
conditional ('if ...') expressions in the configuration, and matches
the C implementation. m is rewritten to 'm && MODULES', so
eval_string("m") will return 0 (n) unless modules are enabled.
"""
# The parser is optimized to be fast when parsing Kconfig files (where
# an expression can never appear at the beginning of a line). We have
# to monkey-patch things a bit here to reuse it.
self._filename = None
# Don't include the "if " from below to avoid giving confusing error
# messages
self._line = s
# [1:] removes the _T_IF token
self._tokens = self._tokenize("if " + s)[1:]
self._tokens_i = -1
return expr_value(self._expect_expr_and_eol()) # transform_m
def unset_values(self):
"""
Resets the user values of all symbols, as if Kconfig.load_config() or
Symbol.set_value() had never been called.
"""
self._warn_for_no_prompt = False
try:
# set_value() already rejects undefined symbols, and they don't
# need to be invalidated (because their value never changes), so we
# can just iterate over defined symbols
for sym in self.unique_defined_syms:
sym.unset_value()
for choice in self.unique_choices:
choice.unset_value()
finally:
self._warn_for_no_prompt = True
def enable_warnings(self):
"""
See Kconfig.__init__().
"""
self._warnings_enabled = True
def disable_warnings(self):
"""
See Kconfig.__init__().
"""
self._warnings_enabled = False
def enable_stderr_warnings(self):
"""
See Kconfig.__init__().
"""
self._warn_to_stderr = True
def disable_stderr_warnings(self):
"""
See Kconfig.__init__().
"""
self._warn_to_stderr = False
def enable_undef_warnings(self):
"""
Enables warnings for assignments to undefined symbols. Disabled by
default unless the KCONFIG_WARN_UNDEF_ASSIGN environment variable was
set to 'y' when the Kconfig instance was created.
"""
self._warn_for_undef_assign = True
def disable_undef_warnings(self):
"""
See enable_undef_assign().
"""
self._warn_for_undef_assign = False
def enable_redun_warnings(self):
"""
Enables warnings for duplicated assignments in .config files that all
set the same value.
These warnings are enabled by default. Disabling them might be helpful
in certain cases when merging configurations.
"""
self._warn_for_redun_assign = True
def disable_redun_warnings(self):
"""
See enable_redun_warnings().
"""
self._warn_for_redun_assign = False
def __repr__(self):
"""
Returns a string with information about the Kconfig object when it is
evaluated on e.g. the interactive Python prompt.
"""
return "<{}>".format(", ".join((
"configuration with {} symbols".format(len(self.syms)),
'main menu prompt "{}"'.format(self.mainmenu_text),
"srctree is current directory" if not self.srctree else
'srctree "{}"'.format(self.srctree),
'config symbol prefix "{}"'.format(self.config_prefix),
"warnings " +
("enabled" if self._warnings_enabled else "disabled"),
"printing of warnings to stderr " +
("enabled" if self._warn_to_stderr else "disabled"),
"undef. symbol assignment warnings " +
("enabled" if self._warn_for_undef_assign else "disabled"),
"redundant symbol assignment warnings " +
("enabled" if self._warn_for_redun_assign else "disabled")
)))
#
# Private methods
#
#
# File reading
#
def _open_config(self, filename):
# Opens a .config file. First tries to open 'filename', then
# '$srctree/filename' if $srctree was set when the configuration was
# loaded.
try:
return self._open(filename, "r")
except IOError as e:
# This will try opening the same file twice if $srctree is unset,
# but it's not a big deal
try:
return self._open(os.path.join(self.srctree, filename), "r")
except IOError as e2:
# This is needed for Python 3, because e2 is deleted after
# the try block:
#
# https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
e = e2
raise _KconfigIOError(e, "\n" + textwrap.fill(
"Could not open '{}' ({}: {}){}".format(
filename, errno.errorcode[e.errno], e.strerror,
self._srctree_hint()),
80))
def _enter_file(self, full_filename, rel_filename):
# Jumps to the beginning of a sourced Kconfig file, saving the previous
# position and file object.
#
# full_filename:
# Actual path to the file.
#
# rel_filename:
# File path with $srctree prefix stripped, stored in e.g.
# self._filename (which makes it indirectly show up in
# MenuNode.filename). Equals full_filename for absolute paths.
self.kconfig_filenames.append(rel_filename)
# The parent Kconfig files are represented as a list of
# (<include path>, <Python 'file' object for Kconfig file>) tuples.
#
# <include path> is immutable and holds a *tuple* of
# (<filename>, <linenr>) tuples, giving the locations of the 'source'
# statements in the parent Kconfig files. The current include path is
# also available in Kconfig._include_path.
#
# The point of this redundant setup is to allow Kconfig._include_path
# to be assigned directly to MenuNode.include_path without having to
# copy it, sharing it wherever possible.
# Save include path and 'file' object before entering the file
self._filestack.append((self._include_path, self._file))
# _include_path is a tuple, so this rebinds the variable instead of
# doing in-place modification
self._include_path += ((self._filename, self._linenr),)
# Check for recursive 'source'
for name, _ in self._include_path:
if name == rel_filename:
raise KconfigError(
"\n{}:{}: Recursive 'source' of '{}' detected. Check that "
"environment variables are set correctly.\n"
"Include path:\n{}"
.format(self._filename, self._linenr, rel_filename,
"\n".join("{}:{}".format(name, linenr)
for name, linenr in self._include_path)))
# Note: We already know that the file exists
try:
self._file = self._open(full_filename, "r")
except IOError as e:
raise _KconfigIOError(
e, "{}:{}: Could not open '{}' ({}: {})"
.format(self._filename, self._linenr, full_filename,
errno.errorcode[e.errno], e.strerror))
self._filename = rel_filename
self._linenr = 0
def _leave_file(self):
# Returns from a Kconfig file to the file that sourced it. See
# _enter_file().
self._file.close()
# Restore location from parent Kconfig file
self._filename, self._linenr = self._include_path[-1]
# Restore include path and 'file' object
self._include_path, self._file = self._filestack.pop()
def _next_line(self):
# Fetches and tokenizes the next line from the current Kconfig file.
# Returns False at EOF and True otherwise.
# We might already have tokens from parsing a line and discovering that
# it's part of a different construct
if self._reuse_tokens:
self._reuse_tokens = False
self._tokens_i = -1
return True
# Note: readline() returns '' over and over at EOF, which we rely on
# for help texts at the end of files (see _line_after_help())
self._line = self._file.readline()
if not self._line:
return False
self._linenr += 1
# Handle line joining
while self._line.endswith("\\\n"):
self._line = self._line[:-2] + self._file.readline()
self._linenr += 1
self._tokens = self._tokenize(self._line)
self._tokens_i = -1 # Token index (minus one)
return True
def _line_after_help(self, line):
# Tokenizes the line after a help text. This case is special in that
# the line has already been fetched (to discover that it isn't part of
# the help text).
#
# An earlier version used a _saved_line variable instead that was
# checked in _next_line(). This special-casing gets rid of it and makes
# _reuse_tokens alone sufficient to handle unget.
if line:
# Handle line joining
while line.endswith("\\\n"):
line = line[:-2] + self._file.readline()
self._linenr += 1
self._line = line
self._tokens = self._tokenize(line)
self._reuse_tokens = True
#
# Tokenization
#
def _lookup_sym(self, name):
# Fetches the symbol 'name' from the symbol table, creating and
# registering it if it does not exist. If '_parsing_kconfigs' is False,
# it means we're in eval_string(), and new symbols won't be registered.
if name in self.syms:
return self.syms[name]
sym = Symbol()
sym.kconfig = self
sym.name = name
sym.is_constant = False
sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
if self._parsing_kconfigs:
self.syms[name] = sym
else:
self._warn("no symbol {} in configuration".format(name))
return sym
def _lookup_const_sym(self, name):
# Like _lookup_sym(), for constant (quoted) symbols
if name in self.const_syms:
return self.const_syms[name]
sym = Symbol()
sym.kconfig = self
sym.name = name
sym.is_constant = True
sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
if self._parsing_kconfigs:
self.const_syms[name] = sym
return sym
def _tokenize(self, s):
# Parses 's', returning a None-terminated list of tokens. Registers any
# new symbols encountered with _lookup(_const)_sym().
#
# Tries to be reasonably speedy by processing chunks of text via
# regexes and string operations where possible. This is the biggest
# hotspot during parsing.
#
# Note: It might be possible to rewrite this to 'yield' tokens instead,
# working across multiple lines. The 'option env' lookback thing below
# complicates things though.
# Initial token on the line
match = _command_match(s)
if not match:
if s.isspace() or s.lstrip().startswith("#"):
return (None,)
self._parse_error("unknown token at start of line")
# Tricky implementation detail: While parsing a token, 'token' refers
# to the previous token. See _STRING_LEX for why this is needed.
token = _get_keyword(match.group(1))
if not token:
# Backwards compatibility with old versions of the C tools, which
# (accidentally) accepted stuff like "--help--" and "-help---".
# This was fixed in the C tools by commit c2264564 ("kconfig: warn
# of unhandled characters in Kconfig commands"), committed in July
# 2015, but it seems people still run Kconfiglib on older kernels.
if s.strip(" \t\n-") == "help":
return (_T_HELP, None)
# If the first token is not a keyword (and not a weird help token),
# we have a preprocessor variable assignment (or a bare macro on a
# line)
self._parse_assignment(s)
return (None,)
tokens = [token]
# The current index in the string being tokenized
i = match.end()
# Main tokenization loop (for tokens past the first one)
while i < len(s):
# Test for an identifier/keyword first. This is the most common
# case.
match = _id_keyword_match(s, i)
if match:
# We have an identifier or keyword
# Check what it is. lookup_sym() will take care of allocating
# new symbols for us the first time we see them. Note that
# 'token' still refers to the previous token.
name = match.group(1)
keyword = _get_keyword(name)
if keyword:
# It's a keyword
token = keyword
# Jump past it
i = match.end()
elif token not in _STRING_LEX:
# It's a non-const symbol, except we translate n, m, and y
# into the corresponding constant symbols, like the C
# implementation
if "$" in name:
# Macro expansion within symbol name
name, s, i = self._expand_name(s, i)
else:
i = match.end()
token = self.const_syms[name] \
if name in ("n", "m", "y") else \
self._lookup_sym(name)
else:
# It's a case of missing quotes. For example, the
# following is accepted:
#
# menu unquoted_title
#
# config A
# tristate unquoted_prompt
#
# endmenu
token = name
i = match.end()
else:
# Neither a keyword nor a non-const symbol
# We always strip whitespace after tokens, so it is safe to
# assume that s[i] is the start of a token here.
c = s[i]
if c in "\"'":
if "$" not in s and "\\" not in s:
# Fast path for lines without $ and \. Find the
# matching quote.
end_i = s.find(c, i + 1) + 1
if not end_i:
self._parse_error("unterminated string")
val = s[i + 1:end_i - 1]
i = end_i
else:
# Slow path
s, end_i = self._expand_str(s, i)
# os.path.expandvars() and the $UNAME_RELEASE replace()
# is a backwards compatibility hack, which should be
# reasonably safe as expandvars() leaves references to
# undefined env. vars. as is.
#
# The preprocessor functionality changed how
# environment variables are referenced, to $(FOO).
val = os.path.expandvars(
s[i + 1:end_i - 1].replace("$UNAME_RELEASE",
platform.uname()[2]))
i = end_i
# This is the only place where we don't survive with a
# single token of lookback: 'option env="FOO"' does not
# refer to a constant symbol named "FOO".
token = \
val if token in _STRING_LEX or tokens[0] is _T_OPTION \
else self._lookup_const_sym(val)
elif s.startswith("&&", i):
token = _T_AND
i += 2
elif s.startswith("||", i):
token = _T_OR
i += 2
elif c == "=":
token = _T_EQUAL
i += 1
elif s.startswith("!=", i):
token = _T_UNEQUAL
i += 2
elif c == "!":
token = _T_NOT
i += 1
elif c == "(":
token = _T_OPEN_PAREN
i += 1
elif c == ")":
token = _T_CLOSE_PAREN
i += 1
elif c == "#":
break
# Very rare
elif s.startswith("<=", i):
token = _T_LESS_EQUAL
i += 2
elif c == "<":
token = _T_LESS
i += 1
elif s.startswith(">=", i):
token = _T_GREATER_EQUAL
i += 2
elif c == ">":
token = _T_GREATER
i += 1
else:
self._parse_error("unknown tokens in line")
# Skip trailing whitespace
while i < len(s) and s[i].isspace():
i += 1
# Add the token
tokens.append(token)
# None-terminating the token list makes the token fetching functions
# simpler/faster
tokens.append(None)
return tokens
def _next_token(self):
self._tokens_i += 1
return self._tokens[self._tokens_i]
def _peek_token(self):
return self._tokens[self._tokens_i + 1]
# The functions below are just _next_token() and _parse_expr() with extra
# syntax checking. Inlining _next_token() and _peek_token() into them saves
# a few % of parsing time.
#
# See the 'Intro to expressions' section for what a constant symbol is.
def _expect_sym(self):
self._tokens_i += 1
token = self._tokens[self._tokens_i]
if not isinstance(token, Symbol):
self._parse_error("expected symbol")
return token
def _expect_nonconst_sym(self):
self._tokens_i += 1
token = self._tokens[self._tokens_i]
if not isinstance(token, Symbol) or token.is_constant:
self._parse_error("expected nonconstant symbol")
return token
def _expect_nonconst_sym_and_eol(self):
self._tokens_i += 1
token = self._tokens[self._tokens_i]
if not isinstance(token, Symbol) or token.is_constant:
self._parse_error("expected nonconstant symbol")
if self._tokens[self._tokens_i + 1] is not None:
self._parse_error("extra tokens at end of line")
return token
def _expect_str(self):
self._tokens_i += 1
token = self._tokens[self._tokens_i]
if not isinstance(token, str):
self._parse_error("expected string")
return token
def _expect_str_and_eol(self):
self._tokens_i += 1
token = self._tokens[self._tokens_i]
if not isinstance(token, str):
self._parse_error("expected string")
if self._tokens[self._tokens_i + 1] is not None:
self._parse_error("extra tokens at end of line")
return token
def _expect_expr_and_eol(self):
expr = self._parse_expr(True)
if self._peek_token() is not None:
self._parse_error("extra tokens at end of line")
return expr
def _check_token(self, token):
# If the next token is 'token', removes it and returns True
if self._tokens[self._tokens_i + 1] is token:
self._tokens_i += 1
return True
return False
#
# Preprocessor logic
#
def _parse_assignment(self, s):
# Parses a preprocessor variable assignment, registering the variable
# if it doesn't already exist. Also takes care of bare macros on lines
# (which are allowed, and can be useful for their side effects).
# Expand any macros in the left-hand side of the assignment (the
# variable name)
s = s.lstrip()
i = 0
while 1:
i = _assignment_lhs_fragment_match(s, i).end()
if s.startswith("$(", i):
s, i = self._expand_macro(s, i, ())
else:
break
if s.isspace():
# We also accept a bare macro on a line (e.g.
# $(warning-if,$(foo),ops)), provided it expands to a blank string
return
# Assigned variable
name = s[:i]
# Extract assignment operator (=, :=, or +=) and value
rhs_match = _assignment_rhs_match(s, i)
if not rhs_match:
self._parse_error("syntax error")
op, val = rhs_match.groups()
if name in self.variables:
# Already seen variable
var = self.variables[name]
else:
# New variable
var = Variable()
var.kconfig = self
var.name = name
var._n_expansions = 0
self.variables[name] = var
# += acts like = on undefined variables (defines a recursive
# variable)
if op == "+=":
op = "="
if op == "=":
var.is_recursive = True
var.value = val
elif op == ":=":
var.is_recursive = False
var.value = self._expand_whole(val, ())
else: # op == "+="
# += does immediate expansion if the variable was last set
# with :=
var.value += " " + (val if var.is_recursive else
self._expand_whole(val, ()))
def _expand_whole(self, s, args):
# Expands preprocessor macros in all of 's'. Used whenever we don't
# have to worry about delimiters. See _expand_macro() re. the 'args'
# parameter.
#
# Returns the expanded string.
i = 0
while 1:
i = s.find("$(", i)
if i == -1:
break
s, i = self._expand_macro(s, i, args)
return s
def _expand_name(self, s, i):
# Expands a symbol name starting at index 'i' in 's'.
#
# Returns the expanded name, the expanded 's' (including the part
# before the name), and the index of the first character in the next
# token after the name.
s, end_i = self._expand_name_iter(s, i)
name = s[i:end_i]
# isspace() is False for empty strings
if not name.strip():
# Avoid creating a Kconfig symbol with a blank name. It's almost
# guaranteed to be an error.
self._parse_error("macro expanded to blank string")
# Skip trailing whitespace
while end_i < len(s) and s[end_i].isspace():
end_i += 1
return name, s, end_i
def _expand_name_iter(self, s, i):
# Expands a symbol name starting at index 'i' in 's'.
#
# Returns the expanded 's' (including the part before the name) and the
# index of the first character after the expanded name in 's'.
while 1:
match = _name_special_search(s, i)
if match.group() == "$(":
s, i = self._expand_macro(s, match.start(), ())
else:
return (s, match.start())
def _expand_str(self, s, i):
# Expands a quoted string starting at index 'i' in 's'. Handles both
# backslash escapes and macro expansion.
#
# Returns the expanded 's' (including the part before the string) and
# the index of the first character after the expanded string in 's'.
quote = s[i]
i += 1 # Skip over initial "/'
while 1:
match = _string_special_search(s, i)
if not match:
self._parse_error("unterminated string")
if match.group() == quote:
# Found the end of the string
return (s, match.end())
elif match.group() == "\\":
# Replace '\x' with 'x'. 'i' ends up pointing to the character
# after 'x', which allows macros to be canceled with '\$(foo)'.
i = match.end()
s = s[:match.start()] + s[i:]
elif match.group() == "$(":
# A macro call within the string
s, i = self._expand_macro(s, match.start(), ())
else:
# A ' quote within " quotes or vice versa
i += 1
def _expand_macro(self, s, i, args):
# Expands a macro starting at index 'i' in 's'. If this macro resulted
# from the expansion of another macro, 'args' holds the arguments
# passed to that macro.
#
# Returns the expanded 's' (including the part before the macro) and
# the index of the first character after the expanded macro in 's'.
start = i
i += 2 # Skip over "$("
# Start of current macro argument
arg_start = i
# Arguments of this macro call
new_args = []
while 1:
match = _macro_special_search(s, i)
if not match:
self._parse_error("missing end parenthesis in macro expansion")
if match.group() == ")":
# Found the end of the macro
new_args.append(s[arg_start:match.start()])
prefix = s[:start]
# $(1) is replaced by the first argument to the function, etc.,
# provided at least that many arguments were passed
try:
# Does the macro look like an integer, with a corresponding
# argument? If so, expand it to the value of the argument.
prefix += args[int(new_args[0])]
except (ValueError, IndexError):
# Regular variables are just functions without arguments,
# and also go through the function value path
prefix += self._fn_val(new_args)
return (prefix + s[match.end():],
len(prefix))
elif match.group() == ",":
# Found the end of a macro argument
new_args.append(s[arg_start:match.start()])
arg_start = i = match.end()
else: # match.group() == "$("
# A nested macro call within the macro
s, i = self._expand_macro(s, match.start(), args)
def _fn_val(self, args):
# Returns the result of calling the function args[0] with the arguments
# args[1..len(args)-1]. Plain variables are treated as functions
# without arguments.
fn = args[0]
if fn in self.variables:
var = self.variables[fn]
if len(args) == 1:
# Plain variable
if var._n_expansions:
self._parse_error("Preprocessor variable {} recursively "
"references itself".format(var.name))
elif var._n_expansions > 100:
# Allow functions to call themselves, but guess that functions
# that are overly recursive are stuck
self._parse_error("Preprocessor function {} seems stuck "
"in infinite recursion".format(var.name))
var._n_expansions += 1
res = self._expand_whole(self.variables[fn].value, args)
var._n_expansions -= 1
return res
if fn in self._functions:
# Built-in or user-defined function
py_fn, min_arg, max_arg = self._functions[fn]
if len(args) - 1 < min_arg or \
(max_arg is not None and len(args) - 1 > max_arg):
if min_arg == max_arg:
expected_args = min_arg
elif max_arg is None:
expected_args = "{} or more".format(min_arg)
else:
expected_args = "{}-{}".format(min_arg, max_arg)
raise KconfigError("{}:{}: bad number of arguments in call "
"to {}, expected {}, got {}"
.format(self._filename, self._linenr, fn,
expected_args, len(args) - 1))
return py_fn(self, *args)
# Environment variables are tried last
if fn in os.environ:
self.env_vars.add(fn)
return os.environ[fn]
return ""
#
# Parsing
#
def _make_and(self, e1, e2):
# Constructs an AND (&&) expression. Performs trivial simplification.
if e1 is self.y:
return e2
if e2 is self.y:
return e1
if e1 is self.n or e2 is self.n:
return self.n
return (AND, e1, e2)
def _make_or(self, e1, e2):
# Constructs an OR (||) expression. Performs trivial simplification.
if e1 is self.n:
return e2
if e2 is self.n:
return e1
if e1 is self.y or e2 is self.y:
return self.y
return (OR, e1, e2)
def _parse_block(self, end_token, parent, prev):
# Parses a block, which is the contents of either a file or an if,
# menu, or choice statement.
#
# end_token:
# The token that ends the block, e.g. _T_ENDIF ("endif") for ifs.
# None for files.
#
# parent:
# The parent menu node, corresponding to a menu, Choice, or 'if'.
# 'if's are flattened after parsing.
#
# prev:
# The previous menu node. New nodes will be added after this one (by
# modifying their 'next' pointer).
#
# 'prev' is reused to parse a list of child menu nodes (for a menu or
# Choice): After parsing the children, the 'next' pointer is assigned
# to the 'list' pointer to "tilt up" the children above the node.
#
# Returns the final menu node in the block (or 'prev' if the block is
# empty). This allows chaining.
while self._next_line():
t0 = self._next_token()
if t0 in (_T_CONFIG, _T_MENUCONFIG):
# The tokenizer allocates Symbol objects for us
sym = self._expect_nonconst_sym_and_eol()
self.defined_syms.append(sym)
node = MenuNode()
node.kconfig = self
node.item = sym
node.is_menuconfig = (t0 is _T_MENUCONFIG)
node.prompt = node.help = node.list = None
node.parent = parent
node.filename = self._filename
node.linenr = self._linenr
node.include_path = self._include_path
sym.nodes.append(node)
self._parse_properties(node)
if node.is_menuconfig and not node.prompt:
self._warn("the menuconfig symbol {} has no prompt"
.format(_name_and_loc(sym)))
# Equivalent to
#
# prev.next = node
# prev = node
#
# due to tricky Python semantics. The order matters.
prev.next = prev = node
elif t0 is None:
# Blank line
continue
elif t0 in (_T_SOURCE, _T_RSOURCE, _T_OSOURCE, _T_ORSOURCE):
pattern = self._expect_str_and_eol()
# Check if the pattern is absolute and avoid stripping srctree
# from it below in that case. We must do the check before
# join()'ing, as srctree might be an absolute path.
isabs = os.path.isabs(pattern)
if t0 in (_T_RSOURCE, _T_ORSOURCE):
# Relative source
pattern = os.path.join(os.path.dirname(self._filename),
pattern)
# Sort the glob results to ensure a consistent ordering of
# Kconfig symbols, which indirectly ensures a consistent
# ordering in e.g. .config files
filenames = \
sorted(glob.iglob(os.path.join(self.srctree, pattern)))
if not filenames and t0 in (_T_SOURCE, _T_RSOURCE):
raise KconfigError("\n" + textwrap.fill(
"{}:{}: '{}' does not exist{}".format(
self._filename, self._linenr, pattern,
self._srctree_hint()),
80))
for filename in filenames:
self._enter_file(
filename,
# Unless an absolute path is passed to *source, strip
# the $srctree prefix from the filename. That way it
# appears without a $srctree prefix in
# MenuNode.filename, which is nice e.g. when generating
# documentation.
filename if isabs else
os.path.relpath(filename, self.srctree))
prev = self._parse_block(None, parent, prev)
self._leave_file()
elif t0 is end_token:
# We have reached the end of the block. Terminate the final
# node and return it.
prev.next = None
return prev
elif t0 is _T_IF:
node = MenuNode()
node.item = node.prompt = None
node.parent = parent
node.dep = self._expect_expr_and_eol()
self._parse_block(_T_ENDIF, node, node)
node.list = node.next
prev.next = prev = node
elif t0 is _T_MENU:
node = MenuNode()
node.kconfig = self
node.item = t0 # _T_MENU == MENU
node.is_menuconfig = True
node.prompt = (self._expect_str_and_eol(), self.y)
node.visibility = self.y
node.parent = parent
node.filename = self._filename
node.linenr = self._linenr
node.include_path = self._include_path
self.menus.append(node)
self._parse_properties(node)
self._parse_block(_T_ENDMENU, node, node)
node.list = node.next
prev.next = prev = node
elif t0 is _T_COMMENT:
node = MenuNode()
node.kconfig = self
node.item = t0 # _T_COMMENT == COMMENT
node.is_menuconfig = False
node.prompt = (self._expect_str_and_eol(), self.y)
node.list = None
node.parent = parent
node.filename = self._filename
node.linenr = self._linenr
node.include_path = self._include_path
self.comments.append(node)
self._parse_properties(node)
prev.next = prev = node
elif t0 is _T_CHOICE:
if self._peek_token() is None:
choice = Choice()
choice.direct_dep = self.n
else:
# Named choice
name = self._expect_str_and_eol()
choice = self.named_choices.get(name)
if not choice:
choice = Choice()
choice.name = name
choice.direct_dep = self.n
self.named_choices[name] = choice
self.choices.append(choice)
choice.kconfig = self
node = MenuNode()
node.kconfig = self
node.item = choice
node.is_menuconfig = True
node.prompt = node.help = None
node.parent = parent
node.filename = self._filename
node.linenr = self._linenr
node.include_path = self._include_path
choice.nodes.append(node)
self._parse_properties(node)
self._parse_block(_T_ENDCHOICE, node, node)
node.list = node.next
prev.next = prev = node
elif t0 is _T_MAINMENU:
self.top_node.prompt = (self._expect_str_and_eol(), self.y)
self.top_node.filename = self._filename
self.top_node.linenr = self._linenr
else:
# A valid endchoice/endif/endmenu is caught by the 'end_token'
# check above
self._parse_error(
"no corresponding 'choice'" if t0 is _T_ENDCHOICE else
"no corresponding 'if'" if t0 is _T_ENDIF else
"no corresponding 'menu'" if t0 is _T_ENDMENU else
"unrecognized construct")
# End of file reached. Terminate the final node and return it.
if end_token:
raise KconfigError("Unexpected end of file " + self._filename)
prev.next = None
return prev
def _parse_cond(self):
# Parses an optional 'if <expr>' construct and returns the parsed
# <expr>, or self.y if the next token is not _T_IF
return self._expect_expr_and_eol() if self._check_token(_T_IF) \
else self.y
def _parse_properties(self, node):
# Parses and adds properties to the MenuNode 'node' (type, 'prompt',
# 'default's, etc.) Properties are later copied up to symbols and
# choices in a separate pass after parsing, in e.g.
# _add_props_to_sym().
#
# An older version of this code added properties directly to symbols
# and choices instead of to their menu nodes (and handled dependency
# propagation simultaneously), but that loses information on where a
# property is added when a symbol or choice is defined in multiple
# locations. Some Kconfig configuration systems rely heavily on such
# symbols, and better docs can be generated by keeping track of where
# properties are added.
#
# node:
# The menu node we're parsing properties on
# Dependencies from 'depends on'. Will get propagated to the properties
# below.
node.dep = self.y
while self._next_line():
t0 = self._next_token()
if t0 in _TYPE_TOKENS:
self._set_type(node, _TOKEN_TO_TYPE[t0])
if self._peek_token() is not None:
self._parse_prompt(node)
elif t0 is _T_DEPENDS:
if not self._check_token(_T_ON):
self._parse_error('expected "on" after "depends"')
node.dep = self._make_and(node.dep,
self._expect_expr_and_eol())
elif t0 is _T_HELP:
self._parse_help(node)
elif t0 is _T_SELECT:
if not isinstance(node.item, Symbol):
self._parse_error("only symbols can select")
node.selects.append((self._expect_nonconst_sym(),
self._parse_cond()))
elif t0 is None:
# Blank line
continue
elif t0 is _T_DEFAULT:
node.defaults.append((self._parse_expr(False),
self._parse_cond()))
elif t0 in (_T_DEF_BOOL, _T_DEF_TRISTATE, _T_DEF_INT, _T_DEF_HEX,
_T_DEF_STRING):
self._set_type(node, _TOKEN_TO_TYPE[t0])
node.defaults.append((self._parse_expr(False),
self._parse_cond()))
elif t0 is _T_PROMPT:
self._parse_prompt(node)
elif t0 is _T_RANGE:
node.ranges.append((self._expect_sym(),
self._expect_sym(),
self._parse_cond()))
elif t0 is _T_IMPLY:
if not isinstance(node.item, Symbol):
self._parse_error("only symbols can imply")
node.implies.append((self._expect_nonconst_sym(),
self._parse_cond()))
elif t0 is _T_VISIBLE:
if not self._check_token(_T_IF):
self._parse_error('expected "if" after "visible"')
node.visibility = self._make_and(node.visibility,
self._expect_expr_and_eol())
elif t0 is _T_OPTION:
if self._check_token(_T_ENV):
if not self._check_token(_T_EQUAL):
self._parse_error('expected "=" after "env"')
env_var = self._expect_str_and_eol()
node.item.env_var = env_var
if env_var in os.environ:
node.defaults.append(
(self._lookup_const_sym(os.environ[env_var]),
self.y))
else:
self._warn("{1} has 'option env=\"{0}\"', "
"but the environment variable {0} is not "
"set".format(node.item.name, env_var),
self._filename, self._linenr)
if env_var != node.item.name:
self._warn("Kconfiglib expands environment variables "
"in strings directly, meaning you do not "
"need 'option env=...' \"bounce\" symbols. "
"For compatibility with the C tools, "
"rename {} to {} (so that the symbol name "
"matches the environment variable name)."
.format(node.item.name, env_var),
self._filename, self._linenr)
elif self._check_token(_T_DEFCONFIG_LIST):
if not self.defconfig_list:
self.defconfig_list = node.item
else:
self._warn("'option defconfig_list' set on multiple "
"symbols ({0} and {1}). Only {0} will be "
"used.".format(self.defconfig_list.name,
node.item.name),
self._filename, self._linenr)
elif self._check_token(_T_MODULES):
# To reduce warning spam, only warn if 'option modules' is
# set on some symbol that isn't MODULES, which should be
# safe. I haven't run into any projects that make use
# modules besides the kernel yet, and there it's likely to
# keep being called "MODULES".
if node.item is not self.modules:
self._warn("the 'modules' option is not supported. "
"Let me know if this is a problem for you, "
"as it wouldn't be that hard to implement. "
"Note that modules are supported -- "
"Kconfiglib just assumes the symbol name "
"MODULES, like older versions of the C "
"implementation did when 'option modules' "
"wasn't used.",
self._filename, self._linenr)
elif self._check_token(_T_ALLNOCONFIG_Y):
if not isinstance(node.item, Symbol):
self._parse_error("the 'allnoconfig_y' option is only "
"valid for symbols")
node.item.is_allnoconfig_y = True
else:
self._parse_error("unrecognized option")
elif t0 is _T_OPTIONAL:
if not isinstance(node.item, Choice):
self._parse_error('"optional" is only valid for choices')
node.item.is_optional = True
else:
# Reuse the tokens for the non-property line later
self._reuse_tokens = True
return
def _set_type(self, node, new_type):
if node.item.orig_type not in (UNKNOWN, new_type):
self._warn("{} defined with multiple types, {} will be used"
.format(_name_and_loc(node.item),
TYPE_TO_STR[new_type]))
node.item.orig_type = new_type
def _parse_prompt(self, node):
# 'prompt' properties override each other within a single definition of
# a symbol, but additional prompts can be added by defining the symbol
# multiple times
if node.prompt:
self._warn(_name_and_loc(node.item) +
" defined with multiple prompts in single location")
prompt = self._expect_str()
if prompt != prompt.strip():
self._warn(_name_and_loc(node.item) +
" has leading or trailing whitespace in its prompt")
# This avoid issues for e.g. reStructuredText documentation, where
# '*prompt *' is invalid
prompt = prompt.strip()
node.prompt = (prompt, self._parse_cond())
def _parse_help(self, node):
# Find first non-blank (not all-space) line and get its indentation
if node.help is not None:
self._warn(_name_and_loc(node.item) +
" defined with more than one help text -- only the "
"last one will be used")
# Small optimization. This code is pretty hot.
readline = self._file.readline
while 1:
line = readline()
self._linenr += 1
if not line or not line.isspace():
break
if not line:
self._warn(_name_and_loc(node.item) +
" has 'help' but empty help text")
node.help = ""
return
indent = _indentation(line)
if not indent:
# If the first non-empty lines has zero indent, there is no help
# text
self._warn(_name_and_loc(node.item) +
" has 'help' but empty help text")
node.help = ""
self._line_after_help(line)
return
# The help text goes on till the first non-empty line with less indent
# than the first line
help_lines = []
# Small optimizations
add_help_line = help_lines.append
indentation = _indentation
while line and (line.isspace() or indentation(line) >= indent):
# De-indent 'line' by 'indent' spaces and rstrip() it to remove any
# newlines (which gets rid of other trailing whitespace too, but
# that's fine).
#
# This prepares help text lines in a speedy way: The [indent:]
# might already remove trailing newlines for lines shorter than
# indent (e.g. empty lines). The rstrip() makes it consistent,
# meaning we can join the lines with "\n" later.
add_help_line(line.expandtabs()[indent:].rstrip())
line = readline()
self._linenr += len(help_lines)
node.help = "\n".join(help_lines).rstrip()
self._line_after_help(line)
def _parse_expr(self, transform_m):
# Parses an expression from the tokens in Kconfig._tokens using a
# simple top-down approach. See the module docstring for the expression
# format.
#
# transform_m:
# True if m should be rewritten to m && MODULES. See the
# Kconfig.eval_string() documentation.
# Grammar:
#
# expr: and_expr ['||' expr]
# and_expr: factor ['&&' and_expr]
# factor: <symbol> ['='/'!='/'<'/... <symbol>]
# '!' factor
# '(' expr ')'
#
# It helps to think of the 'expr: and_expr' case as a single-operand OR
# (no ||), and of the 'and_expr: factor' case as a single-operand AND
# (no &&). Parsing code is always a bit tricky.
# Mind dump: parse_factor() and two nested loops for OR and AND would
# work as well. The straightforward implementation there gives a
# (op, (op, (op, A, B), C), D) parse for A op B op C op D. Representing
# expressions as (op, [list of operands]) instead goes nicely with that
# version, but is wasteful for short expressions and complicates
# expression evaluation and other code that works on expressions (more
# complicated code likely offsets any performance gain from less
# recursion too). If we also try to optimize the list representation by
# merging lists when possible (e.g. when ANDing two AND expressions),
# we end up allocating a ton of lists instead of reusing expressions,
# which is bad.
and_expr = self._parse_and_expr(transform_m)
# Return 'and_expr' directly if we have a "single-operand" OR.
# Otherwise, parse the expression on the right and make an OR node.
# This turns A || B || C || D into (OR, A, (OR, B, (OR, C, D))).
return and_expr \
if not self._check_token(_T_OR) else \
(OR, and_expr, self._parse_expr(transform_m))
def _parse_and_expr(self, transform_m):
factor = self._parse_factor(transform_m)
# Return 'factor' directly if we have a "single-operand" AND.
# Otherwise, parse the right operand and make an AND node. This turns
# A && B && C && D into (AND, A, (AND, B, (AND, C, D))).
return factor \
if not self._check_token(_T_AND) else \
(AND, factor, self._parse_and_expr(transform_m))
def _parse_factor(self, transform_m):
token = self._next_token()
if isinstance(token, Symbol):
# Plain symbol or relation
if self._peek_token() not in _RELATIONS:
# Plain symbol
# For conditional expressions ('depends on <expr>',
# '... if <expr>', etc.), m is rewritten to m && MODULES.
if transform_m and token is self.m:
return (AND, self.m, self.modules)
return token
# Relation
#
# _T_EQUAL, _T_UNEQUAL, etc., deliberately have the same values as
# EQUAL, UNEQUAL, etc., so we can just use the token directly
return (self._next_token(), token, self._expect_sym())
if token is _T_NOT:
# token == _T_NOT == NOT
return (token, self._parse_factor(transform_m))
if token is _T_OPEN_PAREN:
expr_parse = self._parse_expr(transform_m)
if self._check_token(_T_CLOSE_PAREN):
return expr_parse
self._parse_error("malformed expression")
#
# Caching and invalidation
#
def _build_dep(self):
# Populates the Symbol/Choice._dependents sets, which contain all other
# items (symbols and choices) that immediately depend on the item in
# the sense that changing the value of the item might affect the value
# of the dependent items. This is used for caching/invalidation.
#
# The calculated sets might be larger than necessary as we don't do any
# complex analysis of the expressions.
make_depend_on = _make_depend_on # Micro-optimization
# Only calculate _dependents for defined symbols. Constant and
# undefined symbols could theoretically be selected/implied, but it
# wouldn't change their value, so it's not a true dependency.
for sym in self.unique_defined_syms:
# Symbols depend on the following:
# The prompt conditions
for node in sym.nodes:
if node.prompt:
make_depend_on(sym, node.prompt[1])
# The default values and their conditions
for value, cond in sym.defaults:
make_depend_on(sym, value)
make_depend_on(sym, cond)
# The reverse and weak reverse dependencies
make_depend_on(sym, sym.rev_dep)
make_depend_on(sym, sym.weak_rev_dep)
# The ranges along with their conditions
for low, high, cond in sym.ranges:
make_depend_on(sym, low)
make_depend_on(sym, high)
make_depend_on(sym, cond)
# The direct dependencies. This is usually redundant, as the direct
# dependencies get propagated to properties, but it's needed to get
# invalidation solid for 'imply', which only checks the direct
# dependencies (even if there are no properties to propagate it
# to).
make_depend_on(sym, sym.direct_dep)
# In addition to the above, choice symbols depend on the choice
# they're in, but that's handled automatically since the Choice is
# propagated to the conditions of the properties before
# _build_dep() runs.
for choice in self.unique_choices:
# Choices depend on the following:
# The prompt conditions
for node in choice.nodes:
if node.prompt:
make_depend_on(choice, node.prompt[1])
# The default symbol conditions
for _, cond in choice.defaults:
make_depend_on(choice, cond)
def _add_choice_deps(self):
# Choices also depend on the choice symbols themselves, because the
# y-mode selection of the choice might change if a choice symbol's
# visibility changes.
#
# We add these dependencies separately after dependency loop detection.
# The invalidation algorithm can handle the resulting
# <choice symbol> <-> <choice> dependency loops, but they make loop
# detection awkward.
for choice in self.unique_choices:
for sym in choice.syms:
sym._dependents.add(choice)
def _invalidate_all(self):
# Undefined symbols never change value and don't need to be
# invalidated, so we can just iterate over defined symbols.
# Invalidating constant symbols would break things horribly.
for sym in self.unique_defined_syms:
sym._invalidate()
for choice in self.unique_choices:
choice._invalidate()
#
# Post-parsing menu tree processing, including dependency propagation and
# implicit submenu creation
#
def _finalize_tree(self, node, visible_if):
# Propagates properties and dependencies, creates implicit menus (see
# kconfig-language.txt), removes 'if' nodes, and finalizes choices.
# This pretty closely mirrors menu_finalize() from the C
# implementation, with some minor tweaks (MenuNode holds lists of
# properties instead of each property having a MenuNode pointer, for
# example).
#
# node:
# The current "parent" menu node, from which we propagate
# dependencies
#
# visible_if:
# Dependencies from 'visible if' on parent menus. These are added to
# the prompts of symbols and choices.
if node.list:
# The menu node is a choice, menu, or if. Finalize each child in
# it.
if node.item is MENU:
visible_if = self._make_and(visible_if, node.visibility)
# Propagate the menu node's dependencies to each child menu node.
#
# The recursive _finalize_tree() calls assume that the current
# "level" in the tree has already had dependencies propagated. This
# makes e.g. implicit submenu creation easier, because it needs to
# look ahead.
self._propagate_deps(node, visible_if)
# Finalize the children
cur = node.list
while cur:
self._finalize_tree(cur, visible_if)
cur = cur.next
elif isinstance(node.item, Symbol):
# Add the node's non-node-specific properties (defaults, ranges,
# etc.) to the Symbol
self._add_props_to_sym(node)
# See if we can create an implicit menu rooted at the Symbol and
# finalize each child menu node in that menu if so, like for the
# choice/menu/if case above
cur = node
while cur.next and _auto_menu_dep(node, cur.next):
# This also makes implicit submenu creation work recursively,
# with implicit menus inside implicit menus
self._finalize_tree(cur.next, visible_if)
cur = cur.next
cur.parent = node
if cur is not node:
# Found symbols that should go in an implicit submenu. Tilt
# them up above us.
node.list = node.next
node.next = cur.next
cur.next = None
if node.list:
# We have a parent node with individually finalized child nodes. Do
# final steps to finalize this "level" in the menu tree.
_flatten(node.list)
_remove_ifs(node)
# Empty choices (node.list None) are possible, so this needs to go
# outside
if isinstance(node.item, Choice):
# Add the node's non-node-specific properties to the choice, like
# _add_props_to_sym() does
choice = node.item
choice.direct_dep = self._make_or(choice.direct_dep, node.dep)
choice.defaults += node.defaults
_finalize_choice(node)
def _propagate_deps(self, node, visible_if):
# Propagates 'node's dependencies to its child menu nodes
# If the parent node holds a Choice, we use the Choice itself as the
# parent dependency. This makes sense as the value (mode) of the choice
# limits the visibility of the contained choice symbols. The C
# implementation works the same way.
#
# Due to the similar interface, Choice works as a drop-in replacement
# for Symbol here.
basedep = node.item if isinstance(node.item, Choice) else node.dep
cur = node.list
while cur:
cur.dep = dep = self._make_and(cur.dep, basedep)
# Propagate dependencies to prompt
if cur.prompt:
cur.prompt = (cur.prompt[0],
self._make_and(cur.prompt[1], dep))
if isinstance(cur.item, (Symbol, Choice)):
# Propagate 'visible if' dependencies to the prompt
if cur.prompt:
cur.prompt = (cur.prompt[0],
self._make_and(cur.prompt[1], visible_if))
# Propagate dependencies to defaults
if cur.defaults:
cur.defaults = [(default, self._make_and(cond, dep))
for default, cond in cur.defaults]
# Propagate dependencies to ranges
if cur.ranges:
cur.ranges = [(low, high, self._make_and(cond, dep))
for low, high, cond in cur.ranges]
# Propagate dependencies to selects
if cur.selects:
cur.selects = [(target, self._make_and(cond, dep))
for target, cond in cur.selects]
# Propagate dependencies to implies
if cur.implies:
cur.implies = [(target, self._make_and(cond, dep))
for target, cond in cur.implies]
cur = cur.next
def _add_props_to_sym(self, node):
# Copies properties from the menu node 'node' up to its contained
# symbol, and adds (weak) reverse dependencies to selected/implied
# symbols.
#
# This can't be rolled into _propagate_deps(), because that function
# traverses the menu tree roughly breadth-first, meaning properties on
# symbols defined in multiple locations could end up in the wrong
# order.
sym = node.item
# See the Symbol class docstring
sym.direct_dep = self._make_or(sym.direct_dep, node.dep)
sym.defaults += node.defaults
sym.ranges += node.ranges
sym.selects += node.selects
sym.implies += node.implies
# Modify the reverse dependencies of the selected symbol
for target, cond in node.selects:
target.rev_dep = self._make_or(
target.rev_dep,
self._make_and(sym, cond))
# Modify the weak reverse dependencies of the implied
# symbol
for target, cond in node.implies:
target.weak_rev_dep = self._make_or(
target.weak_rev_dep,
self._make_and(sym, cond))
#
# Misc.
#
def _check_sym_sanity(self):
# Checks various symbol properties that are handiest to check after
# parsing. Only generates errors and warnings.
def num_ok(sym, type_):
# Returns True if the (possibly constant) symbol 'sym' is valid as a value
# for a symbol of type type_ (INT or HEX)
# 'not sym.nodes' implies a constant or undefined symbol, e.g. a plain
# "123"
if not sym.nodes:
return _is_base_n(sym.name, _TYPE_TO_BASE[type_])
return sym.orig_type is type_
for sym in self.unique_defined_syms:
if sym.orig_type in (BOOL, TRISTATE):
# A helper function could be factored out here, but keep it
# speedy/straightforward
for target_sym, _ in sym.selects:
if target_sym.orig_type not in (BOOL, TRISTATE, UNKNOWN):
self._warn("{} selects the {} symbol {}, which is not "
"bool or tristate"
.format(_name_and_loc(sym),
TYPE_TO_STR[target_sym.orig_type],
_name_and_loc(target_sym)))
for target_sym, _ in sym.implies:
if target_sym.orig_type not in (BOOL, TRISTATE, UNKNOWN):
self._warn("{} implies the {} symbol {}, which is not "
"bool or tristate"
.format(_name_and_loc(sym),
TYPE_TO_STR[target_sym.orig_type],
_name_and_loc(target_sym)))
elif sym.orig_type in (STRING, INT, HEX):
for default, _ in sym.defaults:
if not isinstance(default, Symbol):
raise KconfigError(
"the {} symbol {} has a malformed default {} -- expected "
"a single symbol"
.format(TYPE_TO_STR[sym.orig_type], _name_and_loc(sym),
expr_str(default)))
if sym.orig_type is STRING:
if not default.is_constant and not default.nodes and \
not default.name.isupper():
# 'default foo' on a string symbol could be either a symbol
# reference or someone leaving out the quotes. Guess that
# the quotes were left out if 'foo' isn't all-uppercase
# (and no symbol named 'foo' exists).
self._warn("style: quotes recommended around "
"default value for string symbol "
+ _name_and_loc(sym))
elif sym.orig_type in (INT, HEX) and \
not num_ok(default, sym.orig_type):
self._warn("the {0} symbol {1} has a non-{0} default {2}"
.format(TYPE_TO_STR[sym.orig_type],
_name_and_loc(sym),
_name_and_loc(default)))
if sym.selects or sym.implies:
self._warn("the {} symbol {} has selects or implies"
.format(TYPE_TO_STR[sym.orig_type],
_name_and_loc(sym)))
else: # UNKNOWN
self._warn("{} defined without a type"
.format(_name_and_loc(sym)))
if sym.ranges:
if sym.orig_type not in (INT, HEX):
self._warn(
"the {} symbol {} has ranges, but is not int or hex"
.format(TYPE_TO_STR[sym.orig_type],
_name_and_loc(sym)))
else:
for low, high, _ in sym.ranges:
if not num_ok(low, sym.orig_type) or \
not num_ok(high, sym.orig_type):
self._warn("the {0} symbol {1} has a non-{0} "
"range [{2}, {3}]"
.format(TYPE_TO_STR[sym.orig_type],
_name_and_loc(sym),
_name_and_loc(low),
_name_and_loc(high)))
def _check_choice_sanity(self):
# Checks various choice properties that are handiest to check after
# parsing. Only generates errors and warnings.
def warn_select_imply(sym, expr, expr_type):
msg = "the choice symbol {} is {} by the following symbols, which " \
"has no effect: ".format(_name_and_loc(sym), expr_type)
# si = select/imply
for si in split_expr(expr, OR):
msg += "\n - " + _name_and_loc(split_expr(si, AND)[0])
self._warn(msg)
for choice in self.unique_choices:
if choice.orig_type not in (BOOL, TRISTATE):
self._warn("{} defined with type {}"
.format(_name_and_loc(choice),
TYPE_TO_STR[choice.orig_type]))
for node in choice.nodes:
if node.prompt:
break
else:
self._warn(_name_and_loc(choice) + " defined without a prompt")
for default, _ in choice.defaults:
if not isinstance(default, Symbol):
raise KconfigError(
"{} has a malformed default {}"
.format(_name_and_loc(choice), expr_str(default)))
if default.choice is not choice:
self._warn("the default selection {} of {} is not "
"contained in the choice"
.format(_name_and_loc(default),
_name_and_loc(choice)))
for sym in choice.syms:
if sym.defaults:
self._warn("default on the choice symbol {} will have "
"no effect, as defaults do not affect choice "
"symbols".format(_name_and_loc(sym)))
if sym.rev_dep is not sym.kconfig.n:
warn_select_imply(sym, sym.rev_dep, "selected")
if sym.weak_rev_dep is not sym.kconfig.n:
warn_select_imply(sym, sym.weak_rev_dep, "implied")
for node in sym.nodes:
if node.parent.item is choice:
if not node.prompt:
self._warn("the choice symbol {} has no prompt"
.format(_name_and_loc(sym)))
elif node.prompt:
self._warn("the choice symbol {} is defined with a "
"prompt outside the choice"
.format(_name_and_loc(sym)))
def _parse_error(self, msg):
if self._filename is None:
loc = ""
else:
loc = "{}:{}: ".format(self._filename, self._linenr)
raise KconfigError(
"{}couldn't parse '{}': {}".format(loc, self._line.rstrip(), msg))
def _open(self, filename, mode):
# open() wrapper:
#
# - Enable universal newlines mode on Python 2 to ease
# interoperability between Linux and Windows. It's already the
# default on Python 3.
#
# The "U" flag would currently work for both Python 2 and 3, but it's
# deprecated on Python 3, so play it future-safe.
#
# A simpler solution would be to use io.open(), which defaults to
# universal newlines on both Python 2 and 3 (and is an alias for
# open() on Python 3), but it's appreciably slower on Python 2:
#
# Parsing x86 Kconfigs on Python 2
#
# with open(..., "rU"):
#
# real 0m0.930s
# user 0m0.905s
# sys 0m0.025s
#
# with io.open():
#
# real 0m1.069s
# user 0m1.040s
# sys 0m0.029s
#
# There's no appreciable performance difference between "r" and
# "rU" for parsing performance on Python 2.
#
# - For Python 3, force the encoding. Forcing the encoding on Python 2
# turns strings into Unicode strings, which gets messy. Python 2
# doesn't decode regular strings anyway.
return open(filename, "rU" if mode == "r" else mode) if _IS_PY2 else \
open(filename, mode, encoding=self._encoding)
def _check_undef_syms(self):
# Prints warnings for all references to undefined symbols within the
# Kconfig files
def is_num(s):
# Returns True if the string 's' looks like a number.
#
# Internally, all operands in Kconfig are symbols, only undefined symbols
# (which numbers usually are) get their name as their value.
#
# Only hex numbers that start with 0x/0X are classified as numbers.
# Otherwise, symbols whose names happen to contain only the letters A-F
# would trigger false positives.
try:
int(s)
except ValueError:
if not s.startswith(("0x", "0X")):
return False
try:
int(s, 16)
except ValueError:
return False
return True
for sym in (self.syms.viewvalues if _IS_PY2 else self.syms.values)():
# - sym.nodes empty means the symbol is undefined (has no
# definition locations)
#
# - Due to Kconfig internals, numbers show up as undefined Kconfig
# symbols, but shouldn't be flagged
#
# - The MODULES symbol always exists
if not sym.nodes and not is_num(sym.name) and \
sym.name != "MODULES":
msg = "undefined symbol {}:".format(sym.name)
for node in self.node_iter():
if sym in node.referenced:
msg += "\n\n- Referenced at {}:{}:\n\n{}" \
.format(node.filename, node.linenr, node)
self._warn(msg)
def _warn(self, msg, filename=None, linenr=None):
# For printing general warnings
if self._warnings_enabled:
msg = "warning: " + msg
if filename is not None:
msg = "{}:{}: {}".format(filename, linenr, msg)
self.warnings.append(msg)
if self._warn_to_stderr:
sys.stderr.write(msg + "\n")
def _warn_undef_assign(self, msg, filename=None, linenr=None):
# See the class documentation
if self._warn_for_undef_assign:
self._warn(msg, filename, linenr)
def _warn_undef_assign_load(self, name, val, filename, linenr):
# Special version for load_config()
self._warn_undef_assign(
'attempt to assign the value "{}" to the undefined symbol {}'
.format(val, name), filename, linenr)
def _warn_redun_assign(self, msg, filename=None, linenr=None):
# See the class documentation
if self._warn_for_redun_assign:
self._warn(msg, filename, linenr)
def _srctree_hint(self):
# Hint printed when Kconfig files can't be found or .config files can't
# be opened
return ". Perhaps the $srctree environment variable ({}) " \
"is set incorrectly. Note that the current value of $srctree " \
"is saved when the Kconfig instance is created (for " \
"consistency and to cleanly separate instances)." \
.format("set to '{}'".format(self.srctree) if self.srctree
else "unset or blank")
class Symbol(object):
"""
Represents a configuration symbol:
(menu)config FOO
...
The following attributes are available. They should be viewed as read-only,
and some are implemented through @property magic (but are still efficient
to access due to internal caching).
Note: Prompts, help texts, and locations are stored in the Symbol's
MenuNode(s) rather than in the Symbol itself. Check the MenuNode class and
the Symbol.nodes attribute. This organization matches the C tools.
name:
The name of the symbol, e.g. "FOO" for 'config FOO'.
type:
The type of the symbol. One of BOOL, TRISTATE, STRING, INT, HEX, UNKNOWN.
UNKNOWN is for undefined symbols, (non-special) constant symbols, and
symbols defined without a type.
When running without modules (MODULES having the value n), TRISTATE
symbols magically change type to BOOL. This also happens for symbols
within choices in "y" mode. This matches the C tools, and makes sense for
menuconfig-like functionality.
orig_type:
The type as given in the Kconfig file, without any magic applied. Used
when printing the symbol.
str_value:
The value of the symbol as a string. Gives the value for string/int/hex
symbols. For bool/tristate symbols, gives "n", "m", or "y".
This is the symbol value that's used in relational expressions
(A = B, A != B, etc.)
Gotcha: For int/hex symbols, the exact format of the value must often be
preserved (e.g., when writing a .config file), hence why you can't get it
directly as an int. Do int(int_sym.str_value) or
int(hex_sym.str_value, 16) to get the integer value.
tri_value:
The tristate value of the symbol as an integer. One of 0, 1, 2,
representing n, m, y. Always 0 (n) for non-bool/tristate symbols.
This is the symbol value that's used outside of relation expressions
(A, !A, A && B, A || B).
assignable:
A tuple containing the tristate user values that can currently be
assigned to the symbol (that would be respected), ordered from lowest (0,
representing n) to highest (2, representing y). This corresponds to the
selections available in the menuconfig interface. The set of assignable
values is calculated from the symbol's visibility and selects/implies.
Returns the empty set for non-bool/tristate symbols and for symbols with
visibility n. The other possible values are (0, 2), (0, 1, 2), (1, 2),
(1,), and (2,). A (1,) or (2,) result means the symbol is visible but
"locked" to m or y through a select, perhaps in combination with the
visibility. menuconfig represents this as -M- and -*-, respectively.
For string/hex/int symbols, check if Symbol.visibility is non-0 (non-n)
instead to determine if the value can be changed.
Some handy 'assignable' idioms:
# Is 'sym' an assignable (visible) bool/tristate symbol?
if sym.assignable:
# What's the highest value it can be assigned? [-1] in Python
# gives the last element.
sym_high = sym.assignable[-1]
# The lowest?
sym_low = sym.assignable[0]
# Can the symbol be set to at least m?
if sym.assignable[-1] >= 1:
...
# Can the symbol be set to m?
if 1 in sym.assignable:
...
visibility:
The visibility of the symbol. One of 0, 1, 2, representing n, m, y. See
the module documentation for an overview of symbol values and visibility.
user_value:
The user value of the symbol. None if no user value has been assigned
(via Kconfig.load_config() or Symbol.set_value()).
Holds 0, 1, or 2 for bool/tristate symbols, and a string for the other
symbol types.
WARNING: Do not assign directly to this. It will break things. Use
Symbol.set_value().
config_string:
The .config assignment string that would get written out for the symbol
by Kconfig.write_config(). Returns the empty string if no .config
assignment would get written out.
In general, visible symbols, symbols with (active) defaults, and selected
symbols get written out. This includes all non-n-valued bool/tristate
symbols, and all visible string/int/hex symbols.
Symbols with the (no longer needed) 'option env=...' option generate no
configuration output, and neither does the special
'option defconfig_list' symbol.
Tip: This field is useful when generating custom configuration output,
even for non-.config-like formats. To write just the symbols that would
get written out to .config files, do this:
if sym.config_string:
*Write symbol, e.g. by looking sym.str_value*
This is a superset of the symbols written out by write_autoconf().
That function skips all n-valued symbols.
There usually won't be any great harm in just writing all symbols either,
though you might get some special symbols and possibly some "redundant"
n-valued symbol entries in there.
nodes:
A list of MenuNodes for this symbol. Will contain a single MenuNode for
most symbols. Undefined and constant symbols have an empty nodes list.
Symbols defined in multiple locations get one node for each location.
choice:
Holds the parent Choice for choice symbols, and None for non-choice
symbols. Doubles as a flag for whether a symbol is a choice symbol.
defaults:
List of (default, cond) tuples for the symbol's 'default' properties. For
example, 'default A && B if C || D' is represented as
((AND, A, B), (OR, C, D)). If no condition was given, 'cond' is
self.kconfig.y.
Note that 'depends on' and parent dependencies are propagated to
'default' conditions.
selects:
List of (symbol, cond) tuples for the symbol's 'select' properties. For
example, 'select A if B && C' is represented as (A, (AND, B, C)). If no
condition was given, 'cond' is self.kconfig.y.
Note that 'depends on' and parent dependencies are propagated to 'select'
conditions.
implies:
Like 'selects', for imply.
ranges:
List of (low, high, cond) tuples for the symbol's 'range' properties. For
example, 'range 1 2 if A' is represented as (1, 2, A). If there is no
condition, 'cond' is self.config.y.
Note that 'depends on' and parent dependencies are propagated to 'range'
conditions.
Gotcha: 1 and 2 above will be represented as (undefined) Symbols rather
than plain integers. Undefined symbols get their name as their string
value, so this works out. The C tools work the same way.
rev_dep:
Reverse dependency expression from other symbols selecting this symbol.
Multiple selections get ORed together. A condition on a select is ANDed
with the selecting symbol.
For example, if A has 'select FOO' and B has 'select FOO if C', then
FOO's rev_dep will be (OR, A, (AND, B, C)).
weak_rev_dep:
Like rev_dep, for imply.
direct_dep:
The 'depends on' dependencies. If a symbol is defined in multiple
locations, the dependencies at each location are ORed together.
Internally, this is used to implement 'imply', which only applies if the
implied symbol has expr_value(self.direct_dep) != 0. 'depends on' and
parent dependencies are automatically propagated to the conditions of
properties, so normally it's redundant to check the direct dependencies.
referenced:
A set() with all symbols and choices referenced in the properties and
property conditions of the symbol.
Also includes dependencies inherited from surrounding menus and if's.
Choices appear in the dependencies of choice symbols.
env_var:
If the Symbol has an 'option env="FOO"' option, this contains the name
("FOO") of the environment variable. None for symbols without no
'option env'.
'option env="FOO"' acts like a 'default' property whose value is the
value of $FOO.
Symbols with 'option env' are never written out to .config files, even if
they are visible. env_var corresponds to a flag called SYMBOL_AUTO in the
C implementation.
is_allnoconfig_y:
True if the symbol has 'option allnoconfig_y' set on it. This has no
effect internally (except when printing symbols), but can be checked by
scripts.
is_constant:
True if the symbol is a constant (quoted) symbol.
kconfig:
The Kconfig instance this symbol is from.
"""
__slots__ = (
"_cached_assignable",
"_cached_str_val",
"_cached_tri_val",
"_cached_vis",
"_dependents",
"_old_val",
"_visited",
"_was_set",
"_write_to_conf",
"choice",
"defaults",
"direct_dep",
"env_var",
"implies",
"is_allnoconfig_y",
"is_constant",
"kconfig",
"name",
"nodes",
"orig_type",
"ranges",
"rev_dep",
"selects",
"user_value",
"weak_rev_dep",
)
#
# Public interface
#
@property
def type(self):
"""
See the class documentation.
"""
if self.orig_type is TRISTATE and \
((self.choice and self.choice.tri_value == 2) or
not self.kconfig.modules.tri_value):
return BOOL
return self.orig_type
@property
def str_value(self):
"""
See the class documentation.
"""
if self._cached_str_val is not None:
return self._cached_str_val
if self.orig_type in (BOOL, TRISTATE):
# Also calculates the visibility, so invalidation safe
self._cached_str_val = TRI_TO_STR[self.tri_value]
return self._cached_str_val
# As a quirk of Kconfig, undefined symbols get their name as their
# string value. This is why things like "FOO = bar" work for seeing if
# FOO has the value "bar".
if not self.orig_type: # UNKNOWN
self._cached_str_val = self.name
return self.name
val = ""
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
vis = self.visibility
self._write_to_conf = (vis != 0)
if self.orig_type in (INT, HEX):
# The C implementation checks the user value against the range in a
# separate code path (post-processing after loading a .config).
# Checking all values here instead makes more sense for us. It
# requires that we check for a range first.
base = _TYPE_TO_BASE[self.orig_type]
# Check if a range is in effect
for low_expr, high_expr, cond in self.ranges:
if expr_value(cond):
has_active_range = True
# The zeros are from the C implementation running strtoll()
# on empty strings
low = int(low_expr.str_value, base) if \
_is_base_n(low_expr.str_value, base) else 0
high = int(high_expr.str_value, base) if \
_is_base_n(high_expr.str_value, base) else 0
break
else:
has_active_range = False
# Defaults are used if the symbol is invisible, lacks a user value,
# or has an out-of-range user value
use_defaults = True
if vis and self.user_value:
user_val = int(self.user_value, base)
if has_active_range and not low <= user_val <= high:
num2str = str if base == 10 else hex
self.kconfig._warn(
"user value {} on the {} symbol {} ignored due to "
"being outside the active range ([{}, {}]) -- falling "
"back on defaults"
.format(num2str(user_val), TYPE_TO_STR[self.orig_type],
_name_and_loc(self),
num2str(low), num2str(high)))
else:
# If the user value is well-formed and satisfies range
# contraints, it is stored in exactly the same form as
# specified in the assignment (with or without "0x", etc.)
val = self.user_value
use_defaults = False
if use_defaults:
# No user value or invalid user value. Look at defaults.
# Used to implement the warning below
has_default = False
for val_sym, cond in self.defaults:
if expr_value(cond):
has_default = self._write_to_conf = True
val = val_sym.str_value
if _is_base_n(val, base):
val_num = int(val, base)
else:
val_num = 0 # strtoll() on empty string
break
else:
val_num = 0 # strtoll() on empty string
# This clamping procedure runs even if there's no default
if has_active_range:
clamp = None
if val_num < low:
clamp = low
elif val_num > high:
clamp = high
if clamp is not None:
# The value is rewritten to a standard form if it is
# clamped
val = str(clamp) \
if self.orig_type is INT else \
hex(clamp)
if has_default:
num2str = str if base == 10 else hex
self.kconfig._warn(
"default value {} on {} clamped to {} due to "
"being outside the active range ([{}, {}])"
.format(val_num, _name_and_loc(self),
num2str(clamp), num2str(low),
num2str(high)))
elif self.orig_type is STRING:
if vis and self.user_value is not None:
# If the symbol is visible and has a user value, use that
val = self.user_value
else:
# Otherwise, look at defaults
for val_sym, cond in self.defaults:
if expr_value(cond):
val = val_sym.str_value
self._write_to_conf = True
break
# env_var corresponds to SYMBOL_AUTO in the C implementation, and is
# also set on the defconfig_list symbol there. Test for the
# defconfig_list symbol explicitly instead here, to avoid a nonsensical
# env_var setting and the defconfig_list symbol being printed
# incorrectly. This code is pretty cold anyway.
if self.env_var is not None or self is self.kconfig.defconfig_list:
self._write_to_conf = False
self._cached_str_val = val
return val
@property
def tri_value(self):
"""
See the class documentation.
"""
if self._cached_tri_val is not None:
return self._cached_tri_val
if self.orig_type not in (BOOL, TRISTATE):
if self.orig_type: # != UNKNOWN
# Would take some work to give the location here
self.kconfig._warn(
"The {} symbol {} is being evaluated in a logical context "
"somewhere. It will always evaluate to n."
.format(TYPE_TO_STR[self.orig_type], _name_and_loc(self)))
self._cached_tri_val = 0
return 0
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
vis = self.visibility
self._write_to_conf = (vis != 0)
val = 0
if not self.choice:
# Non-choice symbol
if vis and self.user_value is not None:
# If the symbol is visible and has a user value, use that
val = min(self.user_value, vis)
else:
# Otherwise, look at defaults and weak reverse dependencies
# (implies)
for default, cond in self.defaults:
dep_val = expr_value(cond)
if dep_val:
val = min(expr_value(default), dep_val)
if val:
self._write_to_conf = True
break
# Weak reverse dependencies are only considered if our
# direct dependencies are met
dep_val = expr_value(self.weak_rev_dep)
if dep_val and expr_value(self.direct_dep):
val = max(dep_val, val)
self._write_to_conf = True
# Reverse (select-related) dependencies take precedence
dep_val = expr_value(self.rev_dep)
if dep_val:
if expr_value(self.direct_dep) < dep_val:
self._warn_select_unsatisfied_deps()
val = max(dep_val, val)
self._write_to_conf = True
# m is promoted to y for (1) bool symbols and (2) symbols with a
# weak_rev_dep (from imply) of y
if val == 1 and \
(self.type is BOOL or expr_value(self.weak_rev_dep) == 2):
val = 2
elif vis == 2:
# Visible choice symbol in y-mode choice. The choice mode limits
# the visibility of choice symbols, so it's sufficient to just
# check the visibility of the choice symbols themselves.
val = 2 if self.choice.selection is self else 0
elif vis and self.user_value:
# Visible choice symbol in m-mode choice, with set non-0 user value
val = 1
self._cached_tri_val = val
return val
@property
def assignable(self):
"""
See the class documentation.
"""
if self._cached_assignable is None:
self._cached_assignable = self._assignable()
return self._cached_assignable
@property
def visibility(self):
"""
See the class documentation.
"""
if self._cached_vis is None:
self._cached_vis = _visibility(self)
return self._cached_vis
@property
def config_string(self):
"""
See the class documentation.
"""
# Note: _write_to_conf is determined when the value is calculated. This
# is a hidden function call due to property magic.
val = self.str_value
if not self._write_to_conf:
return ""
if self.orig_type in (BOOL, TRISTATE):
return "{}{}={}\n" \
.format(self.kconfig.config_prefix, self.name, val) \
if val != "n" else \
"# {}{} is not set\n" \
.format(self.kconfig.config_prefix, self.name)
if self.orig_type in (INT, HEX):
return "{}{}={}\n" \
.format(self.kconfig.config_prefix, self.name, val)
if self.orig_type is STRING:
return '{}{}="{}"\n' \
.format(self.kconfig.config_prefix, self.name, escape(val))
_internal_error("Internal error while creating .config: unknown "
'type "{}".'.format(self.orig_type))
def set_value(self, value):
"""
Sets the user value of the symbol.
Equal in effect to assigning the value to the symbol within a .config
file. For bool and tristate symbols, use the 'assignable' attribute to
check which values can currently be assigned. Setting values outside
'assignable' will cause Symbol.user_value to differ from
Symbol.str/tri_value (be truncated down or up).
Setting a choice symbol to 2 (y) sets Choice.user_selection to the
choice symbol in addition to setting Symbol.user_value.
Choice.user_selection is considered when the choice is in y mode (the
"normal" mode).
Other symbols that depend (possibly indirectly) on this symbol are
automatically recalculated to reflect the assigned value.
value:
The user value to give to the symbol. For bool and tristate symbols,
n/m/y can be specified either as 0/1/2 (the usual format for tristate
values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
symbol types, pass a string.
Values that are invalid for the type (such as "foo" or 1 (m) for a
BOOL or "0x123" for an INT) are ignored and won't be stored in
Symbol.user_value. Kconfiglib will print a warning by default for
invalid assignments, and set_value() will return False.
Returns True if the value is valid for the type of the symbol, and
False otherwise. This only looks at the form of the value. For BOOL and
TRISTATE symbols, check the Symbol.assignable attribute to see what
values are currently in range and would actually be reflected in the
value of the symbol. For other symbol types, check whether the
visibility is non-n.
"""
# If the new user value matches the old, nothing changes, and we can
# save some work.
#
# This optimization is skipped for choice symbols: Setting a choice
# symbol's user value to y might change the state of the choice, so it
# wouldn't be safe (symbol user values always match the values set in a
# .config file or via set_value(), and are never implicitly updated).
if value == self.user_value and not self.choice:
self._was_set = True
return True
# Check if the value is valid for our type
if not (self.orig_type is BOOL and value in (0, 2, "n", "y") or
self.orig_type is TRISTATE and value in (0, 1, 2, "n", "m", "y") or
(isinstance(value, str) and
(self.orig_type is STRING or
self.orig_type is INT and _is_base_n(value, 10) or
self.orig_type is HEX and _is_base_n(value, 16)
and int(value, 16) >= 0))):
# Display tristate values as n, m, y in the warning
self.kconfig._warn(
"the value {} is invalid for {}, which has type {} -- "
"assignment ignored"
.format(TRI_TO_STR[value] if value in (0, 1, 2) else
"'{}'".format(value),
_name_and_loc(self), TYPE_TO_STR[self.orig_type]))
return False
if self.orig_type in (BOOL, TRISTATE) and value in ("n", "m", "y"):
value = STR_TO_TRI[value]
self.user_value = value
self._was_set = True
if self.choice and value == 2:
# Setting a choice symbol to y makes it the user selection of the
# choice. Like for symbol user values, the user selection is not
# guaranteed to match the actual selection of the choice, as
# dependencies come into play.
self.choice.user_selection = self
self.choice._was_set = True
self.choice._rec_invalidate()
else:
self._rec_invalidate_if_has_prompt()
return True
def unset_value(self):
"""
Resets the user value of the symbol, as if the symbol had never gotten
a user value via Kconfig.load_config() or Symbol.set_value().
"""
if self.user_value is not None:
self.user_value = None
self._rec_invalidate_if_has_prompt()
@property
def referenced(self):
"""
See the class documentation.
"""
res = set()
for node in self.nodes:
res |= node.referenced
return res
def __repr__(self):
"""
Returns a string with information about the symbol (including its name,
value, visibility, and location(s)) when it is evaluated on e.g. the
interactive Python prompt.
"""
fields = []
fields.append("symbol " + self.name)
fields.append(TYPE_TO_STR[self.type])
for node in self.nodes:
if node.prompt:
fields.append('"{}"'.format(node.prompt[0]))
# Only add quotes for non-bool/tristate symbols
fields.append("value " +
(self.str_value
if self.orig_type in (BOOL, TRISTATE) else
'"{}"'.format(self.str_value)))
if not self.is_constant:
# These aren't helpful to show for constant symbols
if self.user_value is not None:
# Only add quotes for non-bool/tristate symbols
fields.append("user value " +
(TRI_TO_STR[self.user_value]
if self.orig_type in (BOOL, TRISTATE) else
'"{}"'.format(self.user_value)))
fields.append("visibility " + TRI_TO_STR[self.visibility])
if self.choice:
fields.append("choice symbol")
if self.is_allnoconfig_y:
fields.append("allnoconfig_y")
if self is self.kconfig.defconfig_list:
fields.append("is the defconfig_list symbol")
if self.env_var is not None:
fields.append("from environment variable " + self.env_var)
if self is self.kconfig.modules:
fields.append("is the modules symbol")
fields.append("direct deps " +
TRI_TO_STR[expr_value(self.direct_dep)])
if self.nodes:
for node in self.nodes:
fields.append("{}:{}".format(node.filename, node.linenr))
else:
if self.is_constant:
fields.append("constant")
else:
fields.append("undefined")
return "<{}>".format(", ".join(fields))
def __str__(self):
"""
Returns a string representation of the symbol when it is printed,
matching the Kconfig format, with parent dependencies propagated.
The string is constructed by joining the strings returned by
MenuNode.__str__() for each of the symbol's menu nodes, so symbols
defined in multiple locations will return a string with all
definitions.
The returned string does not end in a newline. An empty string is
returned for undefined and constant symbols.
"""
return self.custom_str(standard_sc_expr_str)
def custom_str(self, sc_expr_str_fn):
"""
Works like Symbol.__str__(), but allows a custom format to be used for
all symbol/choice references. See expr_str().
"""
return "\n\n".join(node.custom_str(sc_expr_str_fn)
for node in self.nodes)
#
# Private methods
#
def __init__(self):
"""
Symbol constructor -- not intended to be called directly by Kconfiglib
clients.
"""
# These attributes are always set on the instance from outside and
# don't need defaults:
# kconfig
# direct_dep
# is_constant
# name
# rev_dep
# weak_rev_dep
self.orig_type = UNKNOWN
self.defaults = []
self.selects = []
self.implies = []
self.ranges = []
self.nodes = []
self.user_value = \
self.choice = \
self.env_var = \
self._cached_str_val = self._cached_tri_val = self._cached_vis = \
self._cached_assignable = None
# _write_to_conf is calculated along with the value. If True, the
# Symbol gets a .config entry.
self.is_allnoconfig_y = \
self._was_set = \
self._write_to_conf = False
# See Kconfig._build_dep()
self._dependents = set()
# Used during dependency loop detection and (independently) in
# node_iter()
self._visited = 0
def _assignable(self):
# Worker function for the 'assignable' attribute
if self.orig_type not in (BOOL, TRISTATE):
return ()
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
vis = self.visibility
if not vis:
return ()
rev_dep_val = expr_value(self.rev_dep)
if vis == 2:
if self.choice:
return (2,)
if not rev_dep_val:
if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
return (0, 2)
return (0, 1, 2)
if rev_dep_val == 2:
return (2,)
# rev_dep_val == 1
if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
return (2,)
return (1, 2)
# vis == 1
# Must be a tristate here, because bool m visibility gets promoted to y
if not rev_dep_val:
return (0, 1) if expr_value(self.weak_rev_dep) != 2 else (0, 2)
if rev_dep_val == 2:
return (2,)
# vis == rev_dep_val == 1
return (1,)
def _invalidate(self):
# Marks the symbol as needing to be recalculated
self._cached_str_val = self._cached_tri_val = self._cached_vis = \
self._cached_assignable = None
def _rec_invalidate(self):
# Invalidates the symbol and all items that (possibly) depend on it
if self is self.kconfig.modules:
# Invalidating MODULES has wide-ranging effects
self.kconfig._invalidate_all()
else:
self._invalidate()
for item in self._dependents:
# _cached_vis doubles as a flag that tells us whether 'item'
# has cached values, because it's calculated as a side effect
# of calculating all other (non-constant) cached values.
#
# If item._cached_vis is None, it means there can't be cached
# values on other items that depend on 'item', because if there
# were, some value on 'item' would have been calculated and
# item._cached_vis set as a side effect. It's therefore safe to
# stop the invalidation at symbols with _cached_vis None.
#
# This approach massively speeds up scripts that set a lot of
# values, vs simply invalidating all possibly dependent symbols
# (even when you already have a list of all the dependent
# symbols, because some symbols get huge dependency trees).
#
# This gracefully handles dependency loops too, which is nice
# for choices, where the choice depends on the choice symbols
# and vice versa.
if item._cached_vis is not None:
item._rec_invalidate()
def _rec_invalidate_if_has_prompt(self):
# Invalidates the symbol and its dependent symbols, but only if the
# symbol has a prompt. User values never have an effect on promptless
# symbols, so we skip invalidation for them as an optimization.
#
# This also prevents constant (quoted) symbols from being invalidated
# if set_value() is called on them, which would cause them to lose
# their value and break things.
#
# Prints a warning if the symbol has no prompt. In some contexts (e.g.
# when loading a .config files) assignments to promptless symbols are
# normal and expected, so the warning can be disabled.
for node in self.nodes:
if node.prompt:
self._rec_invalidate()
return
if self.kconfig._warn_for_no_prompt:
self.kconfig._warn(_name_and_loc(self) + " has no prompt, meaning "
"user values have no effect on it")
def _str_default(self):
# write_min_config() helper function. Returns the value the symbol
# would get from defaults if it didn't have a user value. Uses exactly
# the same algorithm as the C implementation (though a bit cleaned up),
# for compatibility.
if self.orig_type in (BOOL, TRISTATE):
val = 0
# Defaults, selects, and implies do not affect choice symbols
if not self.choice:
for default, cond in self.defaults:
cond_val = expr_value(cond)
if cond_val:
val = min(expr_value(default), cond_val)
break
val = max(expr_value(self.rev_dep),
expr_value(self.weak_rev_dep),
val)
# Transpose mod to yes if type is bool (possibly due to modules
# being disabled)
if val == 1 and self.type is BOOL:
val = 2
return TRI_TO_STR[val]
if self.orig_type in (STRING, INT, HEX):
for default, cond in self.defaults:
if expr_value(cond):
return default.str_value
return ""
def _warn_select_unsatisfied_deps(self):
# Helper for printing an informative warning when a symbol with
# unsatisfied direct dependencies (dependencies from 'depends on', ifs,
# and menus) is selected by some other symbol. Also warn if a symbol
# whose direct dependencies evaluate to m is selected to y.
msg = "{} has direct dependencies {} with value {}, but is " \
"currently being {}-selected by the following symbols:" \
.format(_name_and_loc(self), expr_str(self.direct_dep),
TRI_TO_STR[expr_value(self.direct_dep)],
TRI_TO_STR[expr_value(self.rev_dep)])
# The reverse dependencies from each select are ORed together
for select in split_expr(self.rev_dep, OR):
if expr_value(select) <= expr_value(self.direct_dep):
# Only include selects that exceed the direct dependencies
continue
# - 'select A if B' turns into A && B
# - 'select A' just turns into A
#
# In both cases, we can split on AND and pick the first operand
selecting_sym = split_expr(select, AND)[0]
msg += "\n - {}, with value {}, direct dependencies {} " \
"(value: {})" \
.format(_name_and_loc(selecting_sym),
selecting_sym.str_value,
expr_str(selecting_sym.direct_dep),
TRI_TO_STR[expr_value(selecting_sym.direct_dep)])
if isinstance(select, tuple):
msg += ", and select condition {} (value: {})" \
.format(expr_str(select[2]),
TRI_TO_STR[expr_value(select[2])])
self.kconfig._warn(msg)
class Choice(object):
"""
Represents a choice statement:
choice
...
endchoice
The following attributes are available on Choice instances. They should be
treated as read-only, and some are implemented through @property magic (but
are still efficient to access due to internal caching).
Note: Prompts, help texts, and locations are stored in the Choice's
MenuNode(s) rather than in the Choice itself. Check the MenuNode class and
the Choice.nodes attribute. This organization matches the C tools.
name:
The name of the choice, e.g. "FOO" for 'choice FOO', or None if the
Choice has no name.
type:
The type of the choice. One of BOOL, TRISTATE, UNKNOWN. UNKNOWN is for
choices defined without a type where none of the contained symbols have a
type either (otherwise the choice inherits the type of the first symbol
defined with a type).
When running without modules (CONFIG_MODULES=n), TRISTATE choices
magically change type to BOOL. This matches the C tools, and makes sense
for menuconfig-like functionality.
orig_type:
The type as given in the Kconfig file, without any magic applied. Used
when printing the choice.
tri_value:
The tristate value (mode) of the choice. A choice can be in one of three
modes:
0 (n) - The choice is disabled and no symbols can be selected. For
visible choices, this mode is only possible for choices with
the 'optional' flag set (see kconfig-language.txt).
1 (m) - Any number of choice symbols can be set to m, the rest will
be n.
2 (y) - One symbol will be y, the rest n.
Only tristate choices can be in m mode. The visibility of the choice is
an upper bound on the mode, and the mode in turn is an upper bound on the
visibility of the choice symbols.
To change the mode, use Choice.set_value().
Implementation note:
The C tools internally represent choices as a type of symbol, with
special-casing in many code paths. This is why there is a lot of
similarity to Symbol. The value (mode) of a choice is really just a
normal symbol value, and an implicit reverse dependency forces its
lower bound to m for visible non-optional choices (the reverse
dependency is 'm && <visibility>').
Symbols within choices get the choice propagated as a dependency to
their properties. This turns the mode of the choice into an upper bound
on e.g. the visibility of choice symbols, and explains the gotcha
related to printing choice symbols mentioned in the module docstring.
Kconfiglib uses a separate Choice class only because it makes the code
and interface less confusing (especially in a user-facing interface).
Corresponding attributes have the same name in the Symbol and Choice
classes, for consistency and compatibility.
assignable:
See the symbol class documentation. Gives the assignable values (modes).
visibility:
See the Symbol class documentation. Acts on the value (mode).
selection:
The Symbol instance of the currently selected symbol. None if the Choice
is not in y mode or has no selected symbol (due to unsatisfied
dependencies on choice symbols).
WARNING: Do not assign directly to this. It will break things. Call
sym.set_value(2) on the choice symbol you want to select instead.
user_value:
The value (mode) selected by the user through Choice.set_value(). Either
0, 1, or 2, or None if the user hasn't selected a mode. See
Symbol.user_value.
WARNING: Do not assign directly to this. It will break things. Use
Choice.set_value() instead.
user_selection:
The symbol selected by the user (by setting it to y). Ignored if the
choice is not in y mode, but still remembered so that the choice "snaps
back" to the user selection if the mode is changed back to y. This might
differ from 'selection' due to unsatisfied dependencies.
WARNING: Do not assign directly to this. It will break things. Call
sym.set_value(2) on the choice symbol to be selected instead.
syms:
List of symbols contained in the choice.
Obscure gotcha: If a symbol depends on the previous symbol within a
choice so that an implicit menu is created, it won't be a choice symbol,
and won't be included in 'syms'.
nodes:
A list of MenuNodes for this choice. In practice, the list will probably
always contain a single MenuNode, but it is possible to give a choice a
name and define it in multiple locations.
defaults:
List of (symbol, cond) tuples for the choice's 'defaults' properties. For
example, 'default A if B && C' is represented as (A, (AND, B, C)). If
there is no condition, 'cond' is self.config.y.
Note that 'depends on' and parent dependencies are propagated to
'default' conditions.
direct_dep:
See Symbol.direct_dep.
referenced:
A set() with all symbols referenced in the properties and property
conditions of the choice.
Also includes dependencies inherited from surrounding menus and if's.
is_optional:
True if the choice has the 'optional' flag set on it and can be in
n mode.
kconfig:
The Kconfig instance this choice is from.
"""
__slots__ = (
"_cached_assignable",
"_cached_selection",
"_cached_vis",
"_dependents",
"_visited",
"_was_set",
"defaults",
"direct_dep",
"is_constant",
"is_optional",
"kconfig",
"name",
"nodes",
"orig_type",
"syms",
"user_selection",
"user_value",
)
#
# Public interface
#
@property
def type(self):
"""
Returns the type of the choice. See Symbol.type.
"""
if self.orig_type is TRISTATE and not self.kconfig.modules.tri_value:
return BOOL
return self.orig_type
@property
def str_value(self):
"""
See the class documentation.
"""
return TRI_TO_STR[self.tri_value]
@property
def tri_value(self):
"""
See the class documentation.
"""
# This emulates a reverse dependency of 'm && visibility' for
# non-optional choices, which is how the C implementation does it
val = 0 if self.is_optional else 1
if self.user_value is not None:
val = max(val, self.user_value)
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
val = min(val, self.visibility)
# Promote m to y for boolean choices
return 2 if val == 1 and self.type is BOOL else val
@property
def assignable(self):
"""
See the class documentation.
"""
if self._cached_assignable is None:
self._cached_assignable = self._assignable()
return self._cached_assignable
@property
def visibility(self):
"""
See the class documentation.
"""
if self._cached_vis is None:
self._cached_vis = _visibility(self)
return self._cached_vis
@property
def selection(self):
"""
See the class documentation.
"""
if self._cached_selection is _NO_CACHED_SELECTION:
self._cached_selection = self._selection()
return self._cached_selection
def set_value(self, value):
"""
Sets the user value (mode) of the choice. Like for Symbol.set_value(),
the visibility might truncate the value. Choices without the 'optional'
attribute (is_optional) can never be in n mode, but 0/"n" is still
accepted since it's not a malformed value (though it will have no
effect).
Returns True if the value is valid for the type of the choice, and
False otherwise. This only looks at the form of the value. Check the
Choice.assignable attribute to see what values are currently in range
and would actually be reflected in the mode of the choice.
"""
if value == self.user_value:
# We know the value must be valid if it was successfully set
# previously
self._was_set = True
return True
if not ((self.orig_type is BOOL and value in (0, 2, "n", "y") ) or
(self.orig_type is TRISTATE and value in (0, 1, 2, "n", "m", "y"))):
# Display tristate values as n, m, y in the warning
self.kconfig._warn(
"the value {} is invalid for {}, which has type {} -- "
"assignment ignored"
.format(TRI_TO_STR[value] if value in (0, 1, 2) else
"'{}'".format(value),
_name_and_loc(self),
TYPE_TO_STR[self.orig_type]))
return False
if value in ("n", "m", "y"):
value = STR_TO_TRI[value]
self.user_value = value
self._was_set = True
self._rec_invalidate()
return True
def unset_value(self):
"""
Resets the user value (mode) and user selection of the Choice, as if
the user had never touched the mode or any of the choice symbols.
"""
if self.user_value is not None or self.user_selection:
self.user_value = self.user_selection = None
self._rec_invalidate()
@property
def referenced(self):
"""
See the class documentation.
"""
res = set()
for node in self.nodes:
res |= node.referenced
return res
def __repr__(self):
"""
Returns a string with information about the choice when it is evaluated
on e.g. the interactive Python prompt.
"""
fields = []
fields.append("choice " + self.name if self.name else "choice")
fields.append(TYPE_TO_STR[self.type])
for node in self.nodes:
if node.prompt:
fields.append('"{}"'.format(node.prompt[0]))
fields.append("mode " + self.str_value)
if self.user_value is not None:
fields.append('user mode {}'.format(TRI_TO_STR[self.user_value]))
if self.selection:
fields.append("{} selected".format(self.selection.name))
if self.user_selection:
user_sel_str = "{} selected by user" \
.format(self.user_selection.name)
if self.selection is not self.user_selection:
user_sel_str += " (overridden)"
fields.append(user_sel_str)
fields.append("visibility " + TRI_TO_STR[self.visibility])
if self.is_optional:
fields.append("optional")
for node in self.nodes:
fields.append("{}:{}".format(node.filename, node.linenr))
return "<{}>".format(", ".join(fields))
def __str__(self):
"""
Returns a string representation of the choice when it is printed,
matching the Kconfig format (though without the contained choice
symbols).
The returned string does not end in a newline.
See Symbol.__str__() as well.
"""
return self.custom_str(standard_sc_expr_str)
def custom_str(self, sc_expr_str_fn):
"""
Works like Choice.__str__(), but allows a custom format to be used for
all symbol/choice references. See expr_str().
"""
return "\n\n".join(node.custom_str(sc_expr_str_fn)
for node in self.nodes)
#
# Private methods
#
def __init__(self):
"""
Choice constructor -- not intended to be called directly by Kconfiglib
clients.
"""
# These attributes are always set on the instance from outside and
# don't need defaults:
# direct_dep
# kconfig
self.orig_type = UNKNOWN
self.syms = []
self.defaults = []
self.nodes = []
self.name = \
self.user_value = self.user_selection = \
self._cached_vis = self._cached_assignable = None
self._cached_selection = _NO_CACHED_SELECTION
# is_constant is checked by _make_depend_on(). Just set it to avoid
# having to special-case choices.
self.is_constant = self.is_optional = False
# See Kconfig._build_dep()
self._dependents = set()
# Used during dependency loop detection
self._visited = 0
def _assignable(self):
# Worker function for the 'assignable' attribute
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
vis = self.visibility
if not vis:
return ()
if vis == 2:
if not self.is_optional:
return (2,) if self.type is BOOL else (1, 2)
return (0, 2) if self.type is BOOL else (0, 1, 2)
# vis == 1
return (0, 1) if self.is_optional else (1,)
def _selection(self):
# Worker function for the 'selection' attribute
# Warning: See Symbol._rec_invalidate(), and note that this is a hidden
# function call (property magic)
if self.tri_value != 2:
# Not in y mode, so no selection
return None
# Use the user selection if it's visible
if self.user_selection and self.user_selection.visibility:
return self.user_selection
# Otherwise, check if we have a default
return self._get_selection_from_defaults()
def _get_selection_from_defaults(self):
# Check if we have a default
for sym, cond in self.defaults:
# The default symbol must be visible too
if expr_value(cond) and sym.visibility:
return sym
# Otherwise, pick the first visible symbol, if any
for sym in self.syms:
if sym.visibility:
return sym
# Couldn't find a selection
return None
def _invalidate(self):
self._cached_vis = self._cached_assignable = None
self._cached_selection = _NO_CACHED_SELECTION
def _rec_invalidate(self):
# See Symbol._rec_invalidate()
self._invalidate()
for item in self._dependents:
if item._cached_vis is not None:
item._rec_invalidate()
class MenuNode(object):
"""
Represents a menu node in the configuration. This corresponds to an entry
in e.g. the 'make menuconfig' interface, though non-visible choices, menus,
and comments also get menu nodes. If a symbol or choice is defined in
multiple locations, it gets one menu node for each location.
The top-level menu node, corresponding to the implicit top-level menu, is
available in Kconfig.top_node.
The menu nodes for a Symbol or Choice can be found in the
Symbol/Choice.nodes attribute. Menus and comments are represented as plain
menu nodes, with their text stored in the prompt attribute (prompt[0]).
This mirrors the C implementation.
The following attributes are available on MenuNode instances. They should
be viewed as read-only.
item:
Either a Symbol, a Choice, or one of the constants MENU and COMMENT.
Menus and comments are represented as plain menu nodes. Ifs are collapsed
(matching the C implementation) and do not appear in the final menu tree.
next:
The following menu node. None if there is no following node.
list:
The first child menu node. None if there are no children.
Choices and menus naturally have children, but Symbols can also have
children because of menus created automatically from dependencies (see
kconfig-language.txt).
parent:
The parent menu node. None if there is no parent.
prompt:
A (string, cond) tuple with the prompt for the menu node and its
conditional expression (which is self.kconfig.y if there is no
condition). None if there is no prompt.
For symbols and choices, the prompt is stored in the MenuNode rather than
the Symbol or Choice instance. For menus and comments, the prompt holds
the text.
defaults:
The 'default' properties for this particular menu node. See
symbol.defaults.
When evaluating defaults, you should use Symbol/Choice.defaults instead,
as it include properties from all menu nodes (a symbol/choice can have
multiple definition locations/menu nodes). MenuNode.defaults is meant for
documentation generation.
selects:
Like MenuNode.defaults, for selects.
implies:
Like MenuNode.defaults, for implies.
ranges:
Like MenuNode.defaults, for ranges.
help:
The help text for the menu node for Symbols and Choices. None if there is
no help text. Always stored in the node rather than the Symbol or Choice.
It is possible to have a separate help text at each location if a symbol
is defined in multiple locations.
Trailing whitespace (including a final newline) is stripped from the help
text. This was not the case before Kconfiglib 10.21.0, where the format
was undocumented.
dep:
The 'depends on' dependencies for the menu node, or self.kconfig.y if
there are no dependencies. Parent dependencies are propagated to this
attribute, and this attribute is then in turn propagated to the
properties of symbols and choices.
If a symbol or choice is defined in multiple locations, only the
properties defined at a particular location get the corresponding
MenuNode.dep dependencies propagated to them.
visibility:
The 'visible if' dependencies for the menu node (which must represent a
menu), or self.kconfig.y if there are no 'visible if' dependencies.
'visible if' dependencies are recursively propagated to the prompts of
symbols and choices within the menu.
referenced:
A set() with all symbols and choices referenced in the properties and
property conditions of the menu node.
Also includes dependencies inherited from surrounding menus and if's.
Choices appear in the dependencies of choice symbols.
is_menuconfig:
Set to True if the children of the menu node should be displayed in a
separate menu. This is the case for the following items:
- Menus (node.item == MENU)
- Choices
- Symbols defined with the 'menuconfig' keyword. The children come from
implicitly created submenus, and should be displayed in a separate
menu rather than being indented.
'is_menuconfig' is just a hint on how to display the menu node. It's
ignored internally by Kconfiglib, except when printing symbols.
filename/linenr:
The location where the menu node appears. The filename is relative to
$srctree (or to the current directory if $srctree isn't set), except
absolute paths passed to 'source' and Kconfig.__init__() are preserved.
include_path:
A tuple of (filename, linenr) tuples, giving the locations of the
'source' statements via which the Kconfig file containing this menu node
was included. The first element is the location of the 'source' statement
in the top-level Kconfig file passed to Kconfig.__init__(), etc.
Note that the Kconfig file of the menu node itself isn't included. Check
'filename' and 'linenr' for that.
kconfig:
The Kconfig instance the menu node is from.
"""
__slots__ = (
"dep",
"filename",
"help",
"include_path",
"is_menuconfig",
"item",
"kconfig",
"linenr",
"list",
"next",
"parent",
"prompt",
"visibility",
# Properties
"defaults",
"selects",
"implies",
"ranges",
)
def __init__(self):
# Properties defined on this particular menu node. A local 'depends on'
# only applies to these, in case a symbol is defined in multiple
# locations.
self.defaults = []
self.selects = []
self.implies = []
self.ranges = []
@property
def referenced(self):
"""
See the class documentation.
"""
# self.dep is included to catch dependencies from a lone 'depends on'
# when there are no properties to propagate it to
res = expr_items(self.dep)
if self.prompt:
res |= expr_items(self.prompt[1])
if self.item is MENU:
res |= expr_items(self.visibility)
for value, cond in self.defaults:
res |= expr_items(value)
res |= expr_items(cond)
for value, cond in self.selects:
res.add(value)
res |= expr_items(cond)
for value, cond in self.implies:
res.add(value)
res |= expr_items(cond)
for low, high, cond in self.ranges:
res.add(low)
res.add(high)
res |= expr_items(cond)
return res
def __repr__(self):
"""
Returns a string with information about the menu node when it is
evaluated on e.g. the interactive Python prompt.
"""
fields = []
if isinstance(self.item, Symbol):
fields.append("menu node for symbol " + self.item.name)
elif isinstance(self.item, Choice):
s = "menu node for choice"
if self.item.name is not None:
s += " " + self.item.name
fields.append(s)
elif self.item is MENU:
fields.append("menu node for menu")
elif self.item is COMMENT:
fields.append("menu node for comment")
elif not self.item:
fields.append("menu node for if (should not appear in the final "
" tree)")
else:
_internal_error("unable to determine type in MenuNode.__repr__()")
if self.prompt:
fields.append('prompt "{}" (visibility {})'
.format(self.prompt[0],
TRI_TO_STR[expr_value(self.prompt[1])]))
if isinstance(self.item, Symbol) and self.is_menuconfig:
fields.append("is menuconfig")
fields.append("deps " + TRI_TO_STR[expr_value(self.dep)])
if self.item is MENU:
fields.append("'visible if' deps " +
TRI_TO_STR[expr_value(self.visibility)])
if isinstance(self.item, (Symbol, Choice)) and self.help is not None:
fields.append("has help")
if self.list:
fields.append("has child")
if self.next:
fields.append("has next")
fields.append("{}:{}".format(self.filename, self.linenr))
return "<{}>".format(", ".join(fields))
def __str__(self):
"""
Returns a string representation of the menu node, matching the Kconfig
format.
The output could (almost) be fed back into a Kconfig parser to redefine
the object associated with the menu node. See the module documentation
for a gotcha related to choice symbols.
For symbols and choices with multiple menu nodes (multiple definition
locations), properties that aren't associated with a particular menu
node are shown on all menu nodes ('option env=...', 'optional' for
choices, etc.).
The returned string does not end in a newline.
"""
return self.custom_str(standard_sc_expr_str)
def custom_str(self, sc_expr_str_fn):
"""
Works like MenuNode.__str__(), but allows a custom format to be used
for all symbol/choice references. See expr_str().
"""
return self._menu_comment_node_str(sc_expr_str_fn) \
if self.item in (MENU, COMMENT) else \
self._sym_choice_node_str(sc_expr_str_fn)
def _menu_comment_node_str(self, sc_expr_str_fn):
s = '{} "{}"'.format("menu" if self.item is MENU else "comment",
self.prompt[0])
if self.dep is not self.kconfig.y:
s += "\n\tdepends on {}".format(expr_str(self.dep, sc_expr_str_fn))
if self.item is MENU and self.visibility is not self.kconfig.y:
s += "\n\tvisible if {}".format(expr_str(self.visibility,
sc_expr_str_fn))
return s
def _sym_choice_node_str(self, sc_expr_str_fn):
lines = []
def indent_add(s):
lines.append("\t" + s)
def indent_add_cond(s, cond):
if cond is not self.kconfig.y:
s += " if " + expr_str(cond, sc_expr_str_fn)
indent_add(s)
sc = self.item
if isinstance(sc, Symbol):
lines.append(
("menuconfig " if self.is_menuconfig else "config ")
+ sc.name)
else:
lines.append("choice " + sc.name if sc.name else "choice")
if sc.orig_type: # != UNKNOWN
indent_add(TYPE_TO_STR[sc.orig_type])
if self.prompt:
indent_add_cond(
'prompt "{}"'.format(escape(self.prompt[0])),
self.prompt[1])
if isinstance(sc, Symbol):
if sc.is_allnoconfig_y:
indent_add("option allnoconfig_y")
if sc is sc.kconfig.defconfig_list:
indent_add("option defconfig_list")
if sc.env_var is not None:
indent_add('option env="{}"'.format(sc.env_var))
if sc is sc.kconfig.modules:
indent_add("option modules")
for low, high, cond in self.ranges:
indent_add_cond(
"range {} {}".format(sc_expr_str_fn(low),
sc_expr_str_fn(high)),
cond)
for default, cond in self.defaults:
indent_add_cond("default " + expr_str(default, sc_expr_str_fn),
cond)
if isinstance(sc, Choice) and sc.is_optional:
indent_add("optional")
if isinstance(sc, Symbol):
for select, cond in self.selects:
indent_add_cond("select " + sc_expr_str_fn(select), cond)
for imply, cond in self.implies:
indent_add_cond("imply " + sc_expr_str_fn(imply), cond)
if self.dep is not sc.kconfig.y:
indent_add("depends on " + expr_str(self.dep, sc_expr_str_fn))
if self.help is not None:
indent_add("help")
for line in self.help.splitlines():
indent_add(" " + line)
return "\n".join(lines)
class Variable(object):
"""
Represents a preprocessor variable/function.
The following attributes are available:
name:
The name of the variable.
value:
The unexpanded value of the variable.
expanded_value:
The expanded value of the variable. For simple variables (those defined
with :=), this will equal 'value'. Accessing this property will raise a
KconfigError if the expansion seems to be stuck in a loop.
Note: Accessing this field is the same as calling expanded_value_w_args()
with no arguments. I hadn't considered function arguments when adding it.
It is retained for backwards compatibility though.
is_recursive:
True if the variable is recursive (defined with =).
"""
__slots__ = (
"_n_expansions",
"is_recursive",
"kconfig",
"name",
"value",
)
@property
def expanded_value(self):
"""
See the class documentation.
"""
return self.expanded_value_w_args()
def expanded_value_w_args(self, *args):
"""
Returns the expanded value of the variable/function. Any arguments
passed will be substituted for $(1), $(2), etc.
Raises a KconfigError if the expansion seems to be stuck in a loop.
"""
return self.kconfig._fn_val((self.name,) + args)
def __repr__(self):
return "<variable {}, {}, value '{}'>" \
.format(self.name,
"recursive" if self.is_recursive else "immediate",
self.value)
class KconfigError(Exception):
"Exception raised for Kconfig-related errors"
KconfigSyntaxError = KconfigError # Backwards compatibility
class InternalError(Exception):
"Exception raised for internal errors"
# Workaround:
#
# If 'errno' and 'strerror' are set on IOError, then __str__() always returns
# "[Errno <errno>] <strerror>", ignoring any custom message passed to the
# constructor. By defining our own subclass, we can use a custom message while
# also providing 'errno', 'strerror', and 'filename' to scripts.
class _KconfigIOError(IOError):
def __init__(self, ioerror, msg):
self.msg = msg
super(_KconfigIOError, self).__init__(
ioerror.errno, ioerror.strerror, ioerror.filename)
def __str__(self):
return self.msg
#
# Public functions
#
def expr_value(expr):
"""
Evaluates the expression 'expr' to a tristate value. Returns 0 (n), 1 (m),
or 2 (y).
'expr' must be an already-parsed expression from a Symbol, Choice, or
MenuNode property. To evaluate an expression represented as a string, use
Kconfig.eval_string().
Passing subexpressions of expressions to this function works as expected.
"""
if not isinstance(expr, tuple):
return expr.tri_value
if expr[0] is AND:
v1 = expr_value(expr[1])
# Short-circuit the n case as an optimization (~5% faster
# allnoconfig.py and allyesconfig.py, as of writing)
return 0 if not v1 else min(v1, expr_value(expr[2]))
if expr[0] is OR:
v1 = expr_value(expr[1])
# Short-circuit the y case as an optimization
return 2 if v1 == 2 else max(v1, expr_value(expr[2]))
if expr[0] is NOT:
return 2 - expr_value(expr[1])
if expr[0] in _RELATIONS:
# Implements <, <=, >, >= comparisons as well. These were added to
# kconfig in 31847b67 (kconfig: allow use of relations other than
# (in)equality).
rel, v1, v2 = expr
# If both operands are strings...
if v1.orig_type is STRING and v2.orig_type is STRING:
# ...then compare them lexicographically
comp = _strcmp(v1.str_value, v2.str_value)
else:
# Otherwise, try to compare them as numbers
try:
comp = _sym_to_num(v1) - _sym_to_num(v2)
except ValueError:
# Fall back on a lexicographic comparison if the operands don't
# parse as numbers
comp = _strcmp(v1.str_value, v2.str_value)
if rel is EQUAL: return 2*(comp == 0)
if rel is UNEQUAL: return 2*(comp != 0)
if rel is LESS: return 2*(comp < 0)
if rel is LESS_EQUAL: return 2*(comp <= 0)
if rel is GREATER: return 2*(comp > 0)
if rel is GREATER_EQUAL: return 2*(comp >= 0)
_internal_error("Internal error while evaluating expression: "
"unknown operation {}.".format(expr[0]))
def standard_sc_expr_str(sc):
"""
Standard symbol/choice printing function. Uses plain Kconfig syntax, and
displays choices as <choice> (or <choice NAME>, for named choices).
See expr_str().
"""
if isinstance(sc, Symbol):
return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.name
# Choice
return "<choice {}>".format(sc.name) if sc.name else "<choice>"
def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
"""
Returns the string representation of the expression 'expr', as in a Kconfig
file.
Passing subexpressions of expressions to this function works as expected.
sc_expr_str_fn (default: standard_sc_expr_str):
This function is called for every symbol/choice (hence "sc") appearing in
the expression, with the symbol/choice as the argument. It is expected to
return a string to be used for the symbol/choice.
This can be used e.g. to turn symbols/choices into links when generating
documentation, or for printing the value of each symbol/choice after it.
Note that quoted values are represented as constants symbols
(Symbol.is_constant == True).
"""
if not isinstance(expr, tuple):
return sc_expr_str_fn(expr)
if expr[0] is AND:
return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
_parenthesize(expr[2], OR, sc_expr_str_fn))
if expr[0] is OR:
# This turns A && B || C && D into "(A && B) || (C && D)", which is
# redundant, but more readable
return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
_parenthesize(expr[2], AND, sc_expr_str_fn))
if expr[0] is NOT:
if isinstance(expr[1], tuple):
return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
return "!" + sc_expr_str_fn(expr[1]) # Symbol
# Relation
#
# Relation operands are always symbols (quoted strings are constant
# symbols)
return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
sc_expr_str_fn(expr[2]))
def expr_items(expr):
"""
Returns a set() of all items (symbols and choices) that appear in the
expression 'expr'.
"""
res = set()
def rec(subexpr):
if isinstance(subexpr, tuple):
# AND, OR, NOT, or relation
rec(subexpr[1])
# NOTs only have a single operand
if subexpr[0] is not NOT:
rec(subexpr[2])
else:
# Symbol or choice
res.add(subexpr)
rec(expr)
return res
def split_expr(expr, op):
"""
Returns a list containing the top-level AND or OR operands in the
expression 'expr', in the same (left-to-right) order as they appear in
the expression.
This can be handy e.g. for splitting (weak) reverse dependencies
from 'select' and 'imply' into individual selects/implies.
op:
Either AND to get AND operands, or OR to get OR operands.
(Having this as an operand might be more future-safe than having two
hardcoded functions.)
Pseudo-code examples:
split_expr( A , OR ) -> [A]
split_expr( A && B , OR ) -> [A && B]
split_expr( A || B , OR ) -> [A, B]
split_expr( A || B , AND ) -> [A || B]
split_expr( A || B || (C && D) , OR ) -> [A, B, C && D]
# Second || is not at the top level
split_expr( A || (B && (C || D)) , OR ) -> [A, B && (C || D)]
# Parentheses don't matter as long as we stay at the top level (don't
# encounter any non-'op' nodes)
split_expr( (A || B) || C , OR ) -> [A, B, C]
split_expr( A || (B || C) , OR ) -> [A, B, C]
"""
res = []
def rec(subexpr):
if isinstance(subexpr, tuple) and subexpr[0] is op:
rec(subexpr[1])
rec(subexpr[2])
else:
res.append(subexpr)
rec(expr)
return res
def escape(s):
r"""
Escapes the string 's' in the same fashion as is done for display in
Kconfig format and when writing strings to a .config file. " and \ are
replaced by \" and \\, respectively.
"""
# \ must be escaped before " to avoid double escaping
return s.replace("\\", r"\\").replace('"', r'\"')
# unescape() helper
_unescape_sub = re.compile(r"\\(.)").sub
def unescape(s):
r"""
Unescapes the string 's'. \ followed by any character is replaced with just
that character. Used internally when reading .config files.
"""
return _unescape_sub(r"\1", s)
def standard_kconfig():
"""
Helper for tools. Loads the top-level Kconfig specified as the first
command-line argument, or "Kconfig" if there are no command-line arguments.
Returns the Kconfig instance.
Exits with sys.exit() (which raises a SystemExit exception) and prints a
usage note to stderr if more than one command-line argument is passed.
"""
if len(sys.argv) > 2:
sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
# Only show backtraces for unexpected exceptions
try:
return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
except (IOError, KconfigError) as e:
# Some long exception messages have extra newlines for better
# formatting when reported as an unhandled exception. Strip them here.
sys.exit(str(e).strip())
def standard_config_filename():
"""
Helper for tools. Returns the value of KCONFIG_CONFIG (which specifies the
.config file to load/save) if it is set, and ".config" otherwise.
"""
return os.environ.get("KCONFIG_CONFIG", ".config")
#
# Internal functions
#
def _visibility(sc):
# Symbols and Choices have a "visibility" that acts as an upper bound on
# the values a user can set for them, corresponding to the visibility in
# e.g. 'make menuconfig'. This function calculates the visibility for the
# Symbol or Choice 'sc' -- the logic is nearly identical.
vis = 0
for node in sc.nodes:
if node.prompt:
vis = max(vis, expr_value(node.prompt[1]))
if isinstance(sc, Symbol) and sc.choice:
if sc.choice.orig_type is TRISTATE and \
sc.orig_type is not TRISTATE and sc.choice.tri_value != 2:
# Non-tristate choice symbols are only visible in y mode
return 0
if sc.orig_type is TRISTATE and vis == 1 and sc.choice.tri_value == 2:
# Choice symbols with m visibility are not visible in y mode
return 0
# Promote m to y if we're dealing with a non-tristate (possibly due to
# modules being disabled)
if vis == 1 and sc.type is not TRISTATE:
return 2
return vis
def _make_depend_on(sc, expr):
# Adds 'sc' (symbol or choice) as a "dependee" to all symbols in 'expr'.
# Constant symbols in 'expr' are skipped as they can never change value
# anyway.
if isinstance(expr, tuple):
# AND, OR, NOT, or relation
_make_depend_on(sc, expr[1])
# NOTs only have a single operand
if expr[0] is not NOT:
_make_depend_on(sc, expr[2])
elif not expr.is_constant:
# Non-constant symbol, or choice
expr._dependents.add(sc)
def _parenthesize(expr, type_, sc_expr_str_fn):
# expr_str() helper. Adds parentheses around expressions of type 'type_'.
if isinstance(expr, tuple) and expr[0] is type_:
return "({})".format(expr_str(expr, sc_expr_str_fn))
return expr_str(expr, sc_expr_str_fn)
def _indentation(line):
# Returns the length of the line's leading whitespace, treating tab stops
# as being spaced 8 characters apart.
line = line.expandtabs()
return len(line) - len(line.lstrip())
def _ordered_unique(lst):
# Returns 'lst' with any duplicates removed, preserving order. This hacky
# version seems to be a common idiom. It relies on short-circuit evaluation
# and set.add() returning None, which is falsy.
seen = set()
seen_add = seen.add
return [x for x in lst if x not in seen and not seen_add(x)]
def _is_base_n(s, n):
try:
int(s, n)
return True
except ValueError:
return False
def _strcmp(s1, s2):
# strcmp()-alike that returns -1, 0, or 1
return (s1 > s2) - (s1 < s2)
def _sym_to_num(sym):
# expr_value() helper for converting a symbol to a number. Raises
# ValueError for symbols that can't be converted.
# For BOOL and TRISTATE, n/m/y count as 0/1/2. This mirrors 9059a3493ef
# ("kconfig: fix relational operators for bool and tristate symbols") in
# the C implementation.
return sym.tri_value if sym.orig_type in (BOOL, TRISTATE) else \
int(sym.str_value, _TYPE_TO_BASE[sym.orig_type])
def _internal_error(msg):
raise InternalError(
msg +
"\nSorry! You may want to send an email to ulfalizer a.t Google's "
"email service to tell me about this. Include the message above and "
"the stack trace and describe what you were doing.")
def _decoding_error(e, filename, macro_linenr=None):
# Gives the filename and context for UnicodeDecodeError's, which are a pain
# to debug otherwise. 'e' is the UnicodeDecodeError object.
#
# If the decoding error is for the output of a $(shell,...) command,
# macro_linenr holds the line number where it was run (the exact line
# number isn't available for decoding errors in files).
if macro_linenr is None:
loc = filename
else:
loc = "output from macro at {}:{}".format(filename, macro_linenr)
raise KconfigError(
"\n"
"Malformed {} in {}\n"
"Context: {}\n"
"Problematic data: {}\n"
"Reason: {}".format(
e.encoding, loc,
e.object[max(e.start - 40, 0):e.end + 40],
e.object[e.start:e.end],
e.reason))
def _name_and_loc(sc):
# Helper for giving the symbol/choice name and location(s) in e.g. warnings
# Reuse the expression format. That way choices show up as
# '<choice (name, if any)>'
name = standard_sc_expr_str(sc)
if not sc.nodes:
return name + " (undefined)"
return "{} (defined at {})".format(
name,
", ".join("{}:{}".format(node.filename, node.linenr)
for node in sc.nodes))
# Menu manipulation
def _expr_depends_on(expr, sym):
# Reimplementation of expr_depends_symbol() from mconf.c. Used to determine
# if a submenu should be implicitly created. This also influences which
# items inside choice statements are considered choice items.
if not isinstance(expr, tuple):
return expr is sym
if expr[0] in (EQUAL, UNEQUAL):
# Check for one of the following:
# sym = m/y, m/y = sym, sym != n, n != sym
left, right = expr[1:]
if right is sym:
left, right = right, left
elif left is not sym:
return False
return (expr[0] is EQUAL and right is sym.kconfig.m or
right is sym.kconfig.y) or \
(expr[0] is UNEQUAL and right is sym.kconfig.n)
return expr[0] is AND and \
(_expr_depends_on(expr[1], sym) or
_expr_depends_on(expr[2], sym))
def _auto_menu_dep(node1, node2):
# Returns True if node2 has an "automatic menu dependency" on node1. If
# node2 has a prompt, we check its condition. Otherwise, we look directly
# at node2.dep.
# If node2 has no prompt, use its menu node dependencies instead
return _expr_depends_on(node2.prompt[1] if node2.prompt else node2.dep,
node1.item)
def _flatten(node):
# "Flattens" menu nodes without prompts (e.g. 'if' nodes and non-visible
# symbols with children from automatic menu creation) so that their
# children appear after them instead. This gives a clean menu structure
# with no unexpected "jumps" in the indentation.
#
# Do not flatten promptless choices (which can appear "legitimitely" if a
# named choice is defined in multiple locations to add on symbols). It
# looks confusing, and the menuconfig already shows all choice symbols if
# you enter the choice at some location with a prompt.
while node:
if node.list and not node.prompt and \
not isinstance(node.item, Choice):
last_node = node.list
while 1:
last_node.parent = node.parent
if not last_node.next:
break
last_node = last_node.next
last_node.next = node.next
node.next = node.list
node.list = None
node = node.next
def _remove_ifs(node):
# Removes 'if' nodes (which can be recognized by MenuNode.item being None),
# which are assumed to already have been flattened. The C implementation
# doesn't bother to do this, but we expose the menu tree directly, and it
# makes it nicer to work with.
cur = node.list
while cur and not cur.item:
cur = cur.next
node.list = cur
while cur:
next = cur.next
while next and not next.item:
next = next.next
# Equivalent to
#
# cur.next = next
# cur = next
#
# due to tricky Python semantics. The order matters.
cur.next = cur = next
def _finalize_choice(node):
# Finalizes a choice, marking each symbol whose menu node has the choice as
# the parent as a choice symbol, and automatically determining types if not
# specified.
choice = node.item
cur = node.list
while cur:
if isinstance(cur.item, Symbol):
cur.item.choice = choice
choice.syms.append(cur.item)
cur = cur.next
# If no type is specified for the choice, its type is that of
# the first choice item with a specified type
if not choice.orig_type:
for item in choice.syms:
if item.orig_type:
choice.orig_type = item.orig_type
break
# Each choice item of UNKNOWN type gets the type of the choice
for sym in choice.syms:
if not sym.orig_type:
sym.orig_type = choice.orig_type
def _check_dep_loop_sym(sym, ignore_choice):
# Detects dependency loops using depth-first search on the dependency graph
# (which is calculated earlier in Kconfig._build_dep()).
#
# Algorithm:
#
# 1. Symbols/choices start out with _visited = 0, meaning unvisited.
#
# 2. When a symbol/choice is first visited, _visited is set to 1, meaning
# "visited, potentially part of a dependency loop". The recursive
# search then continues from the symbol/choice.
#
# 3. If we run into a symbol/choice X with _visited already set to 1,
# there's a dependency loop. The loop is found on the call stack by
# recording symbols while returning ("on the way back") until X is seen
# again.
#
# 4. Once a symbol/choice and all its dependencies (or dependents in this
# case) have been checked recursively without detecting any loops, its
# _visited is set to 2, meaning "visited, not part of a dependency
# loop".
#
# This saves work if we run into the symbol/choice again in later calls
# to _check_dep_loop_sym(). We just return immediately.
#
# Choices complicate things, as every choice symbol depends on every other
# choice symbol in a sense. When a choice is "entered" via a choice symbol
# X, we visit all choice symbols from the choice except X, and prevent
# immediately revisiting the choice with a flag (ignore_choice).
#
# Maybe there's a better way to handle this (different flags or the
# like...)
if not sym._visited:
# sym._visited == 0, unvisited
sym._visited = 1
for dep in sym._dependents:
# Choices show up in Symbol._dependents when the choice has the
# symbol in a 'prompt' or 'default' condition (e.g.
# 'default ... if SYM').
#
# Since we aren't entering the choice via a choice symbol, all
# choice symbols need to be checked, hence the None.
loop = _check_dep_loop_choice(dep, None) \
if isinstance(dep, Choice) \
else _check_dep_loop_sym(dep, False)
if loop:
# Dependency loop found
return _found_dep_loop(loop, sym)
if sym.choice and not ignore_choice:
loop = _check_dep_loop_choice(sym.choice, sym)
if loop:
# Dependency loop found
return _found_dep_loop(loop, sym)
# The symbol is not part of a dependency loop
sym._visited = 2
# No dependency loop found
return None
if sym._visited == 2:
# The symbol was checked earlier and is already known to not be part of
# a dependency loop
return None
# sym._visited == 1, found a dependency loop. Return the symbol as the
# first element in it.
return (sym,)
def _check_dep_loop_choice(choice, skip):
if not choice._visited:
# choice._visited == 0, unvisited
choice._visited = 1
# Check for loops involving choice symbols. If we came here via a
# choice symbol, skip that one, as we'd get a false positive
# '<sym FOO> -> <choice> -> <sym FOO>' loop otherwise.
for sym in choice.syms:
if sym is not skip:
# Prevent the choice from being immediately re-entered via the
# "is a choice symbol" path by passing True
loop = _check_dep_loop_sym(sym, True)
if loop:
# Dependency loop found
return _found_dep_loop(loop, choice)
# The choice is not part of a dependency loop
choice._visited = 2
# No dependency loop found
return None
if choice._visited == 2:
# The choice was checked earlier and is already known to not be part of
# a dependency loop
return None
# choice._visited == 1, found a dependency loop. Return the choice as the
# first element in it.
return (choice,)
def _found_dep_loop(loop, cur):
# Called "on the way back" when we know we have a loop
# Is the symbol/choice 'cur' where the loop started?
if cur is not loop[0]:
# Nope, it's just a part of the loop
return loop + (cur,)
# Yep, we have the entire loop. Throw an exception that shows it.
msg = "\nDependency loop\n" \
"===============\n\n"
for item in loop:
if item is not loop[0]:
msg += "...depends on "
if isinstance(item, Symbol) and item.choice:
msg += "the choice symbol "
msg += "{}, with definition...\n\n{}\n\n" \
.format(_name_and_loc(item), item)
# Small wart: Since we reuse the already calculated
# Symbol/Choice._dependents sets for recursive dependency detection, we
# lose information on whether a dependency came from a 'select'/'imply'
# condition or e.g. a 'depends on'.
#
# This might cause selecting symbols to "disappear". For example,
# a symbol B having 'select A if C' gives a direct dependency from A to
# C, since it corresponds to a reverse dependency of B && C.
#
# Always print reverse dependencies for symbols that have them to make
# sure information isn't lost. I wonder if there's some neat way to
# improve this.
if isinstance(item, Symbol):
if item.rev_dep is not item.kconfig.n:
msg += "(select-related dependencies: {})\n\n" \
.format(expr_str(item.rev_dep))
if item.weak_rev_dep is not item.kconfig.n:
msg += "(imply-related dependencies: {})\n\n" \
.format(expr_str(item.rev_dep))
msg += "...depends again on {}".format(_name_and_loc(loop[0]))
raise KconfigError(msg)
# Predefined preprocessor functions
def _filename_fn(kconf, _):
return kconf._filename
def _lineno_fn(kconf, _):
return str(kconf._linenr)
def _info_fn(kconf, _, msg):
print("{}:{}: {}".format(kconf._filename, kconf._linenr, msg))
return ""
def _warning_if_fn(kconf, _, cond, msg):
if cond == "y":
kconf._warn(msg, kconf._filename, kconf._linenr)
return ""
def _error_if_fn(kconf, _, cond, msg):
if cond == "y":
raise KconfigError("{}:{}: {}".format(
kconf._filename, kconf._linenr, msg))
return ""
def _shell_fn(kconf, _, command):
stdout, stderr = subprocess.Popen(
command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).communicate()
if not _IS_PY2:
try:
stdout = stdout.decode(kconf._encoding)
stderr = stderr.decode(kconf._encoding)
except UnicodeDecodeError as e:
_decoding_error(e, kconf._filename, kconf._linenr)
if stderr:
kconf._warn("'{}' wrote to stderr: {}".format(
command, "\n".join(stderr.splitlines())),
kconf._filename, kconf._linenr)
# Universal newlines with splitlines() (to prevent e.g. stray \r's in
# command output on Windows), trailing newline removal, and
# newline-to-space conversion.
#
# On Python 3 versions before 3.6, it's not possible to specify the
# encoding when passing universal_newlines=True to Popen() (the 'encoding'
# parameter was added in 3.6), so we do this manual version instead.
return "\n".join(stdout.splitlines()).rstrip("\n").replace("\n", " ")
#
# Public global constants
#
# Integers representing symbol types. UNKNOWN is 0 (falsy) to simplify some
# checks, though client code shouldn't rely on it (it was non-zero in older
# versions).
(
UNKNOWN,
BOOL,
TRISTATE,
STRING,
INT,
HEX,
) = range(6)
# Converts a symbol/choice type to a string
TYPE_TO_STR = {
UNKNOWN: "unknown",
BOOL: "bool",
TRISTATE: "tristate",
STRING: "string",
INT: "int",
HEX: "hex",
}
TRI_TO_STR = {
0: "n",
1: "m",
2: "y",
}
STR_TO_TRI = {
"n": 0,
"m": 1,
"y": 2,
}
#
# Internal global constants (plus public expression type
# constants)
#
# Note:
#
# The token and type constants below are safe to test with 'is', which is a bit
# faster (~30% faster in a microbenchmark with Python 3 on my machine, and a
# few % faster for total parsing time), even without assuming Python's small
# integer optimization (which caches small integer objects). The constants end
# up pointing to unique integer objects, and since we consistently refer to
# them via the names below, we always get the same object.
#
# Client code would also need to use the names below, because the integer
# values can change e.g. when tokens get added. Client code would usually test
# with == too, which would be safe even in super obscure cases involving e.g.
# pickling (where 'is' would be a bad idea anyway) and no small-integer
# optimization.
# Are we running on Python 2?
_IS_PY2 = sys.version_info[0] < 3
# Tokens, with values 1, 2, ... . Avoiding 0 simplifies some checks by making
# all tokens except empty strings truthy.
(
_T_ALLNOCONFIG_Y,
_T_AND,
_T_BOOL,
_T_CHOICE,
_T_CLOSE_PAREN,
_T_COMMENT,
_T_CONFIG,
_T_DEFAULT,
_T_DEFCONFIG_LIST,
_T_DEF_BOOL,
_T_DEF_HEX,
_T_DEF_INT,
_T_DEF_STRING,
_T_DEF_TRISTATE,
_T_DEPENDS,
_T_ENDCHOICE,
_T_ENDIF,
_T_ENDMENU,
_T_ENV,
_T_EQUAL,
_T_GREATER,
_T_GREATER_EQUAL,
_T_HELP,
_T_HEX,
_T_IF,
_T_IMPLY,
_T_INT,
_T_LESS,
_T_LESS_EQUAL,
_T_MAINMENU,
_T_MENU,
_T_MENUCONFIG,
_T_MODULES,
_T_NOT,
_T_ON,
_T_OPEN_PAREN,
_T_OPTION,
_T_OPTIONAL,
_T_OR,
_T_ORSOURCE,
_T_OSOURCE,
_T_PROMPT,
_T_RANGE,
_T_RSOURCE,
_T_SELECT,
_T_SOURCE,
_T_STRING,
_T_TRISTATE,
_T_UNEQUAL,
_T_VISIBLE,
) = range(1, 51)
# Public integers representing expression types and menu and comment menu
# nodes
#
# Having these match the value of the corresponding tokens removes the need
# for conversion
AND = _T_AND
OR = _T_OR
NOT = _T_NOT
EQUAL = _T_EQUAL
UNEQUAL = _T_UNEQUAL
LESS = _T_LESS
LESS_EQUAL = _T_LESS_EQUAL
GREATER = _T_GREATER
GREATER_EQUAL = _T_GREATER_EQUAL
MENU = _T_MENU
COMMENT = _T_COMMENT
# Keyword to token map, with the get() method assigned directly as a small
# optimization
_get_keyword = {
"---help---": _T_HELP,
"allnoconfig_y": _T_ALLNOCONFIG_Y,
"bool": _T_BOOL,
"boolean": _T_BOOL,
"choice": _T_CHOICE,
"comment": _T_COMMENT,
"config": _T_CONFIG,
"def_bool": _T_DEF_BOOL,
"def_hex": _T_DEF_HEX,
"def_int": _T_DEF_INT,
"def_string": _T_DEF_STRING,
"def_tristate": _T_DEF_TRISTATE,
"default": _T_DEFAULT,
"defconfig_list": _T_DEFCONFIG_LIST,
"depends": _T_DEPENDS,
"endchoice": _T_ENDCHOICE,
"endif": _T_ENDIF,
"endmenu": _T_ENDMENU,
"env": _T_ENV,
"grsource": _T_ORSOURCE, # Backwards compatibility
"gsource": _T_OSOURCE, # Backwards compatibility
"help": _T_HELP,
"hex": _T_HEX,
"if": _T_IF,
"imply": _T_IMPLY,
"int": _T_INT,
"mainmenu": _T_MAINMENU,
"menu": _T_MENU,
"menuconfig": _T_MENUCONFIG,
"modules": _T_MODULES,
"on": _T_ON,
"option": _T_OPTION,
"optional": _T_OPTIONAL,
"orsource": _T_ORSOURCE,
"osource": _T_OSOURCE,
"prompt": _T_PROMPT,
"range": _T_RANGE,
"rsource": _T_RSOURCE,
"select": _T_SELECT,
"source": _T_SOURCE,
"string": _T_STRING,
"tristate": _T_TRISTATE,
"visible": _T_VISIBLE,
}.get
# Tokens after which strings are expected. This is used to tell strings from
# constant symbol references during tokenization, both of which are enclosed in
# quotes.
#
# Identifier-like lexemes ("missing quotes") are also treated as strings after
# these tokens. _T_CHOICE is included to avoid symbols being registered for
# named choices.
_STRING_LEX = frozenset((
_T_BOOL,
_T_CHOICE,
_T_COMMENT,
_T_HEX,
_T_INT,
_T_MAINMENU,
_T_MENU,
_T_ORSOURCE,
_T_OSOURCE,
_T_PROMPT,
_T_RSOURCE,
_T_SOURCE,
_T_STRING,
_T_TRISTATE,
))
# Tokens for types, excluding def_bool, def_tristate, etc., for quick
# checks during parsing
_TYPE_TOKENS = frozenset((
_T_BOOL,
_T_TRISTATE,
_T_INT,
_T_HEX,
_T_STRING,
))
# Helper functions for getting compiled regular expressions, with the needed
# matching function returned directly as a small optimization.
#
# Use ASCII regex matching on Python 3. It's already the default on Python 2.
def _re_match(regex):
return re.compile(regex, 0 if _IS_PY2 else re.ASCII).match
def _re_search(regex):
return re.compile(regex, 0 if _IS_PY2 else re.ASCII).search
# Various regular expressions used during parsing
# The initial token on a line. Also eats leading and trailing whitespace, so
# that we can jump straight to the next token (or to the end of the line if
# there is only one token).
#
# This regex will also fail to match for empty lines and comment lines.
#
# '$' is included to detect preprocessor variable assignments with macro
# expansions in the left-hand side.
_command_match = _re_match(r"\s*([$A-Za-z0-9_-]+)\s*")
# An identifier/keyword after the first token. Also eats trailing whitespace.
# '$' is included to detect identifiers containing macro expansions.
_id_keyword_match = _re_match(r"([$A-Za-z0-9_/.-]+)\s*")
# A fragment in the left-hand side of a preprocessor variable assignment. These
# are the portions between macro expansions ($(foo)). Macros are supported in
# the LHS (variable name).
_assignment_lhs_fragment_match = _re_match("[A-Za-z0-9_-]*")
# The assignment operator and value (right-hand side) in a preprocessor
# variable assignment
_assignment_rhs_match = _re_match(r"\s*(=|:=|\+=)\s*(.*)")
# Special characters/strings while expanding a macro (')', ',', and '$(')
_macro_special_search = _re_search(r"\)|,|\$\(")
# Special characters/strings while expanding a string (quotes, '\', and '$(')
_string_special_search = _re_search(r'"|\'|\\|\$\(')
# Special characters/strings while expanding a symbol name. Also includes
# end-of-line, in case the macro is the last thing on the line.
_name_special_search = _re_search(r'[^$A-Za-z0-9_/.-]|\$\(|$')
# A valid right-hand side for an assignment to a string symbol in a .config
# file, including escaped characters. Extracts the contents.
_conf_string_match = _re_match(r'"((?:[^\\"]|\\.)*)"')
# Token to type mapping
_TOKEN_TO_TYPE = {
_T_BOOL: BOOL,
_T_DEF_BOOL: BOOL,
_T_DEF_HEX: HEX,
_T_DEF_INT: INT,
_T_DEF_STRING: STRING,
_T_DEF_TRISTATE: TRISTATE,
_T_HEX: HEX,
_T_INT: INT,
_T_STRING: STRING,
_T_TRISTATE: TRISTATE,
}
# Constant representing that there's no cached choice selection. This is
# distinct from a cached None (no selection). We create a unique object (any
# will do) for it so we can test with 'is'.
_NO_CACHED_SELECTION = object()
# Used in comparisons. 0 means the base is inferred from the format of the
# string.
_TYPE_TO_BASE = {
HEX: 16,
INT: 10,
STRING: 0,
UNKNOWN: 0,
}
# Note: These constants deliberately equal the corresponding tokens (_T_EQUAL,
# _T_UNEQUAL, etc.), which removes the need for conversion
_RELATIONS = frozenset((
EQUAL,
UNEQUAL,
LESS,
LESS_EQUAL,
GREATER,
GREATER_EQUAL,
))
_REL_TO_STR = {
EQUAL: "=",
UNEQUAL: "!=",
LESS: "<",
LESS_EQUAL: "<=",
GREATER: ">",
GREATER_EQUAL: ">=",
}
_INIT_SRCTREE_NOTE = """\
NOTE: Starting with Kconfiglib 10.0.0, the Kconfig filename passed to
Kconfig.__init__() is looked up relative to $srctree (which is set to '{}')
instead of relative to the working directory. Previously, $srctree only applied
to files being source'd within Kconfig files. This change makes running scripts
out-of-tree work seamlessly, with no special coding required. Sorry for the
backwards compatibility break!
"""
| YifuLiu/AliOS-Things | components/ble_host/script/Kconfiglib-10.21.0/kconfiglib.py | Python | apache-2.0 | 234,390 |
#!/usr/bin/env python3
# Copyright (c) 2018, Nordic Semiconductor ASA and Ulf Magnusson
# SPDX-License-Identifier: ISC
"""
Overview
========
A curses-based menuconfig implementation. The interface should feel familiar to
people used to mconf ('make menuconfig').
Supports the same keys as mconf, and also supports a set of keybindings
inspired by Vi:
J/K : Down/Up
L : Enter menu/Toggle item
H : Leave menu
Ctrl-D/U: Page Down/Page Up
G/End : Jump to end of list
g/Home : Jump to beginning of list
The mconf feature where pressing a key jumps to a menu entry with that
character in it in the current menu isn't supported. A jump-to feature for
jumping directly to any symbol (including invisible symbols), choice, menu or
comment (as in a Kconfig 'comment "Foo"') is available instead.
Space and Enter are "smart" and try to do what you'd expect for the given
menu entry.
Running
=======
menuconfig.py can be run either as a standalone executable or by calling the
menuconfig() function with an existing Kconfig instance. The second option is a
bit inflexible in that it will still load and save .config, etc.
When run in standalone mode, the top-level Kconfig file to load can be passed
as a command-line argument. With no argument, it defaults to "Kconfig".
The KCONFIG_CONFIG environment variable specifies the .config file to load (if
it exists) and save. If KCONFIG_CONFIG is unset, ".config" is used.
$srctree is supported through Kconfiglib.
Color schemes
=============
It is possible to customize the color scheme by setting the MENUCONFIG_STYLE
environment variable. For example, setting it to 'aquatic' will enable an
alternative, less yellow, more 'make menuconfig'-like color scheme, contributed
by Mitja Horvat (pinkfluid).
This is the current list of built-in styles:
- default classic Kconfiglib theme with a yellow accent
- monochrome colorless theme (uses only bold and standout) attributes,
this style is used if the terminal doesn't support colors
- aquatic blue tinted style loosely resembling the lxdialog theme
It is possible to customize the current style by changing colors of UI
elements on the screen. This is the list of elements that can be stylized:
- path Top row in the main display, with the menu path
- separator Separator lines between windows. Also used for the top line
in the symbol information display.
- list List of items, e.g. the main display
- selection Style for the selected item
- inv-list Like list, but for invisible items. Used in show-all mode.
- inv-selection Like selection, but for invisible items. Used in show-all
mode.
- help Help text windows at the bottom of various fullscreen
dialogs
- frame Frame around dialog boxes
- body Body of dialog boxes
- edit Edit box in pop-up dialogs
- jump-edit Edit box in jump-to dialog
- text Symbol information text
The color definition is a comma separated list of attributes:
- fg:COLOR Set the foreground/background colors. COLOR can be one of
* or * the basic 16 colors (black, red, green, yellow, blue,
- bg:COLOR magenta,cyan, white and brighter versions, for example,
brightred). On terminals that support more than 8 colors,
you can also directly put in a color number, e.g. fg:123
(hexadecimal and octal constants are accepted as well).
Colors outside the range -1..curses.COLORS-1 (which is
terminal-dependent) are ignored (with a warning). The COLOR
can be also specified using a RGB value in the HTML
notation, for example #RRGGBB. If the terminal supports
color changing, the color is rendered accurately.
Otherwise, the visually nearest color is used.
If the background or foreground color of an element is not
specified, it defaults to -1, representing the default
terminal foreground or background color.
Note: On some terminals a bright version of the color
implies bold.
- bold Use bold text
- underline Use underline text
- standout Standout text attribute (reverse color)
More often than not, some UI elements share the same color definition. In such
cases the right value may specify an UI element from which the color definition
will be copied. For example, "separator=help" will apply the current color
definition for "help" to "separator".
A keyword without the '=' is assumed to be a style template. The template name
is looked up in the built-in styles list and the style definition is expanded
in-place. With this, built-in styles can be used as basis for new styles.
For example, take the aquatic theme and give it a red selection bar:
MENUCONFIG_STYLE="aquatic selection=fg:white,bg:red"
If there's an error in the style definition or if a missing style is assigned
to, the assignment will be ignored, along with a warning being printed on
stderr.
The 'default' theme is always implicitly parsed first (or the 'monochrome'
theme if the terminal lacks colors), so the following two settings have the
same effect:
MENUCONFIG_STYLE="selection=fg:white,bg:red"
MENUCONFIG_STYLE="default selection=fg:white,bg:red"
Other features
==============
- Seamless terminal resizing
- No dependencies on *nix, as the 'curses' module is in the Python standard
library
- Unicode text entry
- Improved information screen compared to mconf:
* Expressions are split up by their top-level &&/|| operands to improve
readability
* Undefined symbols in expressions are pointed out
* Menus and comments have information displays
* Kconfig definitions are printed
* The include path is shown, listing the locations of the 'source'
statements that included the Kconfig file of the symbol (or other
item)
Limitations
===========
- Python 3 only
This is mostly due to Python 2 not having curses.get_wch(), which is needed
for Unicode support.
- Doesn't work out of the box on Windows
Has been tested to work with the wheels provided at
https://www.lfd.uci.edu/~gohlke/pythonlibs/#curses though.
"""
import curses
import errno
import locale
import os
import platform
import re
import sys
import textwrap
from kconfiglib import Symbol, Choice, MENU, COMMENT, MenuNode, \
BOOL, STRING, INT, HEX, UNKNOWN, \
AND, OR, \
expr_str, expr_value, split_expr, \
standard_sc_expr_str, \
TRI_TO_STR, TYPE_TO_STR, \
standard_kconfig, standard_config_filename
#
# Configuration variables
#
# If True, try to convert LC_CTYPE to a UTF-8 locale if it is set to the C
# locale (which implies ASCII). This fixes curses Unicode I/O issues on systems
# with bad defaults. ncurses configures itself from the locale settings.
#
# Related PEP: https://www.python.org/dev/peps/pep-0538/
_CONVERT_C_LC_CTYPE_TO_UTF8 = True
# How many steps an implicit submenu will be indented. Implicit submenus are
# created when an item depends on the symbol before it. Note that symbols
# defined with 'menuconfig' create a separate menu instead of indenting.
_SUBMENU_INDENT = 4
# Number of steps for Page Up/Down to jump
_PG_JUMP = 6
# How far the cursor needs to be from the edge of the window before it starts
# to scroll. Used for the main menu display, the information display, the
# search display, and for text boxes.
_SCROLL_OFFSET = 5
# Minimum width of dialogs that ask for text input
_INPUT_DIALOG_MIN_WIDTH = 30
# Number of arrows pointing up/down to draw when a window is scrolled
_N_SCROLL_ARROWS = 14
# Lines of help text shown at the bottom of the "main" display
_MAIN_HELP_LINES = """
[Space/Enter] Toggle/enter [ESC] Leave menu [S] Save
[O] Load [?] Symbol info [/] Jump to symbol
[A] Toggle show-all mode [C] Toggle show-name mode
[Q] Quit (prompts for save) [D] Save minimal config (advanced)
"""[1:-1].split("\n")
# Lines of help text shown at the bottom of the information dialog
_INFO_HELP_LINES = """
[ESC/q] Return to menu [/] Jump to symbol
"""[1:-1].split("\n")
# Lines of help text shown at the bottom of the search dialog
_JUMP_TO_HELP_LINES = """
Type text to narrow the search. Regexes are supported (via Python's 're'
module). The up/down cursor keys step in the list. [Enter] jumps to the
selected symbol. [ESC] aborts the search. Type multiple space-separated
strings/regexes to find entries that match all of them. Type Ctrl-F to
view the help of the selected item without leaving the dialog.
"""[1:-1].split("\n")
#
# Styling
#
_STYLES = {
"default": """
path=fg:black,bg:white,bold
separator=fg:black,bg:yellow,bold
list=fg:black,bg:white
selection=fg:white,bg:blue,bold
inv-list=fg:red,bg:white
inv-selection=fg:red,bg:blue
help=path
frame=fg:black,bg:yellow,bold
body=fg:white,bg:black
edit=fg:white,bg:blue
jump-edit=edit
text=list
""",
# This style is forced on terminals that do no support colors
"monochrome": """
path=bold
separator=bold,standout
list=
selection=bold,standout
inv-list=bold
inv-selection=bold,standout
help=bold
frame=bold,standout
body=
edit=standout
jump-edit=
text=
""",
# Blue tinted style loosely resembling lxdialog
"aquatic": """
path=fg:cyan,bg:blue,bold
separator=fg:white,bg:cyan,bold
help=path
frame=fg:white,bg:cyan,bold
body=fg:brightwhite,bg:blue
edit=fg:black,bg:white
"""
}
# Standard colors definition
_STYLE_STD_COLORS = {
# Basic colors
"black": curses.COLOR_BLACK,
"red": curses.COLOR_RED,
"green": curses.COLOR_GREEN,
"yellow": curses.COLOR_YELLOW,
"blue": curses.COLOR_BLUE,
"magenta": curses.COLOR_MAGENTA,
"cyan": curses.COLOR_CYAN,
"white": curses.COLOR_WHITE,
# Bright versions
"brightblack": curses.COLOR_BLACK + 8,
"brightred": curses.COLOR_RED + 8,
"brightgreen": curses.COLOR_GREEN + 8,
"brightyellow": curses.COLOR_YELLOW + 8,
"brightblue": curses.COLOR_BLUE + 8,
"brightmagenta": curses.COLOR_MAGENTA + 8,
"brightcyan": curses.COLOR_CYAN + 8,
"brightwhite": curses.COLOR_WHITE + 8,
# Aliases
"purple": curses.COLOR_MAGENTA,
"brightpurple": curses.COLOR_MAGENTA + 8,
}
def _rgb_to_6cube(rgb):
# Converts an 888 RGB color to a 3-tuple (nice in that it's hashable)
# representing the closests xterm 256-color 6x6x6 color cube color.
#
# The xterm 256-color extension uses a RGB color palette with components in
# the range 0-5 (a 6x6x6 cube). The catch is that the mapping is nonlinear.
# Index 0 in the 6x6x6 cube is mapped to 0, index 1 to 95, then 135, 175,
# etc., in increments of 40. See the links below:
#
# https://commons.wikimedia.org/wiki/File:Xterm_256color_chart.svg
# https://github.com/tmux/tmux/blob/master/colour.c
# 48 is the middle ground between 0 and 95.
return tuple(0 if x < 48 else int(round(max(1, (x - 55)/40))) for x in rgb)
def _6cube_to_rgb(r6g6b6):
# Returns the 888 RGB color for a 666 xterm color cube index
return tuple(0 if x == 0 else 40*x + 55 for x in r6g6b6)
def _rgb_to_gray(rgb):
# Converts an 888 RGB color to the index of an xterm 256-color grayscale
# color with approx. the same perceived brightness
# Calculate the luminance (gray intensity) of the color. See
# https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
# and
# https://www.w3.org/TR/AERT/#color-contrast
luma = 0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2]
# Closests index in the grayscale palette, which starts at RGB 0x080808,
# with stepping 0x0A0A0A
index = int(round((luma - 8)/10))
# Clamp the index to 0-23, corresponding to 232-255
return max(0, min(index, 23))
def _gray_to_rgb(index):
# Convert a grayscale index to its closet single RGB component
return 3*(10*index + 8,) # Returns a 3-tuple
# Obscure Python: We never pass a value for rgb2index, and it keeps pointing to
# the same dict. This avoids a global.
def _alloc_rgb(rgb, rgb2index={}):
# Initialize a new entry in the xterm palette to the given RGB color,
# returning its index. If the color has already been initialized, the index
# of the existing entry is returned.
#
# ncurses is palette-based, so we need to overwrite palette entries to make
# new colors.
#
# The colors from 0 to 15 are user-defined, and there's no way to query
# their RGB values, so we better leave them untouched. Also leave any
# hypothetical colors above 255 untouched (though we're unlikely to
# allocate that many colors anyway).
if rgb in rgb2index:
return rgb2index[rgb]
# Many terminals allow the user to customize the first 16 colors. Avoid
# changing their values.
color_index = 16 + len(rgb2index)
if color_index >= 256:
_warn("Unable to allocate new RGB color ", rgb, ". Too many colors "
"allocated.")
return 0
# Map each RGB component from the range 0-255 to the range 0-1000, which is
# what curses uses
curses.init_color(color_index, *(int(round(1000*x/255)) for x in rgb))
rgb2index[rgb] = color_index
return color_index
def _color_from_num(num):
# Returns the index of a color that looks like color 'num' in the xterm
# 256-color palette (but that might not be 'num', if we're redefining
# colors)
# - _alloc_rgb() won't touch the first 16 colors or any (hypothetical)
# colors above 255, so we can always return them as-is
#
# - If the terminal doesn't support changing color definitions, or if
# curses.COLORS < 256, _alloc_rgb() won't touch any color, and all colors
# can be returned as-is
if num < 16 or num > 255 or not curses.can_change_color() or \
curses.COLORS < 256:
return num
# _alloc_rgb() might redefine colors, so emulate the xterm 256-color
# palette by allocating new colors instead of returning color numbers
# directly
if num < 232:
num -= 16
return _alloc_rgb(_6cube_to_rgb(((num//36)%6, (num//6)%6, num%6)))
return _alloc_rgb(_gray_to_rgb(num - 232))
def _color_from_rgb(rgb):
# Returns the index of a color matching the 888 RGB color 'rgb'. The
# returned color might be an ~exact match or an approximation, depending on
# terminal capabilities.
# Calculates the Euclidean distance between two RGB colors
def dist(r1, r2): return sum((x - y)**2 for x, y in zip(r1, r2))
if curses.COLORS >= 256:
# Assume we're dealing with xterm's 256-color extension
if curses.can_change_color():
# Best case -- the terminal supports changing palette entries via
# curses.init_color(). Initialize an unused palette entry and
# return it.
return _alloc_rgb(rgb)
# Second best case -- pick between the xterm 256-color extension colors
# Closest 6-cube "color" color
c6 = _rgb_to_6cube(rgb)
# Closest gray color
gray = _rgb_to_gray(rgb)
if dist(rgb, _6cube_to_rgb(c6)) < dist(rgb, _gray_to_rgb(gray)):
# Use the "color" color from the 6x6x6 color palette. Calculate the
# color number from the 6-cube index triplet.
return 16 + 36*c6[0] + 6*c6[1] + c6[2]
# Use the color from the gray palette
return 232 + gray
# Terminal not in xterm 256-color mode. This is probably the best we can
# do, or is it? Submit patches. :)
min_dist = float('inf')
best = -1
for color in range(curses.COLORS):
# ncurses uses the range 0..1000. Scale that down to 0..255.
d = dist(rgb, tuple(int(round(255*c/1000))
for c in curses.color_content(color)))
if d < min_dist:
min_dist = d
best = color
return best
# Dictionary mapping element types to the curses attributes used to display
# them
_style = {}
def _parse_style(style_str, parsing_default):
# Parses a string with '<element>=<style>' assignments. Anything not
# containing '=' is assumed to be a reference to a built-in style, which is
# treated as if all the assignments from the style were inserted at that
# point in the string.
#
# The parsing_default flag is set to True when we're implicitly parsing the
# 'default'/'monochrome' style, to prevent warnings.
for sline in style_str.split():
# Words without a "=" character represents a style template
if "=" in sline:
key, data = sline.split("=", 1)
# The 'default' style template is assumed to define all keys. We
# run _style_to_curses() for non-existing keys as well, so that we
# print warnings for errors to the right of '=' for those too.
if key not in _style and not parsing_default:
_warn("Ignoring non-existent style", key)
# If data is a reference to another key, copy its style
if data in _style:
_style[key] = _style[data]
else:
_style[key] = _style_to_curses(data)
elif sline in _STYLES:
# Recursively parse style template. Ignore styles that don't exist,
# for backwards/forwards compatibility.
_parse_style(_STYLES[sline], parsing_default)
else:
_warn("Ignoring non-existent style template", sline)
def _style_to_curses(style_def):
# Parses a style definition string (<element>=<style>), returning
# a (fg_color, bg_color, attributes) tuple.
def parse_color(color_def):
color_def = color_def.split(":", 1)[1]
if color_def in _STYLE_STD_COLORS:
return _color_from_num(_STYLE_STD_COLORS[color_def])
# HTML format, #RRGGBB
if re.match("#[A-Fa-f0-9]{6}", color_def):
return _color_from_rgb((
int(color_def[1:3], 16),
int(color_def[3:5], 16),
int(color_def[5:7], 16)))
try:
color_num = _color_from_num(int(color_def, 0))
except ValueError:
_warn("Ignoring color ", color_def, "that's neither predefined "
"nor a number")
return -1
if not -1 <= color_num < curses.COLORS:
_warn("Ignoring color {}, which is outside the range "
"-1..curses.COLORS-1 (-1..{})"
.format(color_def, curses.COLORS - 1))
return -1
return color_num
fg_color = -1
bg_color = -1
attrs = 0
if style_def:
for field in style_def.split(","):
if field.startswith("fg:"):
fg_color = parse_color(field)
elif field.startswith("bg:"):
bg_color = parse_color(field)
elif field == "bold":
# A_BOLD tends to produce faint and hard-to-read text on the
# Windows console, especially with the old color scheme, before
# the introduction of
# https://blogs.msdn.microsoft.com/commandline/2017/08/02/updating-the-windows-console-colors/
attrs |= curses.A_NORMAL if _IS_WINDOWS else curses.A_BOLD
elif field == "standout":
attrs |= curses.A_STANDOUT
elif field == "underline":
attrs |= curses.A_UNDERLINE
else:
_warn("Ignoring unknown style attribute", field)
return _style_attr(fg_color, bg_color, attrs)
def _init_styles():
if curses.has_colors():
curses.use_default_colors()
# Use the 'monochrome' style template as the base on terminals without
# color
_parse_style("default" if curses.has_colors() else "monochrome", True)
# Add any user-defined style from the environment
if "MENUCONFIG_STYLE" in os.environ:
_parse_style(os.environ["MENUCONFIG_STYLE"], False)
# color_attribs holds the color pairs we've already created, indexed by a
# (<foreground color>, <background color>) tuple.
#
# Obscure Python: We never pass a value for color_attribs, and it keeps
# pointing to the same dict. This avoids a global.
def _style_attr(fg_color, bg_color, attribs, color_attribs={}):
# Returns an attribute with the specified foreground and background color
# and the attributes in 'attribs'. Reuses color pairs already created if
# possible, and creates a new color pair otherwise.
#
# Returns 'attribs' if colors aren't supported.
if not curses.has_colors():
return attribs
if (fg_color, bg_color) not in color_attribs:
# Create new color pair. Color pair number 0 is hardcoded and cannot be
# changed, hence the +1s.
curses.init_pair(len(color_attribs) + 1, fg_color, bg_color)
color_attribs[(fg_color, bg_color)] = \
curses.color_pair(len(color_attribs) + 1)
return color_attribs[(fg_color, bg_color)] | attribs
#
# Main application
#
# Used as the entry point in setup.py
def _main():
menuconfig(standard_kconfig())
def menuconfig(kconf):
"""
Launches the configuration interface, returning after the user exits.
kconf:
Kconfig instance to be configured
"""
global _kconf
global _config_filename
global _show_all
global _conf_changed
_kconf = kconf
_config_filename = standard_config_filename()
if os.path.exists(_config_filename):
_conf_changed = False
print("Using existing configuration '{}' as base"
.format(_config_filename))
_kconf.load_config(_config_filename)
else:
# Always prompt for save if the .config doesn't exist
_conf_changed = True
if kconf.defconfig_filename is not None:
print("Using default configuration found in '{}' as base"
.format(kconf.defconfig_filename))
_kconf.load_config(kconf.defconfig_filename)
else:
print("Using default symbol values as base")
# Any visible items in the top menu?
_show_all = False
if not _shown_nodes(_kconf.top_node):
# Nothing visible. Start in show-all mode and try again.
_show_all = True
if not _shown_nodes(_kconf.top_node):
# Give up. The implementation relies on always having a selected
# node.
print("Empty configuration -- nothing to configure.\n"
"Check that environment variables are set properly.")
return
# Disable warnings. They get mangled in curses mode, and we deal with
# errors ourselves.
_kconf.disable_warnings()
# Make curses use the locale settings specified in the environment
locale.setlocale(locale.LC_ALL, "")
# Try to fix Unicode issues on systems with bad defaults
if _CONVERT_C_LC_CTYPE_TO_UTF8:
_convert_c_lc_ctype_to_utf8()
# Get rid of the delay between pressing ESC and jumping to the parent menu,
# unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much
# smoother to work with.
#
# Note: This is strictly pretty iffy, since escape codes for e.g. cursor
# keys start with ESC, but I've never seen it cause problems in practice
# (probably because it's unlikely that the escape code for a key would get
# split up across read()s, at least with a terminal emulator). Please
# report if you run into issues. Some suitable small default value could be
# used here instead in that case. Maybe it's silly to not put in the
# smallest imperceptible delay here already, though I don't like guessing.
#
# (From a quick glance at the ncurses source code, ESCDELAY might only be
# relevant for mouse events there, so maybe escapes are assumed to arrive
# in one piece already...)
os.environ.setdefault("ESCDELAY", "0")
# Enter curses mode. _menuconfig() returns a string to print on exit, after
# curses has been de-initialized.
print(curses.wrapper(_menuconfig))
# Global variables used below:
#
# _stdscr:
# stdscr from curses
#
# _cur_menu:
# Menu node of the menu (or menuconfig symbol, or choice) currently being
# shown
#
# _shown:
# List of items in _cur_menu that are shown (ignoring scrolling). In
# show-all mode, this list contains all items in _cur_menu. Otherwise, it
# contains just the visible items.
#
# _sel_node_i:
# Index in _shown of the currently selected node
#
# _menu_scroll:
# Index in _shown of the top row of the main display
#
# _parent_screen_rows:
# List/stack of the row numbers that the selections in the parent menus
# appeared on. This is used to prevent the scrolling from jumping around
# when going in and out of menus.
#
# _show_all:
# If True, "show-all" mode is on. Show-all mode shows all symbols and other
# items in the current menu, including those that lack a prompt or aren't
# currently visible.
#
# Invisible items are drawn in a different style to make them stand out.
#
# _show_name:
# If True, the names of all symbol are shown in addition to the prompt.
#
# _conf_changed:
# True if the configuration has been changed. If False, we don't bother
# showing the save-and-quit dialog.
#
# We reset this to False whenever the configuration is saved explicitly
# from the save dialog.
def _menuconfig(stdscr):
# Logic for the main display, with the list of symbols, etc.
global _stdscr
global _conf_changed
global _show_name
_stdscr = stdscr
_init()
while True:
_draw_main()
curses.doupdate()
c = _get_wch_compat(_menu_win)
if c == curses.KEY_RESIZE:
_resize_main()
elif c in (curses.KEY_DOWN, "j", "J"):
_select_next_menu_entry()
elif c in (curses.KEY_UP, "k", "K"):
_select_prev_menu_entry()
elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
# Keep it simple. This way we get sane behavior for small windows,
# etc., for free.
for _ in range(_PG_JUMP):
_select_next_menu_entry()
elif c in (curses.KEY_PPAGE, "\x15"): # Page Up/Ctrl-U
for _ in range(_PG_JUMP):
_select_prev_menu_entry()
elif c in (curses.KEY_END, "G"):
_select_last_menu_entry()
elif c in (curses.KEY_HOME, "g"):
_select_first_menu_entry()
elif c in (curses.KEY_RIGHT, " ", "\n", "l", "L"):
# Do appropriate node action. Only Space is treated specially,
# preferring to toggle nodes rather than enter menus.
sel_node = _shown[_sel_node_i]
if sel_node.is_menuconfig and not \
(c == " " and _prefer_toggle(sel_node.item)):
_enter_menu(sel_node)
else:
_change_node(sel_node)
if _is_y_mode_choice_sym(sel_node.item) and not sel_node.list:
# Immediately jump to the parent menu after making a choice
# selection, like 'make menuconfig' does, except if the
# menu node has children (which can happen if a symbol
# 'depends on' a choice symbol that immediately precedes
# it).
_leave_menu()
elif c in ("n", "N"):
_set_sel_node_tri_val(0)
elif c in ("m", "M"):
_set_sel_node_tri_val(1)
elif c in ("y", "Y"):
_set_sel_node_tri_val(2)
elif c in (curses.KEY_LEFT, curses.KEY_BACKSPACE, _ERASE_CHAR,
"\x1B", # \x1B = ESC
"h", "H"):
if c == "\x1B" and _cur_menu is _kconf.top_node:
res = _quit_dialog()
if res:
return res
else:
_leave_menu()
elif c in ("o", "O"):
if _conf_changed:
c = _key_dialog(
"Load",
"You have unsaved changes. Load new\n"
"configuration anyway?\n"
"\n"
" (Y)es (C)ancel",
"yc")
if c is None or c == "c":
continue
if _load_dialog():
_conf_changed = False
elif c in ("s", "S"):
if _save_dialog(_kconf.write_config, _config_filename,
"configuration"):
_conf_changed = False
elif c in ("d", "D"):
_save_dialog(_kconf.write_min_config, "defconfig",
"minimal configuration")
elif c == "/":
_jump_to_dialog()
# The terminal might have been resized while the fullscreen jump-to
# dialog was open
_resize_main()
elif c == "?":
_info_dialog(_shown[_sel_node_i], False)
# The terminal might have been resized while the fullscreen info
# dialog was open
_resize_main()
elif c in ("a", "A"):
_toggle_show_all()
elif c in ("c", "C"):
_show_name = not _show_name
elif c in ("q", "Q"):
res = _quit_dialog()
if res:
return res
def _quit_dialog():
if not _conf_changed:
return "No changes to save"
while True:
c = _key_dialog(
"Quit",
" Save configuration?\n"
"\n"
"(Y)es (N)o (C)ancel",
"ync")
if c is None or c == "c":
return None
if c == "y":
if _try_save(_kconf.write_config, _config_filename,
"configuration"):
return "Configuration saved to '{}'" \
.format(_config_filename)
elif c == "n":
return "Configuration was not saved"
def _init():
# Initializes the main display with the list of symbols, etc. Also does
# misc. global initialization that needs to happen after initializing
# curses.
global _ERASE_CHAR
global _path_win
global _top_sep_win
global _menu_win
global _bot_sep_win
global _help_win
global _parent_screen_rows
global _cur_menu
global _shown
global _sel_node_i
global _menu_scroll
global _show_name
# Looking for this in addition to KEY_BACKSPACE (which is unreliable) makes
# backspace work with TERM=vt100. That makes it likely to work in sane
# environments.
#
# erasechar() returns a 'bytes' object. Since we use get_wch(), we need to
# decode it. Just give up and avoid crashing if it can't be decoded.
_ERASE_CHAR = curses.erasechar().decode("utf-8", "ignore")
_init_styles()
# Hide the cursor
_safe_curs_set(0)
# Initialize windows
# Top row, with menu path
_path_win = _styled_win("path")
# Separator below menu path, with title and arrows pointing up
_top_sep_win = _styled_win("separator")
# List of menu entries with symbols, etc.
_menu_win = _styled_win("list")
_menu_win.keypad(True)
# Row below menu list, with arrows pointing down
_bot_sep_win = _styled_win("separator")
# Help window with keys at the bottom
_help_win = _styled_win("help")
# The rows we'd like the nodes in the parent menus to appear on. This
# prevents the scroll from jumping around when going in and out of menus.
_parent_screen_rows = []
# Initial state
_cur_menu = _kconf.top_node
_shown = _shown_nodes(_cur_menu)
_sel_node_i = _menu_scroll = 0
_show_name = False
# Give windows their initial size
_resize_main()
def _resize_main():
# Resizes the main display, with the list of symbols, etc., to fill the
# terminal
global _menu_scroll
screen_height, screen_width = _stdscr.getmaxyx()
_path_win.resize(1, screen_width)
_top_sep_win.resize(1, screen_width)
_bot_sep_win.resize(1, screen_width)
help_win_height = len(_MAIN_HELP_LINES)
menu_win_height = screen_height - help_win_height - 3
if menu_win_height >= 1:
_menu_win.resize(menu_win_height, screen_width)
_help_win.resize(help_win_height, screen_width)
_top_sep_win.mvwin(1, 0)
_menu_win.mvwin(2, 0)
_bot_sep_win.mvwin(2 + menu_win_height, 0)
_help_win.mvwin(2 + menu_win_height + 1, 0)
else:
# Degenerate case. Give up on nice rendering and just prevent errors.
menu_win_height = 1
_menu_win.resize(1, screen_width)
_help_win.resize(1, screen_width)
for win in _top_sep_win, _menu_win, _bot_sep_win, _help_win:
win.mvwin(0, 0)
# Adjust the scroll so that the selected node is still within the window,
# if needed
if _sel_node_i - _menu_scroll >= menu_win_height:
_menu_scroll = _sel_node_i - menu_win_height + 1
def _menu_win_height():
# Returns the height of the menu display
return _menu_win.getmaxyx()[0]
def _prefer_toggle(item):
# For nodes with menus, determines whether Space should change the value of
# the node's item or enter its menu. We toggle symbols (which have menus
# when they're defined with 'menuconfig') and choices that can be in more
# than one mode (e.g. optional choices). In other cases, we enter the menu.
return isinstance(item, Symbol) or \
(isinstance(item, Choice) and len(item.assignable) > 1)
def _enter_menu(menu):
# Makes 'menu' the currently displayed menu. "Menu" here includes choices.
global _cur_menu
global _shown
global _sel_node_i
global _menu_scroll
shown_sub = _shown_nodes(menu)
# Never enter empty menus. We depend on having a current node.
if shown_sub:
# Remember where the current node appears on the screen, so we can try
# to get it to appear in the same place when we leave the menu
_parent_screen_rows.append(_sel_node_i - _menu_scroll)
# Jump into menu
_cur_menu = menu
_shown = shown_sub
_sel_node_i = _menu_scroll = 0
if isinstance(menu.item, Choice):
_select_selected_choice_sym()
def _select_selected_choice_sym():
# Puts the cursor on the currently selected (y-valued) choice symbol, if
# any. Does nothing if if the choice has no selection (is not visible/in y
# mode).
global _sel_node_i
choice = _cur_menu.item
if choice.selection:
# Search through all menu nodes to handle choice symbols being defined
# in multiple locations
for node in choice.selection.nodes:
if node in _shown:
_sel_node_i = _shown.index(node)
_center_vertically()
def _jump_to(node):
# Jumps directly to the menu node 'node'
global _cur_menu
global _shown
global _sel_node_i
global _menu_scroll
global _show_all
global _parent_screen_rows
# Clear remembered menu locations. We might not even have been in the
# parent menus before.
_parent_screen_rows = []
old_show_all = _show_all
jump_into = (isinstance(node.item, Choice) or node.item == MENU) and \
node.list
# If we're jumping to a non-empty choice or menu, jump to the first entry
# in it instead of jumping to its menu node
if jump_into:
_cur_menu = node
node = node.list
else:
_cur_menu = _parent_menu(node)
_shown = _shown_nodes(_cur_menu)
if node not in _shown:
# The node wouldn't be shown. Turn on show-all to show it.
_show_all = True
_shown = _shown_nodes(_cur_menu)
_sel_node_i = _shown.index(node)
if jump_into and not old_show_all and _show_all:
# If we're jumping into a choice or menu and were forced to turn on
# show-all because the first entry wasn't visible, try turning it off.
# That will land us at the first visible node if there are visible
# nodes, and is a no-op otherwise.
_toggle_show_all()
_center_vertically()
# If we're jumping to a non-empty choice, jump to the selected symbol, if
# any
if jump_into and isinstance(_cur_menu.item, Choice):
_select_selected_choice_sym()
def _leave_menu():
# Jumps to the parent menu of the current menu. Does nothing if we're in
# the top menu.
global _cur_menu
global _shown
global _sel_node_i
global _menu_scroll
if _cur_menu is _kconf.top_node:
return
# Jump to parent menu
parent = _parent_menu(_cur_menu)
_shown = _shown_nodes(parent)
_sel_node_i = _shown.index(_cur_menu)
_cur_menu = parent
# Try to make the menu entry appear on the same row on the screen as it did
# before we entered the menu.
if _parent_screen_rows:
# The terminal might have shrunk since we were last in the parent menu
screen_row = min(_parent_screen_rows.pop(), _menu_win_height() - 1)
_menu_scroll = max(_sel_node_i - screen_row, 0)
else:
# No saved parent menu locations, meaning we jumped directly to some
# node earlier
_center_vertically()
def _select_next_menu_entry():
# Selects the menu entry after the current one, adjusting the scroll if
# necessary. Does nothing if we're already at the last menu entry.
global _sel_node_i
global _menu_scroll
if _sel_node_i < len(_shown) - 1:
# Jump to the next node
_sel_node_i += 1
# If the new node is sufficiently close to the edge of the menu window
# (as determined by _SCROLL_OFFSET), increase the scroll by one. This
# gives nice and non-jumpy behavior even when
# _SCROLL_OFFSET >= _menu_win_height().
if _sel_node_i >= _menu_scroll + _menu_win_height() - _SCROLL_OFFSET:
_menu_scroll = min(_menu_scroll + 1,
_max_scroll(_shown, _menu_win))
def _select_prev_menu_entry():
# Selects the menu entry before the current one, adjusting the scroll if
# necessary. Does nothing if we're already at the first menu entry.
global _sel_node_i
global _menu_scroll
if _sel_node_i > 0:
# Jump to the previous node
_sel_node_i -= 1
# See _select_next_menu_entry()
if _sel_node_i <= _menu_scroll + _SCROLL_OFFSET:
_menu_scroll = max(_menu_scroll - 1, 0)
def _select_last_menu_entry():
# Selects the last menu entry in the current menu
global _sel_node_i
global _menu_scroll
_sel_node_i = len(_shown) - 1
_menu_scroll = _max_scroll(_shown, _menu_win)
def _select_first_menu_entry():
# Selects the first menu entry in the current menu
global _sel_node_i
global _menu_scroll
_sel_node_i = _menu_scroll = 0
def _toggle_show_all():
# Toggles show-all mode on/off. If turning it off would give no visible
# items in the current menu, it is left on.
global _show_all
global _shown
global _sel_node_i
global _menu_scroll
# Row on the screen the cursor is on. Preferably we want the same row to
# stay highlighted.
old_row = _sel_node_i - _menu_scroll
_show_all = not _show_all
# List of new nodes to be shown after toggling _show_all
new_shown = _shown_nodes(_cur_menu)
# Find a good node to select. The selected node might disappear if show-all
# mode is turned off.
# If there are visible nodes before the previously selected node, select
# the closest one. This will select the previously selected node itself if
# it is still visible.
for node in reversed(_shown[:_sel_node_i + 1]):
if node in new_shown:
_sel_node_i = new_shown.index(node)
break
else:
# No visible nodes before the previously selected node. Select the
# closest visible node after it instead.
for node in _shown[_sel_node_i + 1:]:
if node in new_shown:
_sel_node_i = new_shown.index(node)
break
else:
# No visible nodes at all, meaning show-all was turned off inside
# an invisible menu. Don't allow that, as the implementation relies
# on always having a selected node.
_show_all = True
return
_shown = new_shown
# Try to make the cursor stay on the same row in the menu window. This
# might be impossible if too many nodes have disappeared above the node.
_menu_scroll = max(_sel_node_i - old_row, 0)
def _center_vertically():
# Centers the selected node vertically, if possible
global _menu_scroll
_menu_scroll = min(max(_sel_node_i - _menu_win_height()//2, 0),
_max_scroll(_shown, _menu_win))
def _draw_main():
# Draws the "main" display, with the list of symbols, the header, and the
# footer.
#
# This could be optimized to only update the windows that have actually
# changed, but keep it simple for now and let curses sort it out.
term_width = _stdscr.getmaxyx()[1]
#
# Update the separator row below the menu path
#
_top_sep_win.erase()
# Draw arrows pointing up if the symbol window is scrolled down. Draw them
# before drawing the title, so the title ends up on top for small windows.
if _menu_scroll > 0:
_safe_hline(_top_sep_win, 0, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS)
# Add the 'mainmenu' text as the title, centered at the top
_safe_addstr(_top_sep_win,
0, max((term_width - len(_kconf.mainmenu_text))//2, 0),
_kconf.mainmenu_text)
_top_sep_win.noutrefresh()
# Note: The menu path at the top is deliberately updated last. See below.
#
# Update the symbol window
#
_menu_win.erase()
# Draw the _shown nodes starting from index _menu_scroll up to either as
# many as fit in the window, or to the end of _shown
for i in range(_menu_scroll,
min(_menu_scroll + _menu_win_height(), len(_shown))):
node = _shown[i]
# The 'not _show_all' test avoids showing invisible items in red
# outside show-all mode, which could look confusing/broken. Invisible
# symbols show up outside show-all mode if an invisible symbol has
# visible children in an implicit (indented) menu.
if not _show_all or (node.prompt and expr_value(node.prompt[1])):
style = _style["selection" if i == _sel_node_i else "list"]
else:
style = _style["inv-selection" if i == _sel_node_i else "inv-list"]
_safe_addstr(_menu_win, i - _menu_scroll, 0, _node_str(node), style)
_menu_win.noutrefresh()
#
# Update the bottom separator window
#
_bot_sep_win.erase()
# Draw arrows pointing down if the symbol window is scrolled up
if _menu_scroll < _max_scroll(_shown, _menu_win):
_safe_hline(_bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
# Indicate when show-all and/or show-name mode is enabled
enabled_modes = []
if _show_all:
enabled_modes.append("show-all")
if _show_name:
enabled_modes.append("show-name")
if enabled_modes:
s = " and ".join(enabled_modes) + " mode enabled"
_safe_addstr(_bot_sep_win, 0, term_width - len(s) - 2, s)
_bot_sep_win.noutrefresh()
#
# Update the help window
#
_help_win.erase()
for i, line in enumerate(_MAIN_HELP_LINES):
_safe_addstr(_help_win, i, 0, line)
_help_win.noutrefresh()
#
# Update the top row with the menu path.
#
# Doing this last leaves the cursor on the top row, which avoids some minor
# annoying jumpiness in gnome-terminal when reducing the height of the
# terminal. It seems to happen whenever the row with the cursor on it
# disappears.
#
_path_win.erase()
# Draw the menu path ("(top menu) -> menu -> submenu -> ...")
menu_prompts = []
menu = _cur_menu
while menu is not _kconf.top_node:
# Promptless choices can be entered in show-all mode. Use
# standard_sc_expr_str() for them, so they show up as
# '<choice (name if any)>'.
menu_prompts.append(menu.prompt[0] if menu.prompt else
standard_sc_expr_str(menu.item))
menu = _parent_menu(menu)
menu_prompts.append("(top menu)")
menu_prompts.reverse()
# Hack: We can't put ACS_RARROW directly in the string. Temporarily
# represent it with NULL. Maybe using a Unicode character would be better.
menu_path_str = " \0 ".join(menu_prompts)
# Scroll the menu path to the right if needed to make the current menu's
# title visible
if len(menu_path_str) > term_width:
menu_path_str = menu_path_str[len(menu_path_str) - term_width:]
# Print the path with the arrows reinserted
split_path = menu_path_str.split("\0")
_safe_addstr(_path_win, split_path[0])
for s in split_path[1:]:
_safe_addch(_path_win, curses.ACS_RARROW)
_safe_addstr(_path_win, s)
_path_win.noutrefresh()
def _parent_menu(node):
# Returns the menu node of the menu that contains 'node'. In addition to
# proper 'menu's, this might also be a 'menuconfig' symbol or a 'choice'.
# "Menu" here means a menu in the interface.
menu = node.parent
while not menu.is_menuconfig:
menu = menu.parent
return menu
def _shown_nodes(menu):
# Returns the list of menu nodes from 'menu' (see _parent_menu()) that
# would be shown when entering it
def rec(node):
res = []
while node:
# If a node has children but doesn't have the is_menuconfig flag
# set, the children come from a submenu created implicitly from
# dependencies, and are shown (indented) in the same menu as the
# parent node
shown_children = \
rec(node.list) if node.list and not node.is_menuconfig else []
# Always show the node if it is the root of an implicit submenu
# with visible items, even when the node itself is invisible. This
# can happen e.g. if the symbol has an optional prompt
# ('prompt "foo" if COND') that is currently invisible.
if shown(node) or shown_children:
res.append(node)
res.extend(shown_children)
node = node.next
return res
def shown(node):
# Show the node if its prompt is visible. For menus, also check
# 'visible if'. In show-all mode, show everything.
return _show_all or \
(node.prompt and expr_value(node.prompt[1]) and not
(node.item == MENU and not expr_value(node.visibility)))
if isinstance(menu.item, Choice):
# For named choices defined in multiple locations, entering the choice
# at a particular menu node would normally only show the choice symbols
# defined there (because that's what the MenuNode tree looks like).
#
# That might look confusing, and makes extending choices by defining
# them in multiple locations less useful. Instead, gather all the child
# menu nodes for all the choices whenever a choice is entered. That
# makes all choice symbols visible at all locations.
#
# Choices can contain non-symbol items (people do all sorts of weird
# stuff with them), hence the generality here. We really need to
# preserve the menu tree at each choice location.
#
# Note: Named choices are pretty broken in the C tools, and this is
# super obscure, so you probably won't find much that relies on this.
return [node
for choice_node in menu.item.nodes
for node in rec(choice_node.list)]
return rec(menu.list)
def _change_node(node):
# Changes the value of the menu node 'node' if it is a symbol. Bools and
# tristates are toggled, while other symbol types pop up a text entry
# dialog.
if not isinstance(node.item, (Symbol, Choice)):
return
# This will hit for invisible symbols, which appear in show-all mode and
# when an invisible symbol has visible children (which can happen e.g. for
# symbols with optional prompts)
if not (node.prompt and expr_value(node.prompt[1])):
return
# sc = symbol/choice
sc = node.item
if sc.type in (INT, HEX, STRING):
s = sc.str_value
while True:
s = _input_dialog("{} ({})".format(
node.prompt[0], TYPE_TO_STR[sc.type]),
s, _range_info(sc))
if s is None:
break
if sc.type in (INT, HEX):
s = s.strip()
# 'make menuconfig' does this too. Hex values not starting with
# '0x' are accepted when loading .config files though.
if sc.type == HEX and not s.startswith(("0x", "0X")):
s = "0x" + s
if _check_validity(sc, s):
_set_val(sc, s)
break
elif len(sc.assignable) == 1:
# Handles choice symbols for choices in y mode, which are a special
# case: .assignable can be (2,) while .tri_value is 0.
_set_val(sc, sc.assignable[0])
elif sc.assignable:
# Set the symbol to the value after the current value in
# sc.assignable, with wrapping
val_index = sc.assignable.index(sc.tri_value)
_set_val(sc, sc.assignable[(val_index + 1) % len(sc.assignable)])
def _set_sel_node_tri_val(tri_val):
# Sets the value of the currently selected menu entry to 'tri_val', if that
# value can be assigned
sc = _shown[_sel_node_i].item
if isinstance(sc, (Symbol, Choice)) and tri_val in sc.assignable:
_set_val(sc, tri_val)
def _set_val(sc, val):
# Wrapper around Symbol/Choice.set_value() for updating the menu state and
# _conf_changed
global _conf_changed
# Use the string representation of tristate values. This makes the format
# consistent for all symbol types.
if val in TRI_TO_STR:
val = TRI_TO_STR[val]
if val != sc.str_value:
sc.set_value(val)
_conf_changed = True
# Changing the value of the symbol might have changed what items in the
# current menu are visible. Recalculate the state.
_update_menu()
def _update_menu():
# Updates the current menu after the value of a symbol or choice has been
# changed. Changing a value might change which items in the menu are
# visible.
#
# Tries to preserve the location of the cursor when items disappear above
# it.
global _shown
global _sel_node_i
global _menu_scroll
# Row on the screen the cursor was on
old_row = _sel_node_i - _menu_scroll
sel_node = _shown[_sel_node_i]
# New visible nodes
_shown = _shown_nodes(_cur_menu)
# New index of selected node
_sel_node_i = _shown.index(sel_node)
# Try to make the cursor stay on the same row in the menu window. This
# might be impossible if too many nodes have disappeared above the node.
_menu_scroll = max(_sel_node_i - old_row, 0)
def _input_dialog(title, initial_text, info_text=None):
# Pops up a dialog that prompts the user for a string
#
# title:
# Title to display at the top of the dialog window's border
#
# initial_text:
# Initial text to prefill the input field with
#
# info_text:
# String to show next to the input field. If None, just the input field
# is shown.
win = _styled_win("body")
win.keypad(True)
info_lines = info_text.split("\n") if info_text else []
# Give the input dialog its initial size
_resize_input_dialog(win, title, info_lines)
_safe_curs_set(2)
# Input field text
s = initial_text
# Cursor position
i = len(initial_text)
def edit_width():
return win.getmaxyx()[1] - 4
# Horizontal scroll offset
hscroll = max(i - edit_width() + 1, 0)
while True:
# Draw the "main" display with the menu, etc., so that resizing still
# works properly. This is like a stack of windows, only hardcoded for
# now.
_draw_main()
_draw_input_dialog(win, title, info_lines, s, i, hscroll)
curses.doupdate()
c = _get_wch_compat(win)
if c == curses.KEY_RESIZE:
# Resize the main display too. The dialog floats above it.
_resize_main()
_resize_input_dialog(win, title, info_lines)
elif c == "\n":
_safe_curs_set(0)
return s
elif c == "\x1B": # \x1B = ESC
_safe_curs_set(0)
return None
else:
s, i, hscroll = _edit_text(c, s, i, hscroll, edit_width())
def _resize_input_dialog(win, title, info_lines):
# Resizes the input dialog to a size appropriate for the terminal size
screen_height, screen_width = _stdscr.getmaxyx()
win_height = 5
if info_lines:
win_height += len(info_lines) + 1
win_height = min(win_height, screen_height)
win_width = max(_INPUT_DIALOG_MIN_WIDTH,
len(title) + 4,
*(len(line) + 4 for line in info_lines))
win_width = min(win_width, screen_width)
win.resize(win_height, win_width)
win.mvwin((screen_height - win_height)//2,
(screen_width - win_width)//2)
def _draw_input_dialog(win, title, info_lines, s, i, hscroll):
edit_width = win.getmaxyx()[1] - 4
win.erase()
# Note: Perhaps having a separate window for the input field would be nicer
visible_s = s[hscroll:hscroll + edit_width]
_safe_addstr(win, 2, 2, visible_s + " "*(edit_width - len(visible_s)),
_style["edit"])
for linenr, line in enumerate(info_lines):
_safe_addstr(win, 4 + linenr, 2, line)
# Draw the frame last so that it overwrites the body text for small windows
_draw_frame(win, title)
_safe_move(win, 2, 2 + i - hscroll)
win.noutrefresh()
def _load_dialog():
# Dialog for loading a new configuration
#
# Return value:
# True if a new configuration was loaded, and False if the user canceled
# the dialog
global _show_all
filename = ""
while True:
filename = _input_dialog("File to load", filename, _load_save_info())
if filename is None:
return False
filename = os.path.expanduser(filename)
if _try_load(filename):
sel_node = _shown[_sel_node_i]
# Turn on show-all mode if the current node is (no longer) visible
if not (sel_node.prompt and expr_value(sel_node.prompt[1])):
_show_all = True
_update_menu()
# The message dialog indirectly updates the menu display, so _msg()
# must be called after the new state has been initialized
_msg("Success", "Loaded {}".format(filename))
return True
def _try_load(filename):
# Tries to load a configuration file. Pops up an error and returns False on
# failure.
#
# filename:
# Configuration file to load
try:
_kconf.load_config(filename)
return True
except OSError as e:
_error("Error loading '{}'\n\n{} (errno: {})"
.format(filename, e.strerror, errno.errorcode[e.errno]))
return False
def _save_dialog(save_fn, default_filename, description):
# Dialog for saving the current configuration
#
# save_fn:
# Function to call with 'filename' to save the file
#
# default_filename:
# Prefilled filename in the input field
#
# description:
# String describing the thing being saved
#
# Return value:
# True if the configuration was saved, and False if the user canceled the
# dialog
filename = default_filename
while True:
filename = _input_dialog("Filename to save {} to".format(description),
filename, _load_save_info())
if filename is None:
return False
filename = os.path.expanduser(filename)
if _try_save(save_fn, filename, description):
_msg("Success", "{} saved to {}".format(description, filename))
return True
def _try_save(save_fn, filename, description):
# Tries to save a configuration file. Pops up an error and returns False on
# failure.
#
# save_fn:
# Function to call with 'filename' to save the file
#
# description:
# String describing the thing being saved
try:
save_fn(filename)
return True
except OSError as e:
_error("Error saving {} to '{}'\n\n{} (errno: {})"
.format(description, e.filename, e.strerror,
errno.errorcode[e.errno]))
return False
def _key_dialog(title, text, keys):
# Pops up a dialog that can be closed by pressing a key
#
# title:
# Title to display at the top of the dialog window's border
#
# text:
# Text to show in the dialog
#
# keys:
# List of keys that will close the dialog. Other keys (besides ESC) are
# ignored. The caller is responsible for providing a hint about which
# keys can be pressed in 'text'.
#
# Return value:
# The key that was pressed to close the dialog. Uppercase characters are
# converted to lowercase. ESC will always close the dialog, and returns
# None.
win = _styled_win("body")
win.keypad(True)
_resize_key_dialog(win, text)
while True:
# See _input_dialog()
_draw_main()
_draw_key_dialog(win, title, text)
curses.doupdate()
c = _get_wch_compat(win)
if c == curses.KEY_RESIZE:
# Resize the main display too. The dialog floats above it.
_resize_main()
_resize_key_dialog(win, text)
elif c == "\x1B": # \x1B = ESC
return None
elif isinstance(c, str):
c = c.lower()
if c in keys:
return c
def _resize_key_dialog(win, text):
# Resizes the key dialog to a size appropriate for the terminal size
screen_height, screen_width = _stdscr.getmaxyx()
lines = text.split("\n")
win_height = min(len(lines) + 4, screen_height)
win_width = min(max(len(line) for line in lines) + 4, screen_width)
win.resize(win_height, win_width)
win.mvwin((screen_height - win_height)//2,
(screen_width - win_width)//2)
def _draw_key_dialog(win, title, text):
win.erase()
for i, line in enumerate(text.split("\n")):
_safe_addstr(win, 2 + i, 2, line)
# Draw the frame last so that it overwrites the body text for small windows
_draw_frame(win, title)
win.noutrefresh()
def _draw_frame(win, title):
# Draw a frame around the inner edges of 'win', with 'title' at the top
win_height, win_width = win.getmaxyx()
win.attron(_style["frame"])
# Draw top/bottom edge
_safe_hline(win, 0, 0, " ", win_width)
_safe_hline(win, win_height - 1, 0, " ", win_width)
# Draw left/right edge
_safe_vline(win, 0, 0, " ", win_height)
_safe_vline(win, 0, win_width - 1, " ", win_height)
# Draw title
_safe_addstr(win, 0, max((win_width - len(title))//2, 0), title)
win.attroff(_style["frame"])
def _jump_to_dialog():
# Implements the jump-to dialog, where symbols can be looked up via
# incremental search and jumped to.
#
# Returns True if the user jumped to a symbol, and False if the dialog was
# canceled.
# Search text
s = ""
# Previous search text
prev_s = None
# Search text cursor position
s_i = 0
# Horizontal scroll offset
hscroll = 0
# Index of selected row
sel_node_i = 0
# Index in 'matches' of the top row of the list
scroll = 0
# Edit box at the top
edit_box = _styled_win("jump-edit")
edit_box.keypad(True)
# List of matches
matches_win = _styled_win("list")
# Bottom separator, with arrows pointing down
bot_sep_win = _styled_win("separator")
# Help window with instructions at the bottom
help_win = _styled_win("help")
# Give windows their initial size
_resize_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
sel_node_i, scroll)
_safe_curs_set(2)
# TODO: Code duplication with _select_{next,prev}_menu_entry(). Can this be
# factored out in some nice way?
def select_next_match():
nonlocal sel_node_i
nonlocal scroll
if sel_node_i < len(matches) - 1:
sel_node_i += 1
if sel_node_i >= scroll + matches_win.getmaxyx()[0] - _SCROLL_OFFSET:
scroll = min(scroll + 1, _max_scroll(matches, matches_win))
def select_prev_match():
nonlocal sel_node_i
nonlocal scroll
if sel_node_i > 0:
sel_node_i -= 1
if sel_node_i <= scroll + _SCROLL_OFFSET:
scroll = max(scroll - 1, 0)
while True:
if s != prev_s:
# The search text changed. Find new matching nodes.
prev_s = s
try:
# We could use re.IGNORECASE here instead of lower(), but this
# is noticeably less jerky while inputting regexes like
# '.*debug$' (though the '.*' is redundant there). Those
# probably have bad interactions with re.search(), which
# matches anywhere in the string.
#
# It's not horrible either way. Just a bit smoother.
regex_searches = [re.compile(regex).search
for regex in s.lower().split()]
# No exception thrown, so the regexes are okay
bad_re = None
# List of matching nodes
matches = []
# Search symbols and choices
for node in _sorted_sc_nodes():
# Symbol/choice
sc = node.item
for search in regex_searches:
# Both the name and the prompt might be missing, since
# we're searching both symbols and choices
# Does the regex match either the symbol name or the
# prompt (if any)?
if not (sc.name and search(sc.name.lower()) or
node.prompt and search(node.prompt[0].lower())):
# Give up on the first regex that doesn't match, to
# speed things up a bit when multiple regexes are
# entered
break
else:
matches.append(node)
# Search menus and comments
for node in _sorted_menu_comment_nodes():
for search in regex_searches:
if not search(node.prompt[0].lower()):
break
else:
matches.append(node)
except re.error as e:
# Bad regex. Remember the error message so we can show it.
bad_re = "Bad regular expression"
# re.error.msg was added in Python 3.5
if hasattr(e, "msg"):
bad_re += ": " + e.msg
matches = []
# Reset scroll and jump to the top of the list of matches
sel_node_i = scroll = 0
_draw_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
s, s_i, hscroll,
bad_re, matches, sel_node_i, scroll)
curses.doupdate()
c = _get_wch_compat(edit_box)
if c == "\n":
if matches:
_jump_to(matches[sel_node_i])
_safe_curs_set(0)
return True
elif c == "\x1B": # \x1B = ESC
_safe_curs_set(0)
return False
elif c == curses.KEY_RESIZE:
# We adjust the scroll so that the selected node stays visible in
# the list when the terminal is resized, hence the 'scroll'
# assignment
scroll = _resize_jump_to_dialog(
edit_box, matches_win, bot_sep_win, help_win,
sel_node_i, scroll)
elif c == "\x06": # \x06 = Ctrl-F
if matches:
_safe_curs_set(0)
_info_dialog(matches[sel_node_i], True)
_safe_curs_set(2)
scroll = _resize_jump_to_dialog(
edit_box, matches_win, bot_sep_win, help_win,
sel_node_i, scroll)
elif c == curses.KEY_DOWN:
select_next_match()
elif c == curses.KEY_UP:
select_prev_match()
elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
# Keep it simple. This way we get sane behavior for small windows,
# etc., for free.
for _ in range(_PG_JUMP):
select_next_match()
# Page Up (no Ctrl-U, as it's already used by the edit box)
elif c == curses.KEY_PPAGE:
for _ in range(_PG_JUMP):
select_prev_match()
elif c == curses.KEY_END:
sel_node_i = len(matches) - 1
scroll = _max_scroll(matches, matches_win)
elif c == curses.KEY_HOME:
sel_node_i = scroll = 0
else:
s, s_i, hscroll = _edit_text(c, s, s_i, hscroll,
edit_box.getmaxyx()[1] - 2)
# Obscure Python: We never pass a value for cached_nodes, and it keeps pointing
# to the same list. This avoids a global.
def _sorted_sc_nodes(cached_nodes=[]):
# Returns a sorted list of symbol and choice nodes to search. The symbol
# nodes appear first, sorted by name, and then the choice nodes, sorted by
# prompt and (secondarily) name.
if not cached_nodes:
# Add symbol nodes
for sym in sorted(_kconf.unique_defined_syms,
key=lambda sym: sym.name):
# += is in-place for lists
cached_nodes += sym.nodes
# Add choice nodes
choices = sorted(_kconf.unique_choices,
key=lambda choice: choice.name or "")
cached_nodes += sorted(
[node
for choice in choices
for node in choice.nodes],
key=lambda node: node.prompt[0] if node.prompt else "")
return cached_nodes
def _sorted_menu_comment_nodes(cached_nodes=[]):
# Returns a list of menu and comment nodes to search, sorted by prompt,
# with the menus first
if not cached_nodes:
def prompt_text(mc):
return mc.prompt[0]
cached_nodes += sorted(_kconf.menus, key=prompt_text) + \
sorted(_kconf.comments, key=prompt_text)
return cached_nodes
def _resize_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
sel_node_i, scroll):
# Resizes the jump-to dialog to fill the terminal.
#
# Returns the new scroll index. We adjust the scroll if needed so that the
# selected node stays visible.
screen_height, screen_width = _stdscr.getmaxyx()
bot_sep_win.resize(1, screen_width)
help_win_height = len(_JUMP_TO_HELP_LINES)
matches_win_height = screen_height - help_win_height - 4
if matches_win_height >= 1:
edit_box.resize(3, screen_width)
matches_win.resize(matches_win_height, screen_width)
help_win.resize(help_win_height, screen_width)
matches_win.mvwin(3, 0)
bot_sep_win.mvwin(3 + matches_win_height, 0)
help_win.mvwin(3 + matches_win_height + 1, 0)
else:
# Degenerate case. Give up on nice rendering and just prevent errors.
matches_win_height = 1
edit_box.resize(screen_height, screen_width)
matches_win.resize(1, screen_width)
help_win.resize(1, screen_width)
for win in matches_win, bot_sep_win, help_win:
win.mvwin(0, 0)
# Adjust the scroll so that the selected row is still within the window, if
# needed
if sel_node_i - scroll >= matches_win_height:
return sel_node_i - matches_win_height + 1
return scroll
def _draw_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
s, s_i, hscroll,
bad_re, matches, sel_node_i, scroll):
edit_width = edit_box.getmaxyx()[1] - 2
#
# Update list of matches
#
matches_win.erase()
if matches:
for i in range(scroll,
min(scroll + matches_win.getmaxyx()[0], len(matches))):
node = matches[i]
if isinstance(node.item, (Symbol, Choice)):
node_str = _name_and_val_str(node.item)
if node.prompt:
node_str += ' "{}"'.format(node.prompt[0])
elif node.item == MENU:
node_str = 'menu "{}"'.format(node.prompt[0])
else: # node.item == COMMENT
node_str = 'comment "{}"'.format(node.prompt[0])
_safe_addstr(matches_win, i - scroll, 0, node_str,
_style["selection" if i == sel_node_i else "list"])
else:
# bad_re holds the error message from the re.error exception on errors
_safe_addstr(matches_win, 0, 0, bad_re or "No matches")
matches_win.noutrefresh()
#
# Update bottom separator line
#
bot_sep_win.erase()
# Draw arrows pointing down if the symbol list is scrolled up
if scroll < _max_scroll(matches, matches_win):
_safe_hline(bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
bot_sep_win.noutrefresh()
#
# Update help window at bottom
#
help_win.erase()
for i, line in enumerate(_JUMP_TO_HELP_LINES):
_safe_addstr(help_win, i, 0, line)
help_win.noutrefresh()
#
# Update edit box. We do this last since it makes it handy to position the
# cursor.
#
edit_box.erase()
_draw_frame(edit_box, "Jump to symbol/choice/menu/comment")
# Draw arrows pointing up if the symbol list is scrolled down
if scroll > 0:
# TODO: Bit ugly that _style["frame"] is repeated here
_safe_hline(edit_box, 2, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS,
_style["frame"])
visible_s = s[hscroll:hscroll + edit_width]
_safe_addstr(edit_box, 1, 1, visible_s)
_safe_move(edit_box, 1, 1 + s_i - hscroll)
edit_box.noutrefresh()
def _info_dialog(node, from_jump_to_dialog):
# Shows a fullscreen window with information about 'node'.
#
# If 'from_jump_to_dialog' is True, the information dialog was opened from
# within the jump-to-dialog. In this case, we make '/' from within the
# information dialog just return, to avoid a confusing recursive invocation
# of the jump-to-dialog.
# Top row, with title and arrows point up
top_line_win = _styled_win("separator")
# Text display
text_win = _styled_win("text")
text_win.keypad(True)
# Bottom separator, with arrows pointing down
bot_sep_win = _styled_win("separator")
# Help window with keys at the bottom
help_win = _styled_win("help")
# Give windows their initial size
_resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
# Get lines of help text
lines = _info_str(node).split("\n")
# Index of first row in 'lines' to show
scroll = 0
while True:
_draw_info_dialog(node, lines, scroll, top_line_win, text_win,
bot_sep_win, help_win)
curses.doupdate()
c = _get_wch_compat(text_win)
if c == curses.KEY_RESIZE:
_resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
elif c in (curses.KEY_DOWN, "j", "J"):
if scroll < _max_scroll(lines, text_win):
scroll += 1
elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
scroll = min(scroll + _PG_JUMP, _max_scroll(lines, text_win))
elif c in (curses.KEY_PPAGE, "\x15"): # Page Up/Ctrl-U
scroll = max(scroll - _PG_JUMP, 0)
elif c in (curses.KEY_END, "G"):
scroll = _max_scroll(lines, text_win)
elif c in (curses.KEY_HOME, "g"):
scroll = 0
elif c in (curses.KEY_UP, "k", "K"):
if scroll > 0:
scroll -= 1
elif c == "/":
# Support starting a search from within the information dialog
if from_jump_to_dialog:
# Avoid recursion
return
if _jump_to_dialog():
# Jumped to a symbol. Cancel the information dialog.
return
# Stay in the information dialog if the jump-to dialog was
# canceled. Resize it in case the terminal was resized while the
# fullscreen jump-to dialog was open.
_resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
elif c in (curses.KEY_LEFT, curses.KEY_BACKSPACE, _ERASE_CHAR,
"\x1B", # \x1B = ESC
"q", "Q", "h", "H"):
return
def _resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win):
# Resizes the info dialog to fill the terminal
screen_height, screen_width = _stdscr.getmaxyx()
top_line_win.resize(1, screen_width)
bot_sep_win.resize(1, screen_width)
help_win_height = len(_INFO_HELP_LINES)
text_win_height = screen_height - help_win_height - 2
if text_win_height >= 1:
text_win.resize(text_win_height, screen_width)
help_win.resize(help_win_height, screen_width)
text_win.mvwin(1, 0)
bot_sep_win.mvwin(1 + text_win_height, 0)
help_win.mvwin(1 + text_win_height + 1, 0)
else:
# Degenerate case. Give up on nice rendering and just prevent errors.
text_win.resize(1, screen_width)
help_win.resize(1, screen_width)
for win in text_win, bot_sep_win, help_win:
win.mvwin(0, 0)
def _draw_info_dialog(node, lines, scroll, top_line_win, text_win,
bot_sep_win, help_win):
text_win_height, text_win_width = text_win.getmaxyx()
# Note: The top row is deliberately updated last. See _draw_main().
#
# Update text display
#
text_win.erase()
for i, line in enumerate(lines[scroll:scroll + text_win_height]):
_safe_addstr(text_win, i, 0, line)
text_win.noutrefresh()
#
# Update bottom separator line
#
bot_sep_win.erase()
# Draw arrows pointing down if the symbol window is scrolled up
if scroll < _max_scroll(lines, text_win):
_safe_hline(bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
bot_sep_win.noutrefresh()
#
# Update help window at bottom
#
help_win.erase()
for i, line in enumerate(_INFO_HELP_LINES):
_safe_addstr(help_win, i, 0, line)
help_win.noutrefresh()
#
# Update top row
#
top_line_win.erase()
# Draw arrows pointing up if the information window is scrolled down. Draw
# them before drawing the title, so the title ends up on top for small
# windows.
if scroll > 0:
_safe_hline(top_line_win, 0, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS)
title = ("Symbol" if isinstance(node.item, Symbol) else
"Choice" if isinstance(node.item, Choice) else
"Menu" if node.item == MENU else
"Comment") + " information"
_safe_addstr(top_line_win, 0, max((text_win_width - len(title))//2, 0),
title)
top_line_win.noutrefresh()
def _info_str(node):
# Returns information about the menu node 'node' as a string.
#
# The helper functions are responsible for adding newlines. This allows
# them to return "" if they don't want to add any output.
if isinstance(node.item, Symbol):
sym = node.item
return (
_name_info(sym) +
_prompt_info(sym) +
"Type: {}\n".format(TYPE_TO_STR[sym.type]) +
_value_info(sym) +
_help_info(sym) +
_direct_dep_info(sym) +
_defaults_info(sym) +
_select_imply_info(sym) +
_kconfig_def_info(sym)
)
if isinstance(node.item, Choice):
choice = node.item
return (
_name_info(choice) +
_prompt_info(choice) +
"Type: {}\n".format(TYPE_TO_STR[choice.type]) +
'Mode: {}\n'.format(choice.str_value) +
_help_info(choice) +
_choice_syms_info(choice) +
_direct_dep_info(choice) +
_defaults_info(choice) +
_kconfig_def_info(choice)
)
# node.item in (MENU, COMMENT)
return _kconfig_def_info(node)
def _name_info(sc):
# Returns a string with the name of the symbol/choice. Names are optional
# for choices.
return "Name: {}\n".format(sc.name) if sc.name else ""
def _prompt_info(sc):
# Returns a string listing the prompts of 'sc' (Symbol or Choice)
s = ""
for node in sc.nodes:
if node.prompt:
s += "Prompt: {}\n".format(node.prompt[0])
return s
def _value_info(sym):
# Returns a string showing 'sym's value
# Only put quotes around the value for string symbols
return "Value: {}\n".format(
'"{}"'.format(sym.str_value)
if sym.orig_type == STRING
else sym.str_value)
def _choice_syms_info(choice):
# Returns a string listing the choice symbols in 'choice'. Adds
# "(selected)" next to the selected one.
s = "Choice symbols:\n"
for sym in choice.syms:
s += " - " + sym.name
if sym is choice.selection:
s += " (selected)"
s += "\n"
return s + "\n"
def _help_info(sc):
# Returns a string with the help text(s) of 'sc' (Symbol or Choice).
# Symbols and choices defined in multiple locations can have multiple help
# texts.
s = "\n"
for node in sc.nodes:
if node.help is not None:
s += "Help:\n\n{}\n\n" \
.format(textwrap.indent(node.help, " "))
return s
def _direct_dep_info(sc):
# Returns a string describing the direct dependencies of 'sc' (Symbol or
# Choice). The direct dependencies are the OR of the dependencies from each
# definition location. The dependencies at each definition location come
# from 'depends on' and dependencies inherited from parent items.
if sc.direct_dep is _kconf.y:
return ""
return 'Direct dependencies (={}):\n{}\n' \
.format(TRI_TO_STR[expr_value(sc.direct_dep)],
_split_expr_info(sc.direct_dep, 2))
def _defaults_info(sc):
# Returns a string describing the defaults of 'sc' (Symbol or Choice)
if not sc.defaults:
return ""
s = "Defaults:\n"
for val, cond in sc.defaults:
s += " - "
if isinstance(sc, Symbol):
s += _expr_str(val)
# Skip the tristate value hint if the expression is just a single
# symbol. _expr_str() already shows its value as a string.
#
# This also avoids showing the tristate value for string/int/hex
# defaults, which wouldn't make any sense.
if isinstance(val, tuple):
s += ' (={})'.format(TRI_TO_STR[expr_value(val)])
else:
# Don't print the value next to the symbol name for choice
# defaults, as it looks a bit confusing
s += val.name
s += "\n"
if cond is not _kconf.y:
s += " Condition (={}):\n{}" \
.format(TRI_TO_STR[expr_value(cond)],
_split_expr_info(cond, 4))
return s + "\n"
def _split_expr_info(expr, indent):
# Returns a string with 'expr' split into its top-level && or || operands,
# with one operand per line, together with the operand's value. This is
# usually enough to get something readable for long expressions. A fancier
# recursive thingy would be possible too.
#
# indent:
# Number of leading spaces to add before the split expression.
if len(split_expr(expr, AND)) > 1:
split_op = AND
op_str = "&&"
else:
split_op = OR
op_str = "||"
s = ""
for i, term in enumerate(split_expr(expr, split_op)):
s += "{}{} {}".format(" "*indent,
" " if i == 0 else op_str,
_expr_str(term))
# Don't bother showing the value hint if the expression is just a
# single symbol. _expr_str() already shows its value.
if isinstance(term, tuple):
s += " (={})".format(TRI_TO_STR[expr_value(term)])
s += "\n"
return s
def _select_imply_info(sym):
# Returns a string with information about which symbols 'select' or 'imply'
# 'sym'. The selecting/implying symbols are grouped according to which
# value they select/imply 'sym' to (n/m/y).
s = ""
def add_sis(expr, val, title):
nonlocal s
# sis = selects/implies
sis = [si for si in split_expr(expr, OR) if expr_value(si) == val]
if sis:
s += title
for si in sis:
s += " - {}\n".format(split_expr(si, AND)[0].name)
s += "\n"
if sym.rev_dep is not _kconf.n:
add_sis(sym.rev_dep, 2,
"Symbols currently y-selecting this symbol:\n")
add_sis(sym.rev_dep, 1,
"Symbols currently m-selecting this symbol:\n")
add_sis(sym.rev_dep, 0,
"Symbols currently n-selecting this symbol (no effect):\n")
if sym.weak_rev_dep is not _kconf.n:
add_sis(sym.weak_rev_dep, 2,
"Symbols currently y-implying this symbol:\n")
add_sis(sym.weak_rev_dep, 1,
"Symbols currently m-implying this symbol:\n")
add_sis(sym.weak_rev_dep, 0,
"Symbols currently n-implying this symbol (no effect):\n")
return s
def _kconfig_def_info(item):
# Returns a string with the definition of 'item' in Kconfig syntax,
# together with the definition location(s) and their include and menu paths
nodes = [item] if isinstance(item, MenuNode) else item.nodes
s = "Kconfig definition{}, with propagated dependencies\n" \
.format("s" if len(nodes) > 1 else "")
s += (len(s) - 1)*"="
for node in nodes:
s += "\n\n" \
"At {}:{}\n" \
"{}" \
"Menu path: {}\n\n" \
"{}" \
.format(node.filename, node.linenr,
_include_path_info(node),
_menu_path_info(node),
textwrap.indent(node.custom_str(_name_and_val_str), " "))
return s
def _include_path_info(node):
if not node.include_path:
# In the top-level Kconfig file
return ""
return "Included via {}\n".format(
" -> ".join("{}:{}".format(filename, linenr)
for filename, linenr in node.include_path))
def _menu_path_info(node):
# Returns a string describing the menu path leading up to 'node'
path = ""
node = _parent_menu(node)
while node is not _kconf.top_node:
# Promptless choices might appear among the parents. Use
# standard_sc_expr_str() for them, so that they show up as
# '<choice (name if any)>'.
path = " -> " + (node.prompt[0] if node.prompt else
standard_sc_expr_str(node.item)) + path
node = _parent_menu(node)
return "(top menu)" + path
def _name_and_val_str(sc):
# Custom symbol/choice printer that shows symbol values after symbols
# Show the values of non-constant (non-quoted) symbols that don't look like
# numbers. Things like 123 are actually symbol references, and only work as
# expected due to undefined symbols getting their name as their value.
# Showing the symbol value for those isn't helpful though.
if isinstance(sc, Symbol) and not sc.is_constant and not _is_num(sc.name):
if not sc.nodes:
# Undefined symbol reference
return "{}(undefined/n)".format(sc.name)
return '{}(={})'.format(sc.name, sc.str_value)
# For other items, use the standard format
return standard_sc_expr_str(sc)
def _expr_str(expr):
# Custom expression printer that shows symbol values
return expr_str(expr, _name_and_val_str)
def _styled_win(style):
# Returns a new curses window with style 'style' and space as the fill
# character. The initial dimensions are (1, 1), so the window needs to be
# sized and positioned separately.
win = curses.newwin(1, 1)
win.bkgdset(" ", _style[style])
return win
def _max_scroll(lst, win):
# Assuming 'lst' is a list of items to be displayed in 'win',
# returns the maximum number of steps 'win' can be scrolled down.
# We stop scrolling when the bottom item is visible.
return max(0, len(lst) - win.getmaxyx()[0])
def _edit_text(c, s, i, hscroll, width):
# Implements text editing commands for edit boxes. Takes a character (which
# could also be e.g. curses.KEY_LEFT) and the edit box state, and returns
# the new state after the character has been processed.
#
# c:
# Character from user
#
# s:
# Current contents of string
#
# i:
# Current cursor index in string
#
# hscroll:
# Index in s of the leftmost character in the edit box, for horizontal
# scrolling
#
# width:
# Width in characters of the edit box
#
# Return value:
# An (s, i, hscroll) tuple for the new state
if c == curses.KEY_LEFT:
if i > 0:
i -= 1
elif c == curses.KEY_RIGHT:
if i < len(s):
i += 1
elif c in (curses.KEY_HOME, "\x01"): # \x01 = CTRL-A
i = 0
elif c in (curses.KEY_END, "\x05"): # \x05 = CTRL-E
i = len(s)
elif c in (curses.KEY_BACKSPACE, _ERASE_CHAR):
if i > 0:
s = s[:i-1] + s[i:]
i -= 1
elif c == curses.KEY_DC:
s = s[:i] + s[i+1:]
elif c == "\x17": # \x17 = CTRL-W
# The \W removes characters like ',' one at a time
new_i = re.search(r"(?:\w*|\W)\s*$", s[:i]).start()
s = s[:new_i] + s[i:]
i = new_i
elif c == "\x0B": # \x0B = CTRL-K
s = s[:i]
elif c == "\x15": # \x15 = CTRL-U
s = s[i:]
i = 0
elif isinstance(c, str):
# Insert character
s = s[:i] + c + s[i:]
i += 1
# Adjust the horizontal scroll so that the cursor never touches the left or
# right edges of the edit box, except when it's at the beginning or the end
# of the string
if i < hscroll + _SCROLL_OFFSET:
hscroll = max(i - _SCROLL_OFFSET, 0)
elif i >= hscroll + width - _SCROLL_OFFSET:
max_scroll = max(len(s) - width + 1, 0)
hscroll = min(i - width + _SCROLL_OFFSET + 1, max_scroll)
return s, i, hscroll
def _load_save_info():
# Returns an information string for load/save dialog boxes
return "(Relative to {})\n\nRefer to your home directory with ~" \
.format(os.path.join(os.getcwd(), ""))
def _msg(title, text):
# Pops up a message dialog that can be dismissed with Space/Enter/ESC
_key_dialog(title, text, " \n")
def _error(text):
# Pops up an error dialog that can be dismissed with Space/Enter/ESC
_msg("Error", text)
def _node_str(node):
# Returns the complete menu entry text for a menu node.
#
# Example return value: "[*] Support for X"
# Calculate the indent to print the item with by checking how many levels
# above it the closest 'menuconfig' item is (this includes menus and
# choices as well as menuconfig symbols)
indent = 0
parent = node.parent
while not parent.is_menuconfig:
indent += _SUBMENU_INDENT
parent = parent.parent
# This approach gives nice alignment for empty string symbols ("() Foo")
s = "{:{}}".format(_value_str(node), 3 + indent)
if _should_show_name(node):
if isinstance(node.item, Symbol):
s += " <{}>".format(node.item.name)
else:
# For choices, use standard_sc_expr_str(). That way they show up as
# '<choice (name if any)>'.
s += " " + standard_sc_expr_str(node.item)
if node.prompt:
if node.item == COMMENT:
s += " *** {} ***".format(node.prompt[0])
else:
s += " " + node.prompt[0]
if isinstance(node.item, Symbol):
sym = node.item
# Print "(NEW)" next to symbols without a user value (from e.g. a
# .config), but skip it for choice symbols in choices in y mode,
# and for symbols of UNKNOWN type (which generate a warning though)
if sym.user_value is None and \
sym.type != UNKNOWN and \
not (sym.choice and sym.choice.tri_value == 2):
s += " (NEW)"
if isinstance(node.item, Choice) and node.item.tri_value == 2:
# Print the prompt of the selected symbol after the choice for
# choices in y mode
sym = node.item.selection
if sym:
for node_ in sym.nodes:
if node_.prompt:
s += " ({})".format(node_.prompt[0])
# Print "--->" next to nodes that have menus that can potentially be
# entered. Add "(empty)" if the menu is empty. We don't allow those to be
# entered.
if node.is_menuconfig:
s += " --->" if _shown_nodes(node) else " ---> (empty)"
return s
def _should_show_name(node):
# Returns True if 'node' is a symbol or choice whose name should shown (if
# any, as names are optional for choices)
# The 'not node.prompt' case only hits in show-all mode, for promptless
# symbols and choices
return not node.prompt or \
(_show_name and isinstance(node.item, (Symbol, Choice)))
def _value_str(node):
# Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu node
item = node.item
if item in (MENU, COMMENT):
return ""
# Wouldn't normally happen, and generates a warning
if item.type == UNKNOWN:
return ""
if item.type in (STRING, INT, HEX):
return "({})".format(item.str_value)
# BOOL or TRISTATE
if _is_y_mode_choice_sym(item):
return "(X)" if item.choice.selection is item else "( )"
tri_val_str = (" ", "M", "*")[item.tri_value]
if len(item.assignable) <= 1:
# Pinned to a single value
return "" if isinstance(item, Choice) else "-{}-".format(tri_val_str)
if item.type == BOOL:
return "[{}]".format(tri_val_str)
# item.type == TRISTATE
if item.assignable == (1, 2):
return "{{{}}}".format(tri_val_str) # {M}/{*}
return "<{}>".format(tri_val_str)
def _is_y_mode_choice_sym(item):
# The choice mode is an upper bound on the visibility of choice symbols, so
# we can check the choice symbols' own visibility to see if the choice is
# in y mode
return isinstance(item, Symbol) and item.choice and item.visibility == 2
def _check_validity(sym, s):
# Returns True if the string 's' is a well-formed value for 'sym'.
# Otherwise, displays an error and returns False.
if sym.type not in (INT, HEX):
# Anything goes for non-int/hex symbols
return True
base = 10 if sym.type == INT else 16
try:
int(s, base)
except ValueError:
_error("'{}' is a malformed {} value"
.format(s, TYPE_TO_STR[sym.type]))
return False
for low_sym, high_sym, cond in sym.ranges:
if expr_value(cond):
low = int(low_sym.str_value, base)
val = int(s, base)
high = int(high_sym.str_value, base)
if not low <= val <= high:
_error("{} is outside the range {}-{}"
.format(s, low_sym.str_value, high_sym.str_value))
return False
break
return True
def _range_info(sym):
# Returns a string with information about the valid range for the symbol
# 'sym', or None if 'sym' doesn't have a range
if sym.type in (INT, HEX):
for low, high, cond in sym.ranges:
if expr_value(cond):
return "Range: {}-{}".format(low.str_value, high.str_value)
return None
def _is_num(name):
# Heuristic to see if a symbol name looks like a number, for nicer output
# when printing expressions. Things like 16 are actually symbol names, only
# they get their name as their value when the symbol is undefined.
try:
int(name)
except ValueError:
if not name.startswith(("0x", "0X")):
return False
try:
int(name, 16)
except ValueError:
return False
return True
def _get_wch_compat(win):
# Decent resizing behavior on PDCurses requires calling resize_term(0, 0)
# after receiving KEY_RESIZE, while NCURSES (usually) handles terminal
# resizing automatically in get(_w)ch() (see the end of the
# resizeterm(3NCURSES) man page).
#
# resize_term(0, 0) reliably fails and does nothing on NCURSES, so this
# hack gives NCURSES/PDCurses compatibility for resizing. I don't know
# whether it would cause trouble for other implementations.
c = win.get_wch()
if c == curses.KEY_RESIZE:
try:
curses.resize_term(0, 0)
except curses.error:
pass
return c
def _warn(*args):
# Temporarily returns from curses to shell mode and prints a warning to
# stderr. The warning would get lost in curses mode.
curses.endwin()
print("menuconfig warning: ", end="", file=sys.stderr)
print(*args, file=sys.stderr)
curses.doupdate()
# Ignore exceptions from some functions that might fail, e.g. for small
# windows. They usually do reasonable things anyway.
def _safe_curs_set(visibility):
try:
curses.curs_set(visibility)
except curses.error:
pass
def _safe_addstr(win, *args):
# Clip the line to avoid wrapping to the next line, which looks glitchy.
# addchstr() would do it for us, but it's not available in the 'curses'
# module.
attr = None
if isinstance(args[0], str):
y, x = win.getyx()
s = args[0]
if len(args) == 2:
attr = args[1]
else:
y, x, s = args[:3]
if len(args) == 4:
attr = args[3]
maxlen = win.getmaxyx()[1] - x
s = s.expandtabs()
try:
# The 'curses' module uses wattr_set() internally if you pass 'attr',
# overwriting the background style, so setting 'attr' to 0 in the first
# case won't do the right thing
if attr is None:
win.addnstr(y, x, s, maxlen)
else:
win.addnstr(y, x, s, maxlen, attr)
except curses.error:
pass
def _safe_addch(win, *args):
try:
win.addch(*args)
except curses.error:
pass
def _safe_hline(win, *args):
try:
win.hline(*args)
except curses.error:
pass
def _safe_vline(win, *args):
try:
win.vline(*args)
except curses.error:
pass
def _safe_move(win, *args):
try:
win.move(*args)
except curses.error:
pass
def _convert_c_lc_ctype_to_utf8():
# See _CONVERT_C_LC_CTYPE_TO_UTF8
if _IS_WINDOWS:
# Windows rarely has issues here, and the PEP 538 implementation avoids
# changing the locale on it. None of the UTF-8 locales below were
# supported from some quick testing either. Play it safe.
return
def _try_set_locale(loc):
try:
locale.setlocale(locale.LC_CTYPE, loc)
return True
except locale.Error:
return False
# Is LC_CTYPE set to the C locale?
if locale.setlocale(locale.LC_CTYPE, None) == "C":
# This list was taken from the PEP 538 implementation in the CPython
# code, in Python/pylifecycle.c
for loc in "C.UTF-8", "C.utf8", "UTF-8":
if _try_set_locale(loc):
print("Note: Your environment is configured to use ASCII. To "
"avoid Unicode issues, LC_CTYPE was changed from the "
"C locale to the {} locale.".format(loc))
break
# Are we running on Windows?
_IS_WINDOWS = (platform.system() == "Windows")
if __name__ == "__main__":
_main()
| YifuLiu/AliOS-Things | components/ble_host/script/Kconfiglib-10.21.0/menuconfig.py | Python | apache-2.0 | 98,166 |
#!/bin/sh
CONFIG_FILE=$1
C_HEAD_FILE=$2
if [ ! -f "$C_HEAD_FILE" ]; then
echo "[INFO] Configuration created"
python3 script/Kconfiglib-10.21.0/genconfig.py --header-path $C_HEAD_FILE --config-out $CONFIG_FILE --defconfig-file ../../../defconfig bt_host/Kconfig
else
python3 script/Kconfiglib-10.21.0/genconfig.py --header-path $C_HEAD_FILE.tmp --config-out $CONFIG_FILE --defconfig-file ../../../defconfig bt_host/Kconfig
grep -Fvf $C_HEAD_FILE.tmp $C_HEAD_FILE
ret1=$?
grep -Fvf $C_HEAD_FILE $C_HEAD_FILE.tmp
ret2=$?
if [ "$ret1$ret2" = "11" ]; then
echo "[INFO] Configuration unchanged"
rm $C_HEAD_FILE.tmp
else
echo "[INFO] Configuration changed"
mv $C_HEAD_FILE.tmp $C_HEAD_FILE
fi
fi
| YifuLiu/AliOS-Things | components/ble_host/script/gen_btconfig.sh | Shell | apache-2.0 | 761 |
/*
* Copyright (C) 2017 C-SKY Microsystems Co., All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <ble_os.h>
#include <yoc/eventid.h>
#include <yoc/uservice.h>
#include <settings/settings.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#include <aos/log.h>
#include <aos/mesh.h>
#include "errno.h"
#define TAG "BLE_MESH"
#define BLE_LOGD(fmt, ...) LOGD(TAG, "[%s]"fmt,__FUNCTION__, ##__VA_ARGS__)
#define BLE_LOGE(fmt, ...) LOGE(TAG, "[%s]"fmt,__FUNCTION__, ##__VA_ARGS__)
typedef struct _ble_mesh_dev_t {
uint8_t is_init;
struct bt_mesh_prov *prov;
struct bt_mesh_comp *comp;
mesh_param_init_t init;
} ble_mesh_dev_t;
ble_mesh_dev_t ble_mesh_dev = {0};
static void ble_stack_event_callback(mesh_event_en event, void *event_data, uint32_t event_len)
{
if (ble_mesh_dev.init.event_cb) {
ble_mesh_dev.init.event_cb(event, event_data);
}
}
static int mesh_output_number_cb(bt_mesh_output_action_t act, bt_u32_t num)
{
evt_data_oob_output_t event_data;
event_data.action = act;
event_data.num = num;
ble_stack_event_callback(EVENT_MESH_OOB_OUTPUT, &event_data, sizeof(event_data));
return 0;
}
static int mesh_output_string_cb(const char *str)
{
evt_data_oob_output_t event_data;
event_data.action = MESH_DISPLAY_STRING;
event_data.str = str;
ble_stack_event_callback(EVENT_MESH_OOB_OUTPUT, &event_data, sizeof(event_data));
return 0;
}
static int mesh_input_cb(bt_mesh_input_action_t act, u8_t size)
{
evt_data_oob_input_t event_data;
event_data.action = act;
event_data.size = size;
ble_stack_event_callback(EVENT_MESH_OOB_INPUT, &event_data, sizeof(event_data));
return 0;
}
static void mesh_link_open_cb(bt_mesh_prov_bearer_t bearer)
{
evt_data_prov_bearer_t event_data;
event_data.bearer = bearer;
ble_stack_event_callback(EVENT_MESH_PROV_START, &event_data, sizeof(event_data));
}
static void mesh_link_close_cb(bt_mesh_prov_bearer_t bearer)
{
evt_data_prov_bearer_t event_data;
event_data.bearer = bearer;
ble_stack_event_callback(EVENT_MESH_PROV_END, &event_data, sizeof(event_data));
}
static void mesh_complete_cb(u16_t net_idx, u16_t addr)
{
evt_data_prov_complete_t event_data;
event_data.net_idx = net_idx;
event_data.addr = addr;
ble_stack_event_callback(EVENT_MESH_PROV_COMPLETE, &event_data, sizeof(event_data));
}
static void mesh_reset_cb(void)
{
ble_stack_event_callback(EVENT_MESH_NODE_RESET, NULL, 0);
}
static void mesh_op_cb(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf, uint32_t opcode)
{
evt_data_mesh_msg_t event_data;
mesh_model_t *mesh_model;
uint8_t mesh_model_count;
int i = 0;
event_data.net_idx = ctx->net_idx;
event_data.app_idx = ctx->app_idx;
event_data.remote_addr = ctx->addr;
event_data.recv_dst = ctx->recv_dst;
event_data.recv_ttl = ctx->recv_ttl;
event_data.msg_len = buf->len;
event_data.msg = buf->data;
if (model->elem_idx < ble_mesh_dev.init.comp->elem_count) {
if (opcode < 0x10000) {
mesh_model_count = ble_mesh_dev.init.comp->elem[model->elem_idx].model_count;
mesh_model = ble_mesh_dev.init.comp->elem[model->elem_idx].models;
} else {
mesh_model_count = ble_mesh_dev.init.comp->elem[model->elem_idx].vnd_model_count;
mesh_model = ble_mesh_dev.init.comp->elem[model->elem_idx].vnd_models;
}
if (model->mod_idx < mesh_model_count) {
i = 0;
while (i < mesh_model[model->mod_idx].op_num) {
if (mesh_model[model->mod_idx].op_list[i].op == opcode) {
if (mesh_model[model->mod_idx].op_list[i].op_cb) {
mesh_model[model->mod_idx].op_list[i].op_cb(&event_data);
}
break;
}
i++;
}
}
}
}
static void mesh_op_cb_dummy(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
}
#if defined(CONFIG_BT_MESH_LOW_POWER)
static void mesh_lpn_cb(u16_t friend_addr, bool established)
{
evt_data_friendship_chanage_t event_data;
event_data.established = established;
event_data.friend_addr = friend_addr;
ble_stack_event_callback(EVENT_MESH_FRIENDSHIP_CHANGE, &event_data, sizeof(event_data));
}
#endif
int ble_stack_mesh_get_local_addr(dev_addr_t *addr)
{
struct bt_le_oob oob;
if (addr == NULL) {
return -BLE_STACK_ERR_NULL;
}
bt_le_oob_get_local(0, &oob);
memcpy(addr, &oob.addr, sizeof(dev_addr_t));
return 0;
}
int ble_stack_mesh_init(mesh_param_init_t *param)
{
int ret;
static struct bt_mesh_prov prov = {0};
static struct bt_mesh_comp comp = {0};
static uint8_t uuid[16] = {0};
if (ble_mesh_dev.is_init) {
return 0;
}
ble_mesh_dev.init = *param;
if (ble_mesh_dev.init.dev_addr) {
bt_addr_le_t addr = *(bt_addr_le_t *)ble_mesh_dev.init.dev_addr;
if (addr.type == BT_ADDR_LE_RANDOM) {
ret = bt_set_id_addr(&addr);
if (ret) {
ret = -BLE_STACK_ERR_PARAM;
return ret;
}
} else if (addr.type == BT_ADDR_LE_PUBLIC) {
#if defined(CONFIG_BT_HCI_VS_EXT)
extern int bt_set_bdaddr(const bt_addr_le_t *addr);
ret = bt_set_bdaddr(&addr);
if (ret) {
ret = -BLE_STACK_ERR_PARAM;
return ret;
}
#endif
}
}
//ret = bt_enable(NULL);
//if (ret) {
// LOGE(TAG, "bt init fail %d", ret);
// return -BLE_STACK_ERR_INIT;
//}
if (ble_mesh_dev.init.dev_name) {
ret = bt_set_name(ble_mesh_dev.init.dev_name);
if (ret) {
ret = -BLE_STACK_ERR_PARAM;
return ret;
}
}
memcpy(uuid, param->prov->dev_uuid, sizeof(uuid));
prov.uuid = uuid;
prov.uri = param->prov->uri;
prov.oob_info = param->prov->oob_info;
prov.static_val = param->prov->cap.static_val;
prov.static_val_len = param->prov->cap.static_val_len;
prov.output_size = param->prov->cap.output_oob_size;
prov.output_actions = param->prov->cap.output_oob_actions;
prov.input_size = param->prov->cap.input_oob_size;
prov.input_actions = param->prov->cap.input_oob_actions;
prov.output_number = mesh_output_number_cb;
prov.output_string = mesh_output_string_cb;
prov.input = mesh_input_cb;
prov.link_open = mesh_link_open_cb;
prov.link_close = mesh_link_close_cb;
prov.complete = mesh_complete_cb;
prov.reset = mesh_reset_cb;
comp.cid = param->comp->cid;
comp.pid = param->comp->pid;
comp.vid = param->comp->vid;
comp.elem_count = param->comp->elem_count;
struct bt_mesh_elem *elems = (struct bt_mesh_elem *) malloc(sizeof(struct bt_mesh_elem) * param->comp->elem_count);
if (elems == NULL) {
return -BLE_STACK_ERR_NULL;
}
comp.elem = elems;
int i, j;
for (i = 0; i < param->comp->elem_count; i++, elems++) {
elems->model_count = param->comp->elem[i].model_count;
elems->vnd_model_count = param->comp->elem[i].vnd_model_count;
if (elems->model_count) {
struct bt_mesh_model *models = (struct bt_mesh_model *) malloc(sizeof(struct bt_mesh_model) * elems->model_count);
if (models == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(models, 0, sizeof(struct bt_mesh_model) * elems->model_count);
elems->models = models;
for (j = 0; j < elems->model_count; j++, models++) {
memset(models->keys, 0xFF, sizeof(models->keys));
if (param->comp->elem[i].models[j].id == MESH_MODEL_ID_CFG_SRV) {
mesh_cfg_srv_t *cfg_srv = param->comp->elem[i].models[j].user_data;
static struct bt_mesh_cfg_srv bt_cfg_srv = {0};
bt_cfg_srv.net_transmit = cfg_srv->net_transmit;
bt_cfg_srv.relay = cfg_srv->relay;
bt_cfg_srv.relay_retransmit = cfg_srv->relay_retransmit;
bt_cfg_srv.beacon = cfg_srv->beacon;
bt_cfg_srv.gatt_proxy = cfg_srv->gatt_proxy;
bt_cfg_srv.frnd = cfg_srv->frnd;
bt_cfg_srv.default_ttl = cfg_srv->default_ttl;
models->id = BT_MESH_MODEL_ID_CFG_SRV;
models->op = bt_mesh_cfg_srv_op;
models->pub = NULL;
models->user_data = &bt_cfg_srv;
} else if (param->comp->elem[i].models[j].id == MESH_MODEL_ID_CFG_CLI) {
static struct bt_mesh_cfg_cli bt_cfg_cli = {};
models->id = BT_MESH_MODEL_ID_CFG_CLI;
models->op = bt_mesh_cfg_cli_op;
models->pub = NULL;
models->user_data = &bt_cfg_cli;
} else if (param->comp->elem[i].models[j].id == MESH_MODEL_ID_HEALTH_SRV) {
struct bt_health_srv_data_t {
struct bt_mesh_health_srv srv;
struct bt_mesh_model_pub bt_pub;
struct net_buf_simple msg;
};
struct bt_health_srv_data_t *srv_data = (struct bt_health_srv_data_t *)malloc(sizeof(struct bt_health_srv_data_t));
if (srv_data == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(srv_data, 0, sizeof(struct bt_health_srv_data_t));
uint8_t *msg_data = (uint8_t *)malloc(param->comp->elem[i].models[j].pub_mesh_len + 1 + 3);
if (msg_data == NULL) {
free(srv_data);
srv_data = NULL;
return -BLE_STACK_ERR_NULL;
}
srv_data->msg.data = msg_data;
srv_data->msg.len = 0;
srv_data->msg.size = param->comp->elem[i].models[j].pub_mesh_len + 1 + 3;
srv_data->msg.__buf = msg_data;
srv_data->bt_pub.msg = &srv_data->msg;
srv_data->bt_pub.update = NULL;
models->id = BT_MESH_MODEL_ID_HEALTH_SRV;
models->op = bt_mesh_health_srv_op;
models->pub = &srv_data->bt_pub;
models->user_data = &srv_data->srv;
} else if (param->comp->elem[i].models[j].id == MESH_MODEL_ID_HEALTH_CLI) {
struct bt_mesh_health_cli *bt_health_cli = (struct bt_mesh_health_cli *)malloc(sizeof(struct bt_mesh_health_cli));
if (bt_health_cli == NULL) {
return -BLE_STACK_ERR_NULL;
}
bt_health_cli->current_status = NULL;
models->id = BT_MESH_MODEL_ID_HEALTH_CLI;
models->op = bt_mesh_health_cli_op;
models->pub = NULL;
models->user_data = bt_health_cli;
} else {
struct bt_mesh_model_op *op = malloc(sizeof(struct bt_mesh_model_op) * (param->comp->elem[i].models[j].op_num + 1));
if (op == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(op, 0, sizeof(struct bt_mesh_model_op) * param->comp->elem[i].models[j].op_num);
int k;
for (k = 0; k < param->comp->elem[i].models[j].op_num; k++) {
op[k].opcode = param->comp->elem[i].models[j].op_list[k].op;
op[k].min_len = 0;
op[k].func = mesh_op_cb_dummy;
op[k].func2 = mesh_op_cb;
}
struct bt_model_pub_data_t {
struct bt_mesh_model_pub bt_pub;
struct net_buf_simple msg;
};
struct bt_model_pub_data_t *pub_data = (struct bt_model_pub_data_t *)malloc(sizeof(struct bt_model_pub_data_t));
if (pub_data == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(pub_data, 0, sizeof(struct bt_model_pub_data_t));
uint8_t *msg_data = (uint8_t *)malloc(param->comp->elem[i].models[j].pub_mesh_len + 1 + 3);
if (msg_data == NULL) {
return -BLE_STACK_ERR_NULL;
}
pub_data->msg.data = msg_data;
pub_data->msg.len = 0;
pub_data->msg.size = param->comp->elem[i].models[j].pub_mesh_len + 1 + 3;
pub_data->msg.__buf = msg_data;
pub_data->bt_pub.msg = &pub_data->msg;
pub_data->bt_pub.update = NULL;
models->id = param->comp->elem[i].models[j].id;
models->op = op;
models->pub = &pub_data->bt_pub;
models->user_data = ¶m->comp->elem[i].models[j];
}
}
}
if (elems->vnd_model_count) {
struct bt_mesh_model *models = (struct bt_mesh_model *) malloc(sizeof(struct bt_mesh_model) * elems->vnd_model_count);
if (models == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(models, 0, sizeof(struct bt_mesh_model) * elems->vnd_model_count);
elems->vnd_models = models;
for (j = 0; j < elems->vnd_model_count; j++, models++) {
memset(models->keys, 0xFF, sizeof(models->keys));
struct bt_mesh_model_op *op = malloc(sizeof(struct bt_mesh_model_op) * (param->comp->elem[i].vnd_models[j].op_num + 1));
if (op == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(op, 0, sizeof(struct bt_mesh_model_op) * param->comp->elem[i].vnd_models[j].op_num);
int k;
for (k = 0; k < param->comp->elem[i].vnd_models[j].op_num; k++) {
op[k].opcode = param->comp->elem[i].vnd_models[j].op_list[k].op;
op[k].min_len = 0;
op[k].func = mesh_op_cb_dummy;
op[k].func2 = mesh_op_cb;
}
struct bt_model_pub_data_t {
struct bt_mesh_model_pub bt_pub;
struct net_buf_simple msg;
};
struct bt_model_pub_data_t *pub_data = (struct bt_model_pub_data_t *)malloc(sizeof(struct bt_model_pub_data_t));
if (pub_data == NULL) {
return -BLE_STACK_ERR_NULL;
}
memset(pub_data, 0, sizeof(struct bt_model_pub_data_t));
uint8_t *msg_data = (uint8_t *)malloc(param->comp->elem[i].vnd_models[j].pub_mesh_len + 1 + 3);
if (msg_data == NULL) {
free(pub_data);
pub_data = NULL;
free(op);
op = NULL;
return -BLE_STACK_ERR_NULL;
}
pub_data->msg.data = msg_data;
pub_data->msg.len = 0;
pub_data->msg.size = param->comp->elem[i].vnd_models[j].pub_mesh_len + 1 + 3;
pub_data->msg.__buf = msg_data;
pub_data->bt_pub.msg = &pub_data->msg;
pub_data->bt_pub.update = NULL;
models->id = param->comp->elem[i].vnd_models[j].id;
models->op = op;
models->pub = &pub_data->bt_pub;
models->user_data = ¶m->comp->elem[i].vnd_models[j];
}
}
}
ble_mesh_dev.comp = ∁
ble_mesh_dev.prov = &prov;
ret = bt_mesh_init(&prov, &comp, NULL);
if (ret) {
LOGE(TAG, "mesh init fail %d", ret);
return -BLE_STACK_ERR_INIT;
}
ble_mesh_dev.is_init = 1;
#if defined(CONFIG_BT_MESH_LOW_POWER)
bt_mesh_lpn_set_cb(mesh_lpn_cb);
#endif
ble_stack_event_callback(EVENT_MESH_STACK_INIT, NULL, 0);
return ret;
}
int ble_stack_mesh_prov_start(mesh_prov_en bearers)
{
int ret;
ret = bt_mesh_prov_enable((bt_mesh_prov_bearer_t)bearers);
if (ret == -EALREADY) {
ret = BLE_STACK_OK;
}
return ret;
}
int ble_stack_mesh_prov_stop(mesh_prov_en bearers)
{
int ret;
ret = bt_mesh_prov_disable((bt_mesh_prov_bearer_t)bearers);
if (ret == -EALREADY) {
ret = BLE_STACK_OK;
}
return ret;
}
int ble_stack_mesh_send(uint16_t net_id,
uint16_t app_id,
uint16_t remote_addr,
uint8_t ttl,
uint8_t elem_id,
uint8_t mod_id,
uint32_t op,
uint8_t *msg,
uint16_t msg_len)
{
struct bt_mesh_model *model = NULL;
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_id,
.app_idx = app_id,
.addr = remote_addr,
.send_ttl = ttl,
};
if (!ble_mesh_dev.is_init) {
return 0;
}
if (elem_id <= ble_mesh_dev.comp->elem_count) {
if (op < 0x10000) {
if (mod_id < ble_mesh_dev.comp->elem[elem_id].model_count) {
model = &ble_mesh_dev.comp->elem[elem_id].models[mod_id];
}
} else {
if (mod_id < ble_mesh_dev.comp->elem[elem_id].vnd_model_count) {
model = &ble_mesh_dev.comp->elem[elem_id].vnd_models[mod_id];
}
}
}
if (model == NULL) {
return -BLE_STACK_ERR_PARAM;
}
NET_BUF_SIMPLE_DEFINE(msg_buf, 2 + msg_len + 4);
bt_mesh_model_msg_init(&msg_buf, op);
net_buf_simple_add_mem(&msg_buf, msg, msg_len);
return bt_mesh_model_send(model, &ctx, &msg_buf, NULL, NULL);
}
int ble_stack_mesh_pub(uint8_t elem_id,
uint8_t mod_id,
uint32_t op,
uint8_t *msg,
uint16_t msg_len)
{
struct bt_mesh_model *model = NULL;
if (!ble_mesh_dev.is_init) {
return 0;
}
if (elem_id <= ble_mesh_dev.comp->elem_count) {
if (op < 0x10000) {
if (mod_id < ble_mesh_dev.comp->elem[elem_id].model_count) {
model = &ble_mesh_dev.comp->elem[elem_id].models[mod_id];
}
} else {
if (mod_id < ble_mesh_dev.comp->elem[elem_id].vnd_model_count) {
model = &ble_mesh_dev.comp->elem[elem_id].vnd_models[mod_id];
}
}
}
if (model == NULL || model->pub == NULL || model->pub->msg == NULL) {
return -BLE_STACK_ERR_PARAM;
}
struct net_buf_simple *msg_buf = model->pub->msg;
bt_mesh_model_msg_init(msg_buf, op);
net_buf_simple_add_mem(msg_buf, msg, msg_len);
return bt_mesh_model_publish(model);
}
int ble_stack_mesh_input_num(uint32_t num)
{
return bt_mesh_input_number(num);
}
int ble_stack_mesh_input_string(char *str)
{
return bt_mesh_input_string(str);
}
int ble_stack_mesh_cfg_beacon_get(uint16_t net_idx, uint16_t addr, uint8_t *status)
{
return bt_mesh_cfg_beacon_get(net_idx, addr, status);
}
int ble_stack_mesh_cfg_beacon_set(uint16_t net_idx, uint16_t addr, uint8_t val, uint8_t *status)
{
return bt_mesh_cfg_beacon_set(net_idx, addr, val, status);
}
int ble_stack_mesh_reset(void)
{
bt_mesh_reset();
return 0;
}
int ble_stack_mesh_lpn_set(int enable)
{
return bt_mesh_lpn_set(enable);
}
int ble_stack_mesh_lpn_poll(void)
{
return bt_mesh_lpn_poll();
}
int ble_stack_mesh_iv_update_test(int enable)
{
bt_mesh_iv_update_test(enable);
return 0;
}
int ble_stack_mesh_iv_update(void)
{
return bt_mesh_iv_update();
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/aos/mesh.c | C | apache-2.0 | 20,718 |
##
# Copyright (C) 2017 C-SKY Microsystems Co., All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.crg/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.
##
ifeq ($(CONFIG_BT), y)
L_PATH := $(call cur-dir)
include $(DEFINE_LOCAL)
L_MODULE := libbt_mesh
L_CFLAGS := -Wall
#L_CFLAGS := -D__ORDER_LITTLE_ENDIAN__=1 -D__ORDER_BIG_ENDIAN__=2 -D__BYTE_ORDER__=__ORDER_LITTLE_ENDIAN__
include $(L_PATH)/../bt_defconfig
L_INCS += $(L_PATH)/inc $(L_PATH)/inc/api $(L_PATH)/inc/port $(L_PATH)/../bt_host/port/include $(L_PATH)/../bt_host/port/aos/include $(L_PATH)/../bt_host/host $(L_PATH)/../crypto $(L_PATH)/../bt_host/
L_INCS += $(L_PATH)/../bt_crypto/include
ifeq ($(BT_HOST_CRYPTO), y)
L_INCS += $(L_PATH)/../crypto/tinycrypt/include
endif
ifeq ($(CONFIG_BT_MESH), y)
L_SRCS += src/main.c \
src/adv.c \
src/beacon.c \
src/net.c \
src/transport.c \
src/crypto.c \
src/access.c \
src/cfg_srv.c \
src/health_srv.c
ifeq ($(CONFIG_BT_SETTINGS), y)
L_SRCS += src/settings.c
endif
ifeq ($(CONFIG_BT_MESH_LOW_POWER), y)
L_SRCS += src/lpn.c
endif
ifeq ($(CONFIG_BT_MESH_FRIEND), y)
L_SRCS += src/friend.c
endif
ifeq ($(CONFIG_BT_MESH_PROV), y)
L_SRCS += src/prov.c
endif
ifeq ($(CONFIG_BT_MESH_PROXY), y)
L_SRCS += src/proxy.c
endif
ifeq ($(CONFIG_BT_MESH_CFG_CLI), y)
L_SRCS += src/cfg_cli.c
endif
ifeq ($(CONFIG_BT_MESH_HEALTH_CLI), y)
L_SRCS += src/health_cli.c
endif
ifeq ($(CONFIG_BT_MESH_SELF_TEST), y)
L_SRCS += src/test.c
endif
ifeq ($(CONFIG_BT_MESH_PROVISIONER), y)
L_SRCS += src/provisioner_beacon.c \
src/provisioner_main.c \
src/provisioner_prov.c \
src/provisioner_proxy.c \
ref_impl/mesh_hal_ble.c
endif
ifeq ($(CONFIG_BT_MESH_EVENT_CALLBACK), y)
L_SRCS += ref_impl/mesh_event_port.c
endif
L_SRCS += aos/mesh.c
endif
include $(BUILD_MODULE)
endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/build.mk | Makefile | apache-2.0 | 2,353 |
/* Bluetooth Mesh */
#ifndef __ACCESS_H
#define __ACCESS_H
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
/* bt_mesh_model.flags */
enum {
BT_MESH_MOD_BIND_PENDING = BIT(0),
BT_MESH_MOD_SUB_PENDING = BIT(1),
BT_MESH_MOD_PUB_PENDING = BIT(2),
};
void bt_mesh_elem_register(struct bt_mesh_elem *elem, u8_t count);
u8_t bt_mesh_elem_count(void);
/* Find local element based on unicast or group address */
struct bt_mesh_elem *bt_mesh_elem_find(u16_t addr);
struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem, u16_t company, u16_t id);
struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem *elem, u16_t id);
u16_t *bt_mesh_model_find_group(struct bt_mesh_model *mod, u16_t addr);
bool bt_mesh_fixed_group_match(u16_t addr);
void bt_mesh_model_foreach(void (*func)(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary,
void *user_data),
void *user_data);
bt_s32_t bt_mesh_model_pub_period_get(struct bt_mesh_model *mod);
void bt_mesh_comp_provision(u16_t addr);
void bt_mesh_comp_unprovision(void);
u16_t bt_mesh_primary_addr(void);
const struct bt_mesh_comp *bt_mesh_comp_get(void);
struct bt_mesh_model *bt_mesh_model_get(bool vnd, u8_t elem_idx, u8_t mod_idx);
void bt_mesh_model_recv(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
int bt_mesh_comp_register(const struct bt_mesh_comp *comp);
u16_t bt_mesh_primary_addr(void);
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/access.h | C | apache-2.0 | 1,531 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
/* Maximum advertising data payload for a single data type */
#define BT_MESH_ADV_DATA_SIZE 29
/* The user data is a pointer (4 bytes) to struct bt_mesh_adv */
#define BT_MESH_ADV_USER_DATA_SIZE 4
#define BT_MESH_ADV(buf) (*(struct bt_mesh_adv **)net_buf_user_data(buf))
enum bt_mesh_adv_type {
BT_MESH_ADV_PROV,
BT_MESH_ADV_DATA,
BT_MESH_ADV_BEACON,
BT_MESH_ADV_URI,
};
typedef void (*bt_mesh_adv_func_t)(struct net_buf *buf, u16_t duration, int err, void *user_data);
struct bt_mesh_adv {
const struct bt_mesh_send_cb *cb;
void *cb_data;
u8_t type:2, busy:1;
u8_t xmit;
#ifdef GENIE_ULTRA_PROV
u8_t tiny_adv;
#endif
union {
/* Address, used e.g. for Friend Queue messages */
u16_t addr;
/* For transport layer segment sending */
struct {
u8_t attempts;
} seg;
};
};
typedef struct bt_mesh_adv *(*bt_mesh_adv_alloc_t)(int id);
typedef void (*vendor_beacon_cb)(const bt_addr_le_t *addr, s8_t rssi, u8_t adv_type, void *user_data, uint16_t len);
/* xmit_count: Number of retransmissions, i.e. 0 == 1 transmission */
struct net_buf *bt_mesh_adv_create(enum bt_mesh_adv_type type, u8_t xmit, bt_s32_t timeout);
struct net_buf *bt_mesh_adv_create_from_pool(struct net_buf_pool *pool, bt_mesh_adv_alloc_t get_id,
enum bt_mesh_adv_type type, u8_t xmit, bt_s32_t timeout);
void bt_mesh_adv_send(struct net_buf *buf, const struct bt_mesh_send_cb *cb, void *cb_data);
void bt_mesh_adv_update(void);
void bt_mesh_adv_init(void);
int bt_mesh_scan_enable(void);
int bt_mesh_scan_disable(void);
int bt_mesh_adv_enable(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len);
int bt_mesh_adv_disable();
int bt_mesh_adv_scan_update();
int bt_mesh_scan_enable(void);
int bt_mesh_adv_vnd_scan_register(vendor_beacon_cb);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/adv.h | C | apache-2.0 | 2,061 |
/** @file
* @brief Bluetooth Mesh Profile APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_H
#define __BT_MESH_H
#include <stddef.h>
#include <ble_config.h>
#include <ble_os.h>
#include <ble_mesh_config.h>
#include <api/mesh/access.h>
#include <api/mesh/main.h>
#include <api/mesh/cfg_srv.h>
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
#include <api/mesh/ctrl_relay.h>
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
#include <api/mesh/health_srv.h>
#if defined(CONFIG_BT_MESH_CFG_CLI)
#include <api/mesh/cfg_cli.h>
#endif
#if defined(CONFIG_BT_MESH_HEALTH_CLI)
#include <api/mesh/health_cli.h>
#endif
#if defined(CONFIG_BT_MESH_GATT_PROXY)
#include <api/mesh/proxy.h>
#endif
#endif /* __BT_MESH_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh.h | C | apache-2.0 | 827 |
/** @file
* @brief Bluetooth Mesh Access Layer APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_ACCESS_H
#define __BT_MESH_ACCESS_H
/**
* @brief Bluetooth Mesh Access Layer
* @defgroup bt_mesh_access Bluetooth Mesh Access Layer
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
#define BT_MESH_ADDR_UNASSIGNED 0x0000
#define BT_MESH_ADDR_ALL_NODES 0xffff
#define BT_MESH_ADDR_PROXIES 0xfffc
#define BT_MESH_ADDR_FRIENDS 0xfffd
#define BT_MESH_ADDR_RELAYS 0xfffe
#define BT_MESH_KEY_UNUSED 0xffff
#define BT_MESH_KEY_DEV 0xfffe
/*[Genie begin] add by lgy at 2020-09-10*/
#define BT_MESH_ADDR_TMALL_GENIE 0xf000
#define BT_MESH_ADDR_GENIE_ALL_NODES 0xcfff
/*[Genie end] add by lgy at 2020-09-10*/
/** Helper to define a mesh element within an array.
*
* In case the element has no SIG or Vendor models the helper
* macro BT_MESH_MODEL_NONE can be given instead.
*
* @param _loc Location Descriptor.
* @param _mods Array of models.
* @param _vnd_mods Array of vendor models.
*/
#define BT_MESH_ELEM(_loc, _mods, _vnd_mods, _grop_addr) \
{ \
.loc = (_loc), .model_count = ARRAY_SIZE(_mods), .models = (_mods), .vnd_model_count = ARRAY_SIZE(_vnd_mods), \
.vnd_models = (_vnd_mods), .grop_addr = (_grop_addr), \
}
/** Abstraction that describes a Mesh Element */
struct bt_mesh_elem {
/* Unicast Address. Set at runtime during provisioning. */
u16_t addr;
u16_t grop_addr;
/* Location Descriptor (GATT Bluetooth Namespace Descriptors) */
u16_t loc;
u8_t model_count;
u8_t vnd_model_count;
struct bt_mesh_model *models;
struct bt_mesh_model *vnd_models;
};
/* Foundation Models */
#define BT_MESH_MODEL_ID_CFG_SRV 0x0000
#define BT_MESH_MODEL_ID_CFG_CLI 0x0001
#define BT_MESH_MODEL_ID_HEALTH_SRV 0x0002
#define BT_MESH_MODEL_ID_HEALTH_CLI 0x0003
/* Models from the Mesh Model Specification */
#define BT_MESH_MODEL_ID_GEN_ONOFF_SRV 0x1000
#define BT_MESH_MODEL_ID_GEN_ONOFF_CLI 0x1001
#define BT_MESH_MODEL_ID_GEN_LEVEL_SRV 0x1002
#define BT_MESH_MODEL_ID_GEN_LEVEL_CLI 0x1003
#define BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV 0x1004
#define BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI 0x1005
#define BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV 0x1006
#define BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV 0x1007
#define BT_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI 0x1008
#define BT_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV 0x1009
#define BT_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV 0x100a
#define BT_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI 0x100b
#define BT_MESH_MODEL_ID_GEN_BATTERY_SRV 0x100c
#define BT_MESH_MODEL_ID_GEN_BATTERY_CLI 0x100d
#define BT_MESH_MODEL_ID_GEN_LOCATION_SRV 0x100e
#define BT_MESH_MODEL_ID_GEN_LOCATION_SETUPSRV 0x100f
#define BT_MESH_MODEL_ID_GEN_LOCATION_CLI 0x1010
#define BT_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV 0x1011
#define BT_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV 0x1012
#define BT_MESH_MODEL_ID_GEN_USER_PROP_SRV 0x1013
#define BT_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV 0x1014
#define BT_MESH_MODEL_ID_GEN_PROP_CLI 0x1015
#define BT_MESH_MODEL_ID_SENSOR_SRV 0x1100
#define BT_MESH_MODEL_ID_SENSOR_SETUP_SRV 0x1101
#define BT_MESH_MODEL_ID_SENSOR_CLI 0x1102
#define BT_MESH_MODEL_ID_TIME_SRV 0x1200
#define BT_MESH_MODEL_ID_TIME_SETUP_SRV 0x1201
#define BT_MESH_MODEL_ID_TIME_CLI 0x1202
#define BT_MESH_MODEL_ID_SCENE_SRV 0x1203
#define BT_MESH_MODEL_ID_SCENE_SETUP_SRV 0x1204
#define BT_MESH_MODEL_ID_SCENE_CLI 0x1205
#define BT_MESH_MODEL_ID_SCHEDULER_SRV 0x1206
#define BT_MESH_MODEL_ID_SCHEDULER_SETUP_SRV 0x1207
#define BT_MESH_MODEL_ID_SCHEDULER_CLI 0x1208
#define BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV 0x1300
#define BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV 0x1301
#define BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI 0x1302
#define BT_MESH_MODEL_ID_LIGHT_CTL_SRV 0x1303
#define BT_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV 0x1304
#define BT_MESH_MODEL_ID_LIGHT_CTL_CLI 0x1305
#define BT_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV 0x1306
#define BT_MESH_MODEL_ID_LIGHT_HSL_SRV 0x1307
#define BT_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV 0x1308
#define BT_MESH_MODEL_ID_LIGHT_HSL_CLI 0x1309
#define BT_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV 0x130a
#define BT_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV 0x130b
#define BT_MESH_MODEL_ID_LIGHT_XYL_SRV 0x130c
#define BT_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV 0x130d
#define BT_MESH_MODEL_ID_LIGHT_XYL_CLI 0x130e
#define BT_MESH_MODEL_ID_LIGHT_LC_SRV 0x130f
#define BT_MESH_MODEL_ID_LIGHT_LC_SETUPSRV 0x1310
#define BT_MESH_MODEL_ID_LIGHT_LC_CLI 0x1311
/** Message sending context. */
struct bt_mesh_msg_ctx {
/** NetKey Index of the subnet to send the message on. */
u16_t net_idx;
/** AppKey Index to encrypt the message with. */
u16_t app_idx;
/** Remote address. */
u16_t addr;
/** Destination address of a received message. Not used for sending. */
u16_t recv_dst;
/** Received TTL value. Not used for sending. */
u8_t recv_ttl:7;
/** Force sending reliably by using segment acknowledgement */
u8_t send_rel:1;
/** TTL, or BT_MESH_TTL_DEFAULT for default TTL. */
u8_t send_ttl;
};
struct bt_mesh_model_op {
/* OpCode encoded using the BT_MESH_MODEL_OP_* macros */
bt_u32_t opcode;
/* Minimum required message length */
size_t min_len;
/* Message handler for the opcode */
void (*func)(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf);
void (*func2)(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf,
bt_u32_t opcode);
};
#define BT_MESH_MODEL_OP_1(b0) (b0)
#define BT_MESH_MODEL_OP_2(b0, b1) (((b0) << 8) | (b1))
#define BT_MESH_MODEL_OP_3(b0, cid) ((((b0) << 16) | 0xc00000) | (cid))
#define BT_MESH_MODEL_OP_END \
{ \
0, 0, NULL \
}
#define BT_MESH_MODEL_NO_OPS ((struct bt_mesh_model_op[]){ BT_MESH_MODEL_OP_END })
/** Helper to define an empty model array */
#define BT_MESH_MODEL_NONE ((struct bt_mesh_model[]){})
#define BT_MESH_MODEL(_id, _op, _pub, _user_data) \
{ \
.id = (_id), .op = _op, .keys = { [0 ...(CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = BT_MESH_KEY_UNUSED }, \
.pub = _pub, .groups = { [0 ...(CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = BT_MESH_ADDR_UNASSIGNED }, \
.user_data = _user_data, \
}
#define BT_MESH_MODEL_VND(_company, _id, _op, _pub, _user_data) \
{ \
.vnd.company = (_company), .vnd.id = (_id), .op = _op, .pub = _pub, \
.keys = { [0 ...(CONFIG_BT_MESH_MODEL_KEY_COUNT - 1)] = BT_MESH_KEY_UNUSED }, \
.groups = { [0 ...(CONFIG_BT_MESH_MODEL_GROUP_COUNT - 1)] = BT_MESH_ADDR_UNASSIGNED }, \
.user_data = _user_data, \
}
/** @def BT_MESH_TRANSMIT
*
* @brief Encode transmission count & interval steps.
*
* @param count Number of retransmissions (first transmission is excluded).
* @param int_ms Interval steps in milliseconds. Must be greater than 0,
* less than or equal to 320, and a multiple of 10.
*
* @return Mesh transmit value that can be used e.g. for the default
* values of the configuration model data.
*/
#define BT_MESH_TRANSMIT(count, int_ms) ((count) | (((int_ms / 10) - 1) << 3))
/** @def BT_MESH_TRANSMIT_COUNT
*
* @brief Decode transmit count from a transmit value.
*
* @param transmit Encoded transmit count & interval value.
*
* @return Transmission count (actual transmissions is N + 1).
*/
#define BT_MESH_TRANSMIT_COUNT(transmit) (((transmit) & (u8_t)BIT_MASK(3)))
/** @def BT_MESH_TRANSMIT_INT
*
* @brief Decode transmit interval from a transmit value.
*
* @param transmit Encoded transmit count & interval value.
*
* @return Transmission interval in milliseconds.
*/
#define BT_MESH_TRANSMIT_INT(transmit) ((((transmit) >> 3) + 1) * 10)
/** @def BT_MESH_PUB_TRANSMIT
*
* @brief Encode Publish Retransmit count & interval steps.
*
* @param count Number of retransmissions (first transmission is excluded).
* @param int_ms Interval steps in milliseconds. Must be greater than 0
* and a multiple of 50.
*
* @return Mesh transmit value that can be used e.g. for the default
* values of the configuration model data.
*/
#define BT_MESH_PUB_TRANSMIT(count, int_ms) BT_MESH_TRANSMIT(count, (int_ms) / 5)
/** @def BT_MESH_PUB_TRANSMIT_COUNT
*
* @brief Decode Publish Retransmit count from a given value.
*
* @param transmit Encoded Publish Retransmit count & interval value.
*
* @return Retransmission count (actual transmissions is N + 1).
*/
#define BT_MESH_PUB_TRANSMIT_COUNT(transmit) BT_MESH_TRANSMIT_COUNT(transmit)
/** @def BT_MESH_PUB_TRANSMIT_INT
*
* @brief Decode Publish Retransmit interval from a given value.
*
* @param transmit Encoded Publish Retransmit count & interval value.
*
* @return Transmission interval in milliseconds.
*/
#define BT_MESH_PUB_TRANSMIT_INT(transmit) ((((transmit) >> 3) + 1) * 50)
/** Model publication context.
*
* The context should primarily be created using the
* BT_MESH_MODEL_PUB_DEFINE macro.
*/
struct bt_mesh_model_pub {
/** The model the context belongs to. Initialized by the stack. */
struct bt_mesh_model *mod;
u16_t addr; /**< Publish Address. */
u16_t key; /**< Publish AppKey Index. */
u8_t ttl; /**< Publish Time to Live. */
u8_t retransmit; /**< Retransmit Count & Interval Steps. */
u8_t period; /**< Publish Period. */
u8_t period_div:4, /**< Divisor for the Period. */
cred:1, /**< Friendship Credentials Flag. */
fast_period:1, /**< Use FastPeriodDivisor */
count:3; /**< Retransmissions left. */
bt_u32_t period_start; /**< Start of the current period. */
/** @brief Publication buffer, containing the publication message.
*
* This will get correctly created when the publication context
* has been defined using the BT_MESH_MODEL_PUB_DEFINE macro.
*
* BT_MESH_MODEL_PUB_DEFINE(name, update, size);
*/
struct net_buf_simple *msg;
/** @brief Callback for updating the publication buffer.
*
* When set to NULL, the model is assumed not to support
* periodic publishing. When set to non-NULL the callback
* will be called periodically and is expected to update
* @ref bt_mesh_model_pub.msg with a valid publication
* message.
*
* @param mod The Model the Publication Context belogs to.
*
* @return Zero on success or (negative) error code otherwise.
*/
int (*update)(struct bt_mesh_model *mod);
/** Publish Period Timer. Only for stack-internal use. */
struct k_delayed_work timer;
};
/** @def BT_MESH_MODEL_PUB_DEFINE
*
* Define a model publication context.
*
* @param _name Variable name given to the context.
* @param _update Optional message update callback (may be NULL).
* @param _msg_len Length of the publication message.
*/
#define BT_MESH_MODEL_PUB_DEFINE(_name, _update, _msg_len) \
NET_BUF_SIMPLE_DEFINE_STATIC(bt_mesh_pub_msg_##_name, _msg_len); \
static struct bt_mesh_model_pub _name = { \
.update = _update, \
.msg = &bt_mesh_pub_msg_##_name, \
}
/** Abstraction that describes a Mesh Model instance */
struct bt_mesh_model {
union {
u16_t id;
struct {
u16_t company;
u16_t id;
} vnd;
};
/* Internal information, mainly for persistent storage */
u8_t elem_idx; /* Belongs to Nth element */
u8_t mod_idx; /* Is the Nth model in the element */
u16_t flags; /* Information about what has changed */
/* Model Publication */
struct bt_mesh_model_pub *pub;
/* AppKey List */
u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT];
/* Subscription List (group or virtual addresses) */
u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT];
const struct bt_mesh_model_op *op;
/* Model-specific user data */
void *user_data;
};
struct bt_mesh_send_cb {
void (*start)(u16_t duration, int err, void *cb_data);
void (*end)(int err, void *cb_data);
};
void bt_mesh_model_msg_init(struct net_buf_simple *msg, bt_u32_t opcode);
/** Special TTL value to request using configured default TTL */
#define BT_MESH_TTL_DEFAULT 0xff
/** Maximum allowed TTL value */
#define BT_MESH_TTL_MAX 0x7f
/**
* @brief Send an Access Layer message.
*
* @param model Mesh (client) Model that the message belongs to.
* @param ctx Message context, includes keys, TTL, etc.
* @param msg Access Layer payload (the actual message to be sent).
* @param cb Optional "message sent" callback.
* @param cb_data User data to be passed to the callback.
*
* @return 0 on success, or (negative) error code on failure.
*/
int bt_mesh_model_send(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *msg,
const struct bt_mesh_send_cb *cb, void *cb_data);
/**
* @brief Send a model publication message.
*
* Before calling this function, the user needs to ensure that the model
* publication message (@ref bt_mesh_model_pub.msg) contains a valid
* message to be sent. Note that this API is only to be used for
* non-period publishing. For periodic publishing the app only needs
* to make sure that @ref bt_mesh_model_pub.msg contains a valid message
* whenever the @ref bt_mesh_model_pub.update callback is called.
*
* @param model Mesh (client) Model that's publishing the message.
*
* @return 0 on success, or (negative) error code on failure.
*/
int bt_mesh_model_publish(struct bt_mesh_model *model);
/**
* @brief Get the element that a model belongs to.
*
* @param mod Mesh model.
*
* @return Pointer to the element that the given model belongs to.
*/
struct bt_mesh_elem *bt_mesh_model_elem(struct bt_mesh_model *mod);
struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem, u16_t company, u16_t id);
u16_t bt_mesh_model_get_netkey_id(struct bt_mesh_elem *elem);
u16_t bt_mesh_model_get_appkey_id(struct bt_mesh_elem *elem, struct bt_mesh_model *p_model);
/* Find local element based on element id */
struct bt_mesh_elem *bt_mesh_elem_find_by_id(u8_t id);
/** Node Composition */
struct bt_mesh_comp {
u16_t cid;
u16_t pid;
u16_t vid;
size_t elem_count;
struct bt_mesh_elem *elem;
};
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_ACCESS_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/access.h | C | apache-2.0 | 14,357 |
/** @file
* @brief Bluetooth Mesh Configuration Client Model APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_CFG_CLI_H
#define __BT_MESH_CFG_CLI_H
/**
* @brief Bluetooth Mesh
* @defgroup bt_mesh_cfg_cli Bluetooth Mesh Configuration Client Model
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/** Mesh Configuration Client Model Context */
struct bt_mesh_cfg_cli {
struct bt_mesh_model *model;
struct k_sem op_sync;
bt_u32_t op_pending;
void *op_param;
};
extern const struct bt_mesh_model_op bt_mesh_cfg_cli_op[];
extern struct bt_mesh_cfg_cli g_cfg_cli;
#define BT_MESH_MODEL_CFG_CLI(cli_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_CLI, bt_mesh_cfg_cli_op, NULL, cli_data)
#define MESH_MODEL_CFG_CLI_NULL() BT_MESH_MODEL_CFG_CLI(&g_cfg_cli)
int bt_mesh_cfg_comp_data_get(u16_t net_idx, u16_t addr, u8_t page, u8_t *status, struct net_buf_simple *comp);
int bt_mesh_cfg_beacon_get(u16_t net_idx, u16_t addr, u8_t *status);
int bt_mesh_cfg_beacon_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status);
int bt_mesh_cfg_ttl_get(u16_t net_idx, u16_t addr, u8_t *ttl);
int bt_mesh_cfg_ttl_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *ttl);
int bt_mesh_cfg_friend_get(u16_t net_idx, u16_t addr, u8_t *status);
int bt_mesh_cfg_friend_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status);
int bt_mesh_cfg_gatt_proxy_get(u16_t net_idx, u16_t addr, u8_t *status);
int bt_mesh_cfg_gatt_proxy_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status);
int bt_mesh_cfg_relay_get(u16_t net_idx, u16_t addr, u8_t *status, u8_t *transmit);
int bt_mesh_cfg_relay_set(u16_t net_idx, u16_t addr, u8_t new_relay, u8_t new_transmit, u8_t *status, u8_t *transmit);
int bt_mesh_cfg_net_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, const u8_t net_key[16], u8_t *status);
int bt_mesh_cfg_app_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, u16_t key_app_idx, const u8_t app_key[16],
u8_t *status);
int bt_mesh_cfg_mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u8_t *status);
int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u16_t cid,
u8_t *status);
int bt_mesh_cfg_mod_app_unbind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id,
u8_t *status);
int bt_mesh_cfg_mod_app_unbind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id,
u16_t cid, u8_t *status);
int bt_mesh_cfg_net_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, const u8_t net_key[16], u8_t *status);
int bt_mesh_cfg_app_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, u16_t key_app_idx, const u8_t app_key[16],
u8_t *status);
/** @def BT_MESH_PUB_PERIOD_100MS
*
* @brief Helper macro to encode model publication period in units of 100ms
*
* @param steps Number of 100ms steps.
*
* @return Encoded value that can be assigned to bt_mesh_cfg_mod_pub.period
*/
#define BT_MESH_PUB_PERIOD_100MS(steps) ((steps) & BIT_MASK(6))
/** @def BT_MESH_PUB_PERIOD_SEC
*
* @brief Helper macro to encode model publication period in units of 1 second
*
* @param steps Number of 1 second steps.
*
* @return Encoded value that can be assigned to bt_mesh_cfg_mod_pub.period
*/
#define BT_MESH_PUB_PERIOD_SEC(steps) (((steps) & BIT_MASK(6)) | (1 << 6))
/** @def BT_MESH_PUB_PERIOD_10SEC
*
* @brief Helper macro to encode model publication period in units of 10
* seconds
*
* @param steps Number of 10 second steps.
*
* @return Encoded value that can be assigned to bt_mesh_cfg_mod_pub.period
*/
#define BT_MESH_PUB_PERIOD_10SEC(steps) (((steps) & BIT_MASK(6)) | (2 << 6))
/** @def BT_MESH_PUB_PERIOD_10MIN
*
* @brief Helper macro to encode model publication period in units of 10
* minutes
*
* @param steps Number of 10 minute steps.
*
* @return Encoded value that can be assigned to bt_mesh_cfg_mod_pub.period
*/
#define BT_MESH_PUB_PERIOD_10MIN(steps) (((steps) & BIT_MASK(6)) | (3 << 6))
struct bt_mesh_cfg_mod_pub {
u16_t addr;
u16_t app_idx;
bool cred_flag;
u8_t ttl;
u8_t period;
u8_t transmit;
};
int bt_mesh_cfg_mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub,
u8_t *status);
int bt_mesh_cfg_mod_pub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status);
int bt_mesh_cfg_mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub,
u8_t *status);
int bt_mesh_cfg_mod_pub_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status);
int bt_mesh_cfg_mod_sub_add(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u8_t *status);
int bt_mesh_cfg_mod_sub_get(u16_t net_idx, u16_t addr, u16_t mod_id, uint16_t *sub, u8_t *status);
int bt_mesh_cfg_mod_sub_get_vnd(u16_t net_idx, u16_t addr, u16_t mod_id, u16_t cid, uint16_t *sub, u8_t *status);
int bt_mesh_cfg_mod_sub_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid,
u8_t *status);
int bt_mesh_cfg_mod_sub_del(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u8_t *status);
int bt_mesh_cfg_mod_sub_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid,
u8_t *status);
int bt_mesh_cfg_mod_sub_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id,
u8_t *status);
int bt_mesh_cfg_mod_sub_overwrite_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id,
u16_t cid, u8_t *status);
int bt_mesh_cfg_mod_sub_va_add(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_mod_sub_va_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_mod_sub_va_del(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_mod_sub_va_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_mod_sub_va_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_mod_sub_va_overwrite_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status);
int bt_mesh_cfg_node_reset(u16_t net_idx, u16_t addr);
int bt_mesh_cfg_krp_set(u16_t net_idx, u16_t addr, u16_t key_net_idx, u8_t *phase, u8_t *status);
int bt_mesh_cfg_krp_get(u16_t net_idx, u16_t addr, u16_t key_net_idx, u8_t *phase, u8_t *status);
struct bt_mesh_cfg_hb_sub {
u16_t src;
u16_t dst;
u8_t period;
u8_t count;
u8_t min;
u8_t max;
};
int bt_mesh_cfg_hb_sub_set(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_sub *sub, u8_t *status);
int bt_mesh_cfg_hb_sub_get(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_sub *sub, u8_t *status);
struct bt_mesh_cfg_hb_pub {
u16_t dst;
u8_t count;
u8_t period;
u8_t ttl;
u16_t feat;
u16_t net_idx;
};
int bt_mesh_cfg_hb_pub_set(u16_t net_idx, u16_t addr, const struct bt_mesh_cfg_hb_pub *pub, u8_t *status);
int bt_mesh_cfg_hb_pub_get(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_pub *pub, u8_t *status);
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
int bt_mesh_cfg_ctrl_relay_get(u16_t net_idx, u16_t addr, struct ctrl_relay_param *cr, u8_t *status);
int bt_mesh_cfg_ctrl_relay_set(u16_t net_idx, u16_t addr, const struct ctrl_relay_param *cr, u8_t *status);
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
bt_s32_t bt_mesh_cfg_cli_timeout_get(void);
void bt_mesh_cfg_cli_timeout_set(bt_s32_t timeout);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_CFG_CLI_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/cfg_cli.h | C | apache-2.0 | 8,768 |
/** @file
* @brief Bluetooth Mesh Configuration Server Model APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_CFG_SRV_H
#define __BT_MESH_CFG_SRV_H
/**
* @brief Bluetooth Mesh
* @defgroup bt_mesh_cfg_srv Bluetooth Mesh Configuration Server Model
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/** Mesh Configuration Server Model Context */
struct bt_mesh_cfg_srv {
struct bt_mesh_model *model;
u8_t net_transmit; /* Network Transmit state */
u8_t relay; /* Relay Mode state */
u8_t relay_retransmit; /* Relay Retransmit state */
u8_t beacon; /* Secure Network Beacon state */
u8_t gatt_proxy; /* GATT Proxy state */
u8_t frnd; /* Friend state */
u8_t default_ttl; /* Default TTL */
/* Heartbeat Publication */
struct bt_mesh_hb_pub {
struct k_delayed_work timer;
u16_t dst;
u16_t count;
u8_t period;
u8_t ttl;
u16_t feat;
u16_t net_idx;
} hb_pub;
/* Heartbeat Subscription */
struct bt_mesh_hb_sub {
s64_t expiry;
u16_t src;
u16_t dst;
u16_t count;
u8_t min_hops;
u8_t max_hops;
/* Optional subscription tracking function */
void (*func)(u8_t hops, u16_t feat);
} hb_sub;
};
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
typedef struct {
uint8_t status;
uint16_t netkey_idx;
uint16_t appkey_idx;
}appkey_status;
#endif
extern const struct bt_mesh_model_op bt_mesh_cfg_srv_op[];
extern struct bt_mesh_cfg_srv g_cfg_srv;
#define BT_MESH_MODEL_CFG_SRV(srv_data) \
BT_MESH_MODEL(BT_MESH_MODEL_ID_CFG_SRV, \
bt_mesh_cfg_srv_op, NULL, srv_data)
#define MESH_MODEL_CFG_SRV_NULL() BT_MESH_MODEL_CFG_SRV(&g_cfg_srv)
u8_t bt_mesh_mod_bind(struct bt_mesh_model *model, u16_t key_idx);
u8_t bt_mesh_mod_sub_add(struct bt_mesh_model *model, u16_t sub_addr);
u8_t bt_mesh_mod_pub_set(struct bt_mesh_model *model, u16_t pub_addr);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_CFG_SRV_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/cfg_srv.h | C | apache-2.0 | 2,105 |
/** @file
* @brief Bluetooth Mesh Configuration Server Model APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_CTRL_RELAY_H
#define __BT_MESH_CTRL_RELAY_H
#include <net/buf.h>
#include "net.h"
#define CTRL_RELAY_N_MIN 3
#define CTRL_RELAY_N_MAX 7
#define CTRL_RELAY_N_DEF 5
#define CTRL_RELAY_RSSI_DEF 90
#define CTRL_RELAY_STA_PERIOD_DEF 60
#define CTRL_RELAY_CHK_PERIOD_DEF 70
#define CTRL_RELAY_KEEP_PERIOD 10
#define CTRL_RELAY_CACHE_TIMEOUT 70
#define CTRL_RELAY_CACHE_EXPIRE 90
#define CTRL_RELAY_CHK_PROTECT 120
#define CTRL_RELAY_CACHE_LIMIT 8
#define CTRL_RELAY_CACHE_SIZE 10
#define RSSI_VAL(n) (((n) < 0) ? -(n) : (n))
typedef enum {
CTRL_RELAY_TYPE_STATUS = 0,
CTRL_RELAY_TYPE_REQ,
CTRL_RELAY_TYPE_OPEN,
CTRL_RELAY_TYPE_NONE
} ctrl_relay_send_type;
typedef enum {
CTRL_RELAY_STATUS_PUB = 0,
CTRL_RELAY_STATUS_CHK_NOTIFY,
CTRL_RELAY_STATUS_FD_NOTIFY,
CTRL_RELAY_STATUS_FD_DISABLE,
CTRL_RELAY_STATUS_REQ,
CTRL_RELAY_STATUS_OPEN,
CTRL_RELAY_STATUS_NONE
} ctrl_relay_status_sub_type;
struct ctrl_relay_cache {
bt_u32_t tmms;
u16_t addr;
u16_t nb_addr[CTRL_RELAY_CACHE_SIZE];
} __packed;
struct ctrl_relay_status {
bt_u32_t tmms;
bt_u32_t flood_ms;
u8_t flood_flg;
u8_t enable;
u8_t nb_relay_cnt;
} __packed;
struct ctrl_relay_param {
u8_t enable;
u8_t trd_n;
u8_t rssi;
u8_t sta_period;
u8_t chk_period;
u8_t req_period;
} __packed;
struct ctrl_relay_cfg {
struct ctrl_relay_param param;
struct ctrl_relay_status curr_stat;
struct bt_mesh_model *model;
struct k_delayed_work sta_work;
struct k_delayed_work chk_work;
struct k_delayed_work keep_work;
};
int ctrl_relay_init(struct bt_mesh_model *model);
int ctrl_relay_deinit(void);
void ctrl_relay_conf_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf);
void ctrl_relay_conf_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf);
int ctrl_relay_msg_recv(u8_t ctl_op, struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
void ctrl_relay_set_flood_flg(void);
#endif /* __BT_MESH_CTRL_RELAY_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/ctrl_relay.h | C | apache-2.0 | 2,239 |
/** @file
* @brief Bluetooth Mesh Health Client Model APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_HEALTH_CLI_H
#define __BT_MESH_HEALTH_CLI_H
/**
* @brief Bluetooth Mesh
* @defgroup bt_mesh_health_cli Bluetooth Mesh Health Client Model
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/** Mesh Health Client Model Context */
struct bt_mesh_health_cli {
struct bt_mesh_model *model;
void (*current_status)(struct bt_mesh_health_cli *cli, u16_t addr,
u8_t test_id, u16_t cid, u8_t *faults,
size_t fault_count);
struct k_sem op_sync;
bt_u32_t op_pending;
void *op_param;
};
extern const struct bt_mesh_model_op bt_mesh_health_cli_op[];
extern struct bt_mesh_health_cli g_health_cli;
#define BT_MESH_MODEL_HEALTH_CLI(cli_data) \
BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_CLI, \
bt_mesh_health_cli_op, NULL, cli_data)
#define MESH_MODEL_HEALTH_CLI_NULL() BT_MESH_MODEL_HEALTH_CLI(&g_health_cli)
int bt_mesh_health_cli_set(struct bt_mesh_model *model);
int bt_mesh_health_fault_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t *test_id, u8_t *faults,
size_t *fault_count);
int bt_mesh_health_fault_clear(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t *test_id, u8_t *faults,
size_t *fault_count);
int bt_mesh_health_fault_test(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t test_id, u8_t *faults,
size_t *fault_count);
int bt_mesh_health_period_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t *divisor);
int bt_mesh_health_period_set(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t divisor, u8_t *updated_divisor);
int bt_mesh_health_attention_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t *attention);
int bt_mesh_health_attention_set(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t attention, u8_t *updated_attention);
bt_s32_t bt_mesh_health_cli_timeout_get(void);
void bt_mesh_health_cli_timeout_set(bt_s32_t timeout);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_HEALTH_CLI_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/health_cli.h | C | apache-2.0 | 2,263 |
/** @file
* @brief Bluetooth Mesh Health Server Model APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_HEALTH_SRV_H
#define __BT_MESH_HEALTH_SRV_H
/**
* @brief Bluetooth Mesh Health Server Model
* @defgroup bt_mesh_health_srv Bluetooth Mesh Health Server Model
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
struct bt_mesh_health_srv_cb {
/* Fetch current faults */
int (*fault_get_cur)(struct bt_mesh_model *model, u8_t *test_id,
u16_t *company_id, u8_t *faults,
u8_t *fault_count);
/* Fetch registered faults */
int (*fault_get_reg)(struct bt_mesh_model *model, u16_t company_id,
u8_t *test_id, u8_t *faults,
u8_t *fault_count);
/* Clear registered faults */
int (*fault_clear)(struct bt_mesh_model *model, u16_t company_id);
/* Run a specific test */
int (*fault_test)(struct bt_mesh_model *model, u8_t test_id,
u16_t company_id);
/* Attention on */
void (*attn_on)(struct bt_mesh_model *model);
/* Attention off */
void (*attn_off)(struct bt_mesh_model *model);
};
/** @def BT_MESH_HEALTH_FAULT_MSG
*
* A helper to define a health fault message.
*
* @param max_faults Maximum number of faults the element can have.
*
* @return a New net_buf_simple of the needed size.
*/
#define BT_MESH_HEALTH_FAULT_MSG(max_faults) \
NET_BUF_SIMPLE(1 + 3 + (max_faults))
/** @def BT_MESH_HEALTH_PUB_DEFINE
*
* A helper to define a health publication context
*
* @param _name Name given to the publication context variable.
* @param _max_faults Maximum number of faults the element can have.
*/
#define BT_MESH_HEALTH_PUB_DEFINE(_name, _max_faults) \
BT_MESH_MODEL_PUB_DEFINE(_name, NULL, (1 + 3 + (_max_faults)))
/** Mesh Health Server Model Context */
struct bt_mesh_health_srv {
struct bt_mesh_model *model;
/* Optional callback struct */
const struct bt_mesh_health_srv_cb *cb;
/* Attention Timer state */
struct k_delayed_work attn_timer;
};
int bt_mesh_fault_update(struct bt_mesh_elem *elem);
extern const struct bt_mesh_model_op bt_mesh_health_srv_op[];
/** @def BT_MESH_MODEL_HEALTH_SRV
*
* Define a new health server model. Note that this API needs to be
* repeated for each element that the application wants to have a
* health server model on. Each instance also needs a unique
* bt_mesh_health_srv and bt_mesh_model_pub context.
*
* @param srv Pointer to a unique struct bt_mesh_health_srv.
* @param pub Pointer to a unique struct bt_mesh_model_pub.
*
* @return New mesh model instance.
*/
extern struct bt_mesh_health_srv g_health_srv;
extern struct bt_mesh_model_pub g_health_pub;
#define BT_MESH_MODEL_HEALTH_SRV(srv, pub) \
BT_MESH_MODEL(BT_MESH_MODEL_ID_HEALTH_SRV, \
bt_mesh_health_srv_op, pub, srv)
#define MESH_MODEL_HEALTH_SRV_NULL() BT_MESH_MODEL_HEALTH_SRV(&g_health_srv, &g_health_pub)
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_HEALTH_SRV_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/health_srv.h | C | apache-2.0 | 3,052 |
/** @file
* @brief Bluetooth Mesh Profile APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_MAIN_H
#define __BT_MESH_MAIN_H
/**
* @brief Bluetooth Mesh Provisioning
* @defgroup bt_mesh_prov Bluetooth Mesh Provisioning
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
#ifndef bool
#define bool unsigned char
#endif
#define BITN(n) (1U << (n))
typedef enum {
BT_MESH_NO_OUTPUT = 0,
BT_MESH_BLINK = BITN(0),
BT_MESH_BEEP = BITN(1),
BT_MESH_VIBRATE = BITN(2),
BT_MESH_DISPLAY_NUMBER = BITN(3),
BT_MESH_DISPLAY_STRING = BITN(4),
} bt_mesh_output_action_t;
typedef enum {
BT_MESH_NO_INPUT = 0,
BT_MESH_PUSH = BITN(0),
BT_MESH_TWIST = BITN(1),
BT_MESH_ENTER_NUMBER = BITN(2),
BT_MESH_ENTER_STRING = BITN(3),
} bt_mesh_input_action_t;
typedef enum {
BT_MESH_PROV_ADV = BITN(0),
BT_MESH_PROV_GATT = BITN(1),
} bt_mesh_prov_bearer_t;
typedef enum {
BT_MESH_PROV_OOB_OTHER = BITN(0),
BT_MESH_PROV_OOB_URI = BITN(1),
BT_MESH_PROV_OOB_2D_CODE = BITN(2),
BT_MESH_PROV_OOB_BAR_CODE = BITN(3),
BT_MESH_PROV_OOB_NFC = BITN(4),
BT_MESH_PROV_OOB_NUMBER = BITN(5),
BT_MESH_PROV_OOB_STRING = BITN(6),
/* 7 - 10 are reserved */
BT_MESH_PROV_OOB_ON_BOX = BITN(11),
BT_MESH_PROV_OOB_IN_BOX = BITN(12),
BT_MESH_PROV_OOB_ON_PAPER = BITN(13),
BT_MESH_PROV_OOB_IN_MANUAL = BITN(14),
BT_MESH_PROV_OOB_ON_DEV = BITN(15),
} bt_mesh_prov_oob_info_t;
/** Provisioning properties & capabilities. */
struct bt_mesh_prov {
/** The UUID that's used when advertising as unprovisioned */
const u8_t *uuid;
/** Optional URI. This will be advertised separately from the
* unprovisioned beacon, however the unprovisioned beacon will
* contain a hash of it so the two can be associated by the
* provisioner.
*/
const char *uri;
/** Out of Band information field. */
bt_mesh_prov_oob_info_t oob_info;
/** Static OOB value */
const u8_t *static_val;
/** Static OOB value length */
u8_t static_val_len;
/** Maximum size of Output OOB supported */
u8_t output_size;
/** Supported Output OOB Actions */
u16_t output_actions;
/* Maximum size of Input OOB supported */
u8_t input_size;
/** Supported Input OOB Actions */
u16_t input_actions;
/** @brief Output of a number is requested.
*
* This callback notifies the application that it should
* output the given number using the given action.
*
* @param act Action for outputting the number.
* @param num Number to be outputted.
*
* @return Zero on success or negative error code otherwise
*/
int (*output_number)(bt_mesh_output_action_t act, bt_u32_t num);
/** @brief Output of a string is requested.
*
* This callback notifies the application that it should
* display the given string to the user.
*
* @param str String to be displayed.
*
* @return Zero on success or negative error code otherwise
*/
int (*output_string)(const char *str);
/** @brief Input is requested.
*
* This callback notifies the application that it should
* request input from the user using the given action. The
* requested input will either be a string or a number, and
* the application needs to consequently call the
* bt_mesh_input_string() or bt_mesh_input_number() functions
* once the data has been acquired from the user.
*
* @param act Action for inputting data.
* @param num Maximum size of the inputted data.
*
* @return Zero on success or negative error code otherwise
*/
int (*input)(bt_mesh_input_action_t act, u8_t size);
/** @brief Provisioning link has been opened.
*
* This callback notifies the application that a provisioning
* link has been opened on the given provisioning bearer.
*
* @param bearer Provisioning bearer.
*/
void (*link_open)(bt_mesh_prov_bearer_t bearer);
/** @brief Provisioning link has been closed.
*
* This callback notifies the application that a provisioning
* link has been closed on the given provisioning bearer.
*
* @param bearer Provisioning bearer.
*/
void (*link_close)(bt_mesh_prov_bearer_t bearer);
/** @brief Provisioning is complete.
*
* This callback notifies the application that provisioning has
* been successfully completed, and that the local node has been
* assigned the specified NetKeyIndex and primary element address.
*
* @param net_idx NetKeyIndex given during provisioning.
* @param addr Primary element address.
*/
void (*complete)(u16_t net_idx, u16_t addr);
/** @brief Node has been reset.
*
* This callback notifies the application that the local node
* has been reset and needs to be reprovisioned. The node will
* not automatically advertise as unprovisioned, rather the
* bt_mesh_prov_enable() API needs to be called to enable
* unprovisioned advertising on one or more provisioning bearers.
*/
void (*reset)(void);
};
struct bt_mesh_provisioner {
/* Provisioner device uuid */
const u8_t *prov_uuid;
/*
* Primary element address of the provisioner, for
* temporary provisioner no need to initialize it.
*/
u16_t prov_unicast_addr;
/*
* Starting unicast address going to assigned, for
* temporary provisioner no need to initialize it.
*/
u16_t prov_start_address;
/* Attention timer contained in Provisioning Invite */
u8_t prov_attention;
/* Provisioner provisioning Algorithm */
u8_t prov_algorithm;
/* Provisioner public key oob */
u8_t prov_pub_key_oob;
/** @brief Input is requested.
*
* This callback notifies the application that it should
* read device's public key with OOB
*
* @param remote_pub_key Public key pointer of the device.
*
* @return Zero on success or negative error code otherwise
*/
int (*prov_pub_key_oob_cb)(u8_t remote_pub_key[64]);
/* Provisioner static oob value */
u8_t *prov_static_oob_val;
/* Provisioner static oob value length */
u8_t prov_static_oob_len;
/** @brief Provisioner input a number read from device output
*
* This callback notifies the application that it should
* input the number given by the device.
*
* @param act: The output action of the device
* @param size: The output size of the device
*
* @return Zero on success or negative error code otherwise
*/
int (*prov_input_num)(bt_mesh_output_action_t act, u8_t size);
/** @brief Provisioner input static oob
*
* This callback notifies the application that it should
*
* @param size: The output size of the device
*
* @return Zero on success or negative error code otherwise
*/
int (*prov_input_static_oob)();
/** @brief Provisioner output a number to the device
*
* This callback notifies the application that it should
* output the number to the device.
*
* @param act: The input action of the device
* @param size: The input size of the device
*
* @return Zero on success or negative error code otherwise
*/
int (*prov_output_num)(bt_mesh_input_action_t act, u8_t size);
/*
* Key refresh and IV update flag, for temporary provisioner no
* need to initialize it.
*/
u8_t flags;
/*
* IV index, for temporary provisioner no need to initialize it.
*/
bt_u32_t iv_index;
/** @brief Provisioner has opened a provisioning link.
*
* This callback notifies the application that a provisioning
* link has been opened on the given provisioning bearer.
*
* @param bearer Provisioning bearer.
* @param link info.
*/
void (*prov_link_open)(bt_mesh_prov_bearer_t bearer, u8_t addr_val[6], u8_t addr_type, u8_t uuid[16],
u8_t prov_count);
/** @brief Provisioner has closed a provisioning link.
*
* This callback notifies the application that a provisioning
* link has been closed on the given provisioning bearer.
*
* @param bearer Provisioning bearer.
* @param reason Provisioning link close reason(disconnect reason)
* @param link info.
*/
void (*prov_link_close)(bt_mesh_prov_bearer_t bearer, u8_t reason, u8_t addr_val[6], u8_t addr_type, u8_t uuid[16],
u8_t prov_count);
/** @brief Provision one device is complete.
*
* This callback notifies the application that provisioner has
* successfully provisioned a device, and the node has been assigned
* with the specified NetKeyIndex and primary element address.
*
* @param node_idx Node index within the node(provisioned device) queue.
* @param device_uuid Provisioned device device uuid pointer.
* @param unicast_addr Provisioned device assigned unicast address.
* @param element_num Provisioned device element number.
* @param netkey_idx Provisioned device assigned netkey index.
*/
void (*prov_complete)(int node_idx, const u8_t device_uuid[16], u16_t unicast_addr, u8_t element_num,
u16_t netkey_idx, bool gatt_flag);
};
/** @brief Provide provisioning input OOB string.
*
* This is intended to be called after the bt_mesh_prov input callback
* has been called with BT_MESH_ENTER_STRING as the action.
*
* @param str String.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_input_string(const char *str);
/** @brief Provide provisioning input OOB number.
*
* This is intended to be called after the bt_mesh_prov input callback
* has been called with BT_MESH_ENTER_NUMBER as the action.
*
* @param num Number.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_input_number(bt_u32_t num);
/** @brief Enable specific provisioning bearers
*
* Enable one or more provisioning bearers.
*
* @param bearers Bit-wise or of provisioning bearers.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_prov_enable(bt_mesh_prov_bearer_t bearers);
/** @brief Disable specific provisioning bearers
*
* Disable one or more provisioning bearers.
*
* @param bearers Bit-wise or of provisioning bearers.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_prov_disable(bt_mesh_prov_bearer_t bearers);
/**
* @}
*/
/**
* @brief Bluetooth Mesh
* @defgroup bt_mesh Bluetooth Mesh
* @ingroup bluetooth
* @{
*/
/* Primary Network Key index */
#define BT_MESH_NET_PRIMARY 0x000
#define BT_MESH_RELAY_DISABLED 0x00
#define BT_MESH_RELAY_ENABLED 0x01
#define BT_MESH_RELAY_NOT_SUPPORTED 0x02
#define BT_MESH_BEACON_DISABLED 0x00
#define BT_MESH_BEACON_ENABLED 0x01
#define BT_MESH_GATT_PROXY_DISABLED 0x00
#define BT_MESH_GATT_PROXY_ENABLED 0x01
#define BT_MESH_GATT_PROXY_NOT_SUPPORTED 0x02
#define BT_MESH_FRIEND_DISABLED 0x00
#define BT_MESH_FRIEND_ENABLED 0x01
#define BT_MESH_FRIEND_NOT_SUPPORTED 0x02
#define BT_MESH_NODE_IDENTITY_STOPPED 0x00
#define BT_MESH_NODE_IDENTITY_RUNNING 0x01
#define BT_MESH_NODE_IDENTITY_NOT_SUPPORTED 0x02
/* Features */
#define BT_MESH_FEAT_RELAY BITN(0)
#define BT_MESH_FEAT_PROXY BITN(1)
#define BT_MESH_FEAT_FRIEND BITN(2)
#define BT_MESH_FEAT_LOW_POWER BITN(3)
#define BT_MESH_FEAT_SUPPORTED (BT_MESH_FEAT_RELAY | BT_MESH_FEAT_PROXY | BT_MESH_FEAT_FRIEND | BT_MESH_FEAT_LOW_POWER)
/** @brief Initialize Mesh support
*
* After calling this API, the node will not automatically advertise as
* unprovisioned, rather the bt_mesh_prov_enable() API needs to be called
* to enable unprovisioned advertising on one or more provisioning bearers.
*
* @param prov Node provisioning information.
* @param comp Node Composition.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_init(const struct bt_mesh_prov *prov, const struct bt_mesh_comp *comp,
const struct bt_mesh_provisioner *provisioner);
/** @brief Reset the state of the local Mesh node.
*
* Resets the state of the node, which means that it needs to be
* reprovisioned to become an active node in a Mesh network again.
*
* After calling this API, the node will not automatically advertise as
* unprovisioned, rather the bt_mesh_prov_enable() API needs to be called
* to enable unprovisioned advertising on one or more provisioning bearers.
*
*/
void bt_mesh_reset(void);
/** @brief Suspend the Mesh network temporarily.
*
* This API can be used for power saving purposes, but the user should be
* aware that leaving the local node suspended for a long period of time
* may cause it to become permanently disconnected from the Mesh network.
* If at all possible, the Friendship feature should be used instead, to
* make the node into a Low Power Node.
*
* @return 0 on success, or (negative) error code on failure.
*/
int bt_mesh_suspend(bool force);
/** @brief Resume a suspended Mesh network.
*
* This API resumes the local node, after it has been suspended using the
* bt_mesh_suspend() API.
*
* @return 0 on success, or (negative) error code on failure.
*/
int bt_mesh_resume(void);
/** @brief Provision the local Mesh Node.
*
* This API should normally not be used directly by the application. The
* only exception is for testing purposes where manual provisioning is
* desired without an actual external provisioner.
*
* @param net_key Network Key
* @param net_idx Network Key Index
* @param flags Provisioning Flags
* @param iv_index IV Index
* @param addr Primary element address
* @param dev_key Device Key
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_provision(const u8_t net_key[16], u16_t net_idx, u8_t flags, bt_u32_t iv_index, u16_t addr,
const u8_t dev_key[16]);
/** @brief Check if the local node has been provisioned.
*
* This API can be used to check if the local node has been provisioned
* or not. It can e.g. be helpful to determine if there was a stored
* network in flash, i.e. if the network was restored after calling
* settings_load().
*
* @return True if the node is provisioned. False otherwise.
*/
bool bt_mesh_is_provisioned(void);
/** @brief Toggle the IV Update test mode
*
* This API is only available if the IV Update test mode has been enabled
* in Kconfig. It is needed for passing most of the IV Update qualification
* test cases.
*
* @param enable true to enable IV Update test mode, false to disable it.
*/
void bt_mesh_iv_update_test(bool enable);
/** @brief Toggle the IV Update state
*
* This API is only available if the IV Update test mode has been enabled
* in Kconfig. It is needed for passing most of the IV Update qualification
* test cases.
*
* @return true if IV Update In Progress state was entered, false otherwise.
*/
bool bt_mesh_iv_update(void);
/** @brief Toggle the Low Power feature of the local device
*
* Enables or disables the Low Power feature of the local device. This is
* exposed as a run-time feature, since the device might want to change
* this e.g. based on being plugged into a stable power source or running
* from a battery power source.
*
* @param enable true to enable LPN functionality, false to disable it.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_lpn_set(bool enable);
/** @brief Send out a Friend Poll message.
*
* Send a Friend Poll message to the Friend of this node. If there is no
* established Friendship the function will return an error.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_lpn_poll(void);
/** @brief Register a callback for Friendship changes.
*
* Registers a callback that will be called whenever Friendship gets
* established or is lost.
*
* @param cb Function to call when the Friendship status changes.
*/
void bt_mesh_lpn_set_cb(void (*cb)(u16_t friend_addr, bool established));
int bt_mesh_provisioner_enable(bt_mesh_prov_bearer_t bearers);
int bt_mesh_provisioner_disable(bt_mesh_prov_bearer_t bearers);
int bt_mesh_is_init();
struct adv_addr_t {
u8_t type;
u8_t val[6];
};
int bt_mesh_vnd_adv_set_cb(void (*cb)(const struct adv_addr_t *addr, s8_t rssi, u8_t adv_type, void *user_data,
u16_t len));
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_MAIN_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/main.h | C | apache-2.0 | 16,422 |
/** @file
* @brief Bluetooth Mesh Proxy APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __BT_MESH_PROXY_H
#define __BT_MESH_PROXY_H
/**
* @brief Bluetooth Mesh Proxy
* @defgroup bt_mesh_proxy Bluetooth Mesh Proxy
* @ingroup bt_mesh
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Enable advertising with Node Identity.
*
* This API requires that GATT Proxy support has been enabled. Once called
* each subnet will start advertising using Node Identity for the next
* 60 seconds.
*
* @return 0 on success, or (negative) error code on failure.
*/
int bt_mesh_proxy_identity_enable(void);
int bt_mesh_proxy_identity_disable(void);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#endif /* __BT_MESH_PROXY_H */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/api/mesh/proxy.h | C | apache-2.0 | 795 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define BEACON_TYPE_UNPROVISIONED 0x00
#define BEACON_TYPE_SECURE 0x01
void bt_mesh_beacon_enable(void);
void bt_mesh_beacon_disable(void);
void bt_mesh_beacon_ivu_initiator(bool enable);
void bt_mesh_beacon_recv(struct net_buf_simple *buf);
void bt_mesh_beacon_create(struct bt_mesh_subnet *sub,
struct net_buf_simple *buf);
void bt_mesh_beacon_init(void);
bt_u32_t bt_mesh_get_beacon_interval(u8_t type);
void bt_mesh_set_beacon_interval(u8_t type, bt_u32_t delay);
void genie_set_silent_unprov_beacon_interval(bool is_silent);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/beacon.h | C | apache-2.0 | 666 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define TRANS_SEQ_AUTH_NVAL 0xffffffffffffffff
#define BT_MESH_TX_SDU_MAX (CONFIG_BT_MESH_TX_SEG_MAX * 16)
#define TRANS_CTL_OP_MASK ((u8_t)BIT_MASK(7))
#define TRANS_CTL_OP(data) ((data)[0] & TRANS_CTL_OP_MASK)
#define TRANS_CTL_HDR(op, seg) ((op & TRANS_CTL_OP_MASK) | (seg << 7))
#define TRANS_CTL_OP_ACK 0x00
#define TRANS_CTL_OP_FRIEND_POLL 0x01
#define TRANS_CTL_OP_FRIEND_UPDATE 0x02
#define TRANS_CTL_OP_FRIEND_REQ 0x03
#define TRANS_CTL_OP_FRIEND_OFFER 0x04
#define TRANS_CTL_OP_FRIEND_CLEAR 0x05
#define TRANS_CTL_OP_FRIEND_CLEAR_CFM 0x06
#define TRANS_CTL_OP_FRIEND_SUB_ADD 0x07
#define TRANS_CTL_OP_FRIEND_SUB_REM 0x08
#define TRANS_CTL_OP_FRIEND_SUB_CFM 0x09
#define TRANS_CTL_OP_HEARTBEAT 0x0a
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
#define TRANS_CTL_OP_CTRL_RELAY_STATUS 0x30
#define TRANS_CTL_OP_CTRL_RELAY_REQ 0x31
#define TRANS_CTL_OP_CTRL_RELAY_OPEN 0x32
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
struct bt_mesh_ctl_friend_poll {
u8_t fsn;
} __packed;
struct bt_mesh_ctl_friend_update {
u8_t flags;
bt_u32_t iv_index;
u8_t md;
} __packed;
struct bt_mesh_ctl_friend_req {
u8_t criteria;
u8_t recv_delay;
u8_t poll_to[3];
u16_t prev_addr;
u8_t num_elem;
u16_t lpn_counter;
} __packed;
struct bt_mesh_ctl_friend_offer {
u8_t recv_win;
u8_t queue_size;
u8_t sub_list_size;
s8_t rssi;
u16_t frnd_counter;
} __packed;
struct bt_mesh_ctl_friend_clear {
u16_t lpn_addr;
u16_t lpn_counter;
} __packed;
struct bt_mesh_ctl_friend_clear_confirm {
u16_t lpn_addr;
u16_t lpn_counter;
} __packed;
#define BT_MESH_FRIEND_SUB_MIN_LEN (1 + 2)
struct bt_mesh_ctl_friend_sub {
u8_t xact;
u16_t addr_list[5];
} __packed;
struct bt_mesh_ctl_friend_sub_confirm {
u8_t xact;
} __packed;
void bt_mesh_set_hb_sub_dst(u16_t addr);
struct bt_mesh_app_key *bt_mesh_app_key_find(u16_t app_idx);
bool bt_mesh_tx_in_progress(void);
void bt_mesh_rx_reset(void);
void bt_mesh_tx_reset(void);
int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, u8_t ctl_op, void *data,
size_t data_len, u64_t *seq_auth,
const struct bt_mesh_send_cb *cb, void *cb_data);
int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg,
const struct bt_mesh_send_cb *cb, void *cb_data);
int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx);
void bt_mesh_trans_init(void);
void bt_mesh_rpl_clear(void);
void bt_mesh_rpl_clear_all(void);
void bt_mesh_rpl_clear_node(uint16_t unicast_addr,uint8_t elem_num);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/ble_transport.h | C | apache-2.0 | 2,776 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
struct bt_mesh_sg {
const void *data;
size_t len;
};
int bt_mesh_aes_cmac(const u8_t key[16], struct bt_mesh_sg *sg,
size_t sg_len, u8_t mac[16]);
static inline int bt_mesh_aes_cmac_one(const u8_t key[16], const void *m,
size_t len, u8_t mac[16])
{
struct bt_mesh_sg sg = { m, len };
return bt_mesh_aes_cmac(key, &sg, 1, mac);
}
static inline bool bt_mesh_s1(const char *m, u8_t salt[16])
{
const u8_t zero[16] = { 0 };
return bt_mesh_aes_cmac_one(zero, m, strlen(m), salt);
}
int bt_mesh_k1(const u8_t *ikm, size_t ikm_len, const u8_t salt[16],
const char *info, u8_t okm[16]);
#define bt_mesh_k1_str(ikm, ikm_len, salt_str, info, okm) \
({ \
const u8_t salt[16] = salt_str; \
bt_mesh_k1(ikm, ikm_len, salt, info, okm); \
})
int bt_mesh_k2(const u8_t n[16], const u8_t *p, size_t p_len,
u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16]);
int bt_mesh_k3(const u8_t n[16], u8_t out[8]);
int bt_mesh_k4(const u8_t n[16], u8_t out[1]);
int bt_mesh_id128(const u8_t n[16], const char *s, u8_t out[16]);
static inline int bt_mesh_id_resolving_key(const u8_t net_key[16],
u8_t resolving_key[16])
{
return bt_mesh_k1_str(net_key, 16, "smbt", "smbi", resolving_key);
}
static inline int bt_mesh_identity_key(const u8_t net_key[16],
u8_t identity_key[16])
{
return bt_mesh_id128(net_key, "nkik", identity_key);
}
static inline int bt_mesh_beacon_key(const u8_t net_key[16],
u8_t beacon_key[16])
{
return bt_mesh_id128(net_key, "nkbk", beacon_key);
}
int bt_mesh_beacon_auth(const u8_t beacon_key[16], u8_t flags,
const u8_t net_id[16], bt_u32_t iv_index,
u8_t auth[8]);
static inline int bt_mesh_app_id(const u8_t app_key[16], u8_t app_id[1])
{
return bt_mesh_k4(app_key, app_id);
}
static inline int bt_mesh_session_key(const u8_t dhkey[32],
const u8_t prov_salt[16],
u8_t session_key[16])
{
return bt_mesh_k1(dhkey, 32, prov_salt, "prsk", session_key);
}
static inline int bt_mesh_prov_nonce(const u8_t dhkey[32],
const u8_t prov_salt[16],
u8_t nonce[13])
{
u8_t tmp[16];
int err;
err = bt_mesh_k1(dhkey, 32, prov_salt, "prsn", tmp);
if (!err) {
memcpy(nonce, tmp + 3, 13);
}
return err;
}
static inline int bt_mesh_dev_key(const u8_t dhkey[32],
const u8_t prov_salt[16],
u8_t dev_key[16])
{
return bt_mesh_k1(dhkey, 32, prov_salt, "prdk", dev_key);
}
static inline int bt_mesh_prov_salt(const u8_t conf_salt[16],
const u8_t prov_rand[16],
const u8_t dev_rand[16],
u8_t prov_salt[16])
{
const u8_t prov_salt_key[16] = { 0 };
struct bt_mesh_sg sg[] = {
{ conf_salt, 16 },
{ prov_rand, 16 },
{ dev_rand, 16 },
};
return bt_mesh_aes_cmac(prov_salt_key, sg, ARRAY_SIZE(sg), prov_salt);
}
int bt_mesh_net_obfuscate(u8_t *pdu, bt_u32_t iv_index,
const u8_t privacy_key[16]);
int bt_mesh_net_encrypt(const u8_t key[16], struct net_buf_simple *buf,
bt_u32_t iv_index, bool proxy);
int bt_mesh_net_decrypt(const u8_t key[16], struct net_buf_simple *buf,
bt_u32_t iv_index, bool proxy);
int bt_mesh_app_encrypt(const u8_t key[16], bool dev_key, u8_t aszmic,
struct net_buf_simple *buf, const u8_t *ad,
u16_t src, u16_t dst, bt_u32_t seq_num, bt_u32_t iv_index);
int bt_mesh_app_decrypt(const u8_t key[16], bool dev_key, u8_t aszmic,
struct net_buf_simple *buf, struct net_buf_simple *out,
const u8_t *ad, u16_t src, u16_t dst, bt_u32_t seq_num,
bt_u32_t iv_index);
u8_t bt_mesh_fcs_calc(const u8_t *data, u8_t data_len);
bool bt_mesh_fcs_check(struct net_buf_simple *buf, u8_t received_fcs);
int bt_mesh_virtual_addr(const u8_t virtual_label[16], u16_t *addr);
int bt_mesh_prov_conf_salt(const u8_t conf_inputs[145], u8_t salt[16]);
int bt_mesh_prov_conf_key(const u8_t dhkey[32], const u8_t conf_salt[16],
u8_t conf_key[16]);
int bt_mesh_prov_conf(const u8_t conf_key[16], const u8_t rand[16],
const u8_t auth[16], u8_t conf[16]);
int bt_mesh_prov_decrypt(const u8_t key[16], u8_t nonce[13],
const u8_t data[25 + 8], u8_t out[25]);
int bt_mesh_prov_encrypt(const u8_t key[16], u8_t nonce[13],
const u8_t data[25], u8_t out[33]);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/crypto.h | C | apache-2.0 | 4,287 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define OP_APP_KEY_ADD BT_MESH_MODEL_OP_1(0x00)
#define OP_APP_KEY_UPDATE BT_MESH_MODEL_OP_1(0x01)
#define OP_DEV_COMP_DATA_STATUS BT_MESH_MODEL_OP_1(0x02)
#define OP_MOD_PUB_SET BT_MESH_MODEL_OP_1(0x03)
#define OP_HEALTH_CURRENT_STATUS BT_MESH_MODEL_OP_1(0x04)
#define OP_HEALTH_FAULT_STATUS BT_MESH_MODEL_OP_1(0x05)
#define OP_HEARTBEAT_PUB_STATUS BT_MESH_MODEL_OP_1(0x06)
#define OP_APP_KEY_DEL BT_MESH_MODEL_OP_2(0x80, 0x00)
#define OP_APP_KEY_GET BT_MESH_MODEL_OP_2(0x80, 0x01)
#define OP_APP_KEY_LIST BT_MESH_MODEL_OP_2(0x80, 0x02)
#define OP_APP_KEY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x03)
#define OP_ATTENTION_GET BT_MESH_MODEL_OP_2(0x80, 0x04)
#define OP_ATTENTION_SET BT_MESH_MODEL_OP_2(0x80, 0x05)
#define OP_ATTENTION_SET_UNREL BT_MESH_MODEL_OP_2(0x80, 0x06)
#define OP_ATTENTION_STATUS BT_MESH_MODEL_OP_2(0x80, 0x07)
#define OP_DEV_COMP_DATA_GET BT_MESH_MODEL_OP_2(0x80, 0x08)
#define OP_BEACON_GET BT_MESH_MODEL_OP_2(0x80, 0x09)
#define OP_BEACON_SET BT_MESH_MODEL_OP_2(0x80, 0x0a)
#define OP_BEACON_STATUS BT_MESH_MODEL_OP_2(0x80, 0x0b)
#define OP_DEFAULT_TTL_GET BT_MESH_MODEL_OP_2(0x80, 0x0c)
#define OP_DEFAULT_TTL_SET BT_MESH_MODEL_OP_2(0x80, 0x0d)
#define OP_DEFAULT_TTL_STATUS BT_MESH_MODEL_OP_2(0x80, 0x0e)
#define OP_FRIEND_GET BT_MESH_MODEL_OP_2(0x80, 0x0f)
#define OP_FRIEND_SET BT_MESH_MODEL_OP_2(0x80, 0x10)
#define OP_FRIEND_STATUS BT_MESH_MODEL_OP_2(0x80, 0x11)
#define OP_GATT_PROXY_GET BT_MESH_MODEL_OP_2(0x80, 0x12)
#define OP_GATT_PROXY_SET BT_MESH_MODEL_OP_2(0x80, 0x13)
#define OP_GATT_PROXY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x14)
#define OP_KRP_GET BT_MESH_MODEL_OP_2(0x80, 0x15)
#define OP_KRP_SET BT_MESH_MODEL_OP_2(0x80, 0x16)
#define OP_KRP_STATUS BT_MESH_MODEL_OP_2(0x80, 0x17)
#define OP_MOD_PUB_GET BT_MESH_MODEL_OP_2(0x80, 0x18)
#define OP_MOD_PUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x19)
#define OP_MOD_PUB_VA_SET BT_MESH_MODEL_OP_2(0x80, 0x1a)
#define OP_MOD_SUB_ADD BT_MESH_MODEL_OP_2(0x80, 0x1b)
#define OP_MOD_SUB_DEL BT_MESH_MODEL_OP_2(0x80, 0x1c)
#define OP_MOD_SUB_DEL_ALL BT_MESH_MODEL_OP_2(0x80, 0x1d)
#define OP_MOD_SUB_OVERWRITE BT_MESH_MODEL_OP_2(0x80, 0x1e)
#define OP_MOD_SUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x1f)
#define OP_MOD_SUB_VA_ADD BT_MESH_MODEL_OP_2(0x80, 0x20)
#define OP_MOD_SUB_VA_DEL BT_MESH_MODEL_OP_2(0x80, 0x21)
#define OP_MOD_SUB_VA_OVERWRITE BT_MESH_MODEL_OP_2(0x80, 0x22)
#define OP_NET_TRANSMIT_GET BT_MESH_MODEL_OP_2(0x80, 0x23)
#define OP_NET_TRANSMIT_SET BT_MESH_MODEL_OP_2(0x80, 0x24)
#define OP_NET_TRANSMIT_STATUS BT_MESH_MODEL_OP_2(0x80, 0x25)
#define OP_RELAY_GET BT_MESH_MODEL_OP_2(0x80, 0x26)
#define OP_RELAY_SET BT_MESH_MODEL_OP_2(0x80, 0x27)
#define OP_RELAY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x28)
#define OP_MOD_SUB_GET BT_MESH_MODEL_OP_2(0x80, 0x29)
#define OP_MOD_SUB_LIST BT_MESH_MODEL_OP_2(0x80, 0x2a)
#define OP_MOD_SUB_GET_VND BT_MESH_MODEL_OP_2(0x80, 0x2b)
#define OP_MOD_SUB_LIST_VND BT_MESH_MODEL_OP_2(0x80, 0x2c)
#define OP_LPN_TIMEOUT_GET BT_MESH_MODEL_OP_2(0x80, 0x2d)
#define OP_LPN_TIMEOUT_STATUS BT_MESH_MODEL_OP_2(0x80, 0x2e)
#define OP_HEALTH_FAULT_CLEAR BT_MESH_MODEL_OP_2(0x80, 0x2f)
#define OP_HEALTH_FAULT_CLEAR_UNREL BT_MESH_MODEL_OP_2(0x80, 0x30)
#define OP_HEALTH_FAULT_GET BT_MESH_MODEL_OP_2(0x80, 0x31)
#define OP_HEALTH_FAULT_TEST BT_MESH_MODEL_OP_2(0x80, 0x32)
#define OP_HEALTH_FAULT_TEST_UNREL BT_MESH_MODEL_OP_2(0x80, 0x33)
#define OP_HEALTH_PERIOD_GET BT_MESH_MODEL_OP_2(0x80, 0x34)
#define OP_HEALTH_PERIOD_SET BT_MESH_MODEL_OP_2(0x80, 0x35)
#define OP_HEALTH_PERIOD_SET_UNREL BT_MESH_MODEL_OP_2(0x80, 0x36)
#define OP_HEALTH_PERIOD_STATUS BT_MESH_MODEL_OP_2(0x80, 0x37)
#define OP_HEARTBEAT_PUB_GET BT_MESH_MODEL_OP_2(0x80, 0x38)
#define OP_HEARTBEAT_PUB_SET BT_MESH_MODEL_OP_2(0x80, 0x39)
#define OP_HEARTBEAT_SUB_GET BT_MESH_MODEL_OP_2(0x80, 0x3a)
#define OP_HEARTBEAT_SUB_SET BT_MESH_MODEL_OP_2(0x80, 0x3b)
#define OP_HEARTBEAT_SUB_STATUS BT_MESH_MODEL_OP_2(0x80, 0x3c)
#define OP_MOD_APP_BIND BT_MESH_MODEL_OP_2(0x80, 0x3d)
#define OP_MOD_APP_STATUS BT_MESH_MODEL_OP_2(0x80, 0x3e)
#define OP_MOD_APP_UNBIND BT_MESH_MODEL_OP_2(0x80, 0x3f)
#define OP_NET_KEY_ADD BT_MESH_MODEL_OP_2(0x80, 0x40)
#define OP_NET_KEY_DEL BT_MESH_MODEL_OP_2(0x80, 0x41)
#define OP_NET_KEY_GET BT_MESH_MODEL_OP_2(0x80, 0x42)
#define OP_NET_KEY_LIST BT_MESH_MODEL_OP_2(0x80, 0x43)
#define OP_NET_KEY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x44)
#define OP_NET_KEY_UPDATE BT_MESH_MODEL_OP_2(0x80, 0x45)
#define OP_NODE_IDENTITY_GET BT_MESH_MODEL_OP_2(0x80, 0x46)
#define OP_NODE_IDENTITY_SET BT_MESH_MODEL_OP_2(0x80, 0x47)
#define OP_NODE_IDENTITY_STATUS BT_MESH_MODEL_OP_2(0x80, 0x48)
#define OP_NODE_RESET BT_MESH_MODEL_OP_2(0x80, 0x49)
#define OP_NODE_RESET_STATUS BT_MESH_MODEL_OP_2(0x80, 0x4a)
#define OP_SIG_MOD_APP_GET BT_MESH_MODEL_OP_2(0x80, 0x4b)
#define OP_SIG_MOD_APP_LIST BT_MESH_MODEL_OP_2(0x80, 0x4c)
#define OP_VND_MOD_APP_GET BT_MESH_MODEL_OP_2(0x80, 0x4d)
#define OP_VND_MOD_APP_LIST BT_MESH_MODEL_OP_2(0x80, 0x4e)
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
#define OP_CTRL_RELAY_CONF_GET BT_MESH_MODEL_OP_2(0x80, 0x70)
#define OP_CTRL_RELAY_CONF_SET BT_MESH_MODEL_OP_2(0x80, 0x71)
#define OP_CTRL_RELAY_CONF_STATUS BT_MESH_MODEL_OP_2(0x80, 0x72)
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
#define STATUS_SUCCESS 0x00
#define STATUS_INVALID_ADDRESS 0x01
#define STATUS_INVALID_MODEL 0x02
#define STATUS_INVALID_APPKEY 0x03
#define STATUS_INVALID_NETKEY 0x04
#define STATUS_INSUFF_RESOURCES 0x05
#define STATUS_IDX_ALREADY_STORED 0x06
#define STATUS_NVAL_PUB_PARAM 0x07
#define STATUS_NOT_SUB_MOD 0x08
#define STATUS_STORAGE_FAIL 0x09
#define STATUS_FEAT_NOT_SUPP 0x0a
#define STATUS_CANNOT_UPDATE 0x0b
#define STATUS_CANNOT_REMOVE 0x0c
#define STATUS_CANNOT_BIND 0x0d
#define STATUS_TEMP_STATE_CHG_FAIL 0x0e
#define STATUS_CANNOT_SET 0x0f
#define STATUS_UNSPECIFIED 0x10
#define STATUS_INVALID_BINDING 0x11
int bt_mesh_cfg_srv_init(struct bt_mesh_model *model, bool primary);
int bt_mesh_health_srv_init(struct bt_mesh_model *model, bool primary);
int bt_mesh_cfg_cli_init(struct bt_mesh_model *model, bool primary);
int bt_mesh_health_cli_init(struct bt_mesh_model *model, bool primary);
void bt_mesh_cfg_reset(void);
void bt_mesh_heartbeat(u16_t src, u16_t dst, u8_t hops, u16_t feat);
void bt_mesh_attention(struct bt_mesh_model *model, u8_t time);
u8_t *bt_mesh_label_uuid_get(u16_t addr);
struct bt_mesh_hb_pub *bt_mesh_hb_pub_get(void);
void bt_mesh_hb_pub_disable(void);
struct bt_mesh_cfg_srv *bt_mesh_cfg_get(void);
u8_t bt_mesh_net_transmit_get(void);
u8_t bt_mesh_relay_get(void);
u8_t bt_mesh_friend_get(void);
u8_t bt_mesh_relay_retransmit_get(void);
u8_t bt_mesh_beacon_get(void);
u8_t bt_mesh_gatt_proxy_get(void);
u8_t bt_mesh_default_ttl_get(void);
void bt_mesh_subnet_del(struct bt_mesh_subnet *sub, bool store);
struct bt_mesh_app_key *bt_mesh_app_key_alloc(u16_t app_idx);
void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store);
#include <misc/byteorder.h>
static inline void key_idx_pack(struct net_buf_simple *buf,
u16_t idx1, u16_t idx2)
{
net_buf_simple_add_le16(buf, idx1 | ((idx2 & 0x00f) << 12));
net_buf_simple_add_u8(buf, idx2 >> 4);
}
static inline void key_idx_unpack(struct net_buf_simple *buf,
u16_t *idx1, u16_t *idx2)
{
*idx1 = sys_get_le16(&buf->data[0]) & 0xfff;
*idx2 = sys_get_le16(&buf->data[1]) >> 4;
net_buf_simple_pull(buf, 3);
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/foundation.h | C | apache-2.0 | 9,167 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
enum bt_mesh_friend_pdu_type {
BT_MESH_FRIEND_PDU_SINGLE,
BT_MESH_FRIEND_PDU_PARTIAL,
BT_MESH_FRIEND_PDU_COMPLETE,
};
bool bt_mesh_friend_match(u16_t net_idx, u16_t addr);
struct bt_mesh_friend *bt_mesh_friend_find(u16_t net_idx, u16_t lpn_addr,
bool valid, bool established);
void bt_mesh_friend_enqueue_rx(struct bt_mesh_net_rx *rx,
enum bt_mesh_friend_pdu_type type,
u64_t *seq_auth, struct net_buf_simple *sbuf);
bool bt_mesh_friend_enqueue_tx(struct bt_mesh_net_tx *tx,
enum bt_mesh_friend_pdu_type type,
u64_t *seq_auth, struct net_buf_simple *sbuf);
void bt_mesh_friend_clear_incomplete(struct bt_mesh_subnet *sub, u16_t src,
u16_t dst, u64_t *seq_auth);
void bt_mesh_friend_sec_update(u16_t net_idx);
void bt_mesh_friend_clear_net_idx(u16_t net_idx);
int bt_mesh_friend_poll(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
int bt_mesh_friend_req(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
int bt_mesh_friend_clear(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf);
int bt_mesh_friend_clear_cfm(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_friend_sub_add(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_friend_sub_rem(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_friend_init(void);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/friend.h | C | apache-2.0 | 1,482 |
/**
* @file testing.h
* @brief Internal API for Bluetooth testing.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
void bt_test_mesh_net_recv(u8_t ttl, u8_t ctl, u16_t src, u16_t dst,
const void *payload, size_t payload_len);
void bt_test_mesh_model_bound(u16_t addr, struct bt_mesh_model *model,
u16_t key_idx);
void bt_test_mesh_model_unbound(u16_t addr, struct bt_mesh_model *model,
u16_t key_idx);
void bt_test_mesh_prov_invalid_bearer(u8_t opcode);
void bt_test_mesh_trans_incomp_timer_exp(void);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/host/testing.h | C | apache-2.0 | 570 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
int bt_mesh_lpn_friend_update(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_lpn_friend_offer(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_lpn_friend_clear_cfm(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
int bt_mesh_lpn_friend_sub_cfm(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
static inline bool bt_mesh_lpn_established(void)
{
#if defined(CONFIG_BT_MESH_LOW_POWER)
return bt_mesh.lpn.established;
#else
return false;
#endif
}
static inline bool bt_mesh_lpn_match(u16_t addr)
{
#if defined(CONFIG_BT_MESH_LOW_POWER)
if (bt_mesh_lpn_established()) {
return (addr == bt_mesh.lpn.frnd);
}
#endif
return false;
}
static inline bool bt_mesh_lpn_waiting_update(void)
{
#if defined(CONFIG_BT_MESH_LOW_POWER)
return (bt_mesh.lpn.state == BT_MESH_LPN_WAIT_UPDATE);
#else
return false;
#endif
}
static inline bool bt_mesh_lpn_timer(void)
{
#if defined(CONFIG_BT_MESH_LPN_AUTO)
return (bt_mesh.lpn.state == BT_MESH_LPN_TIMER);
#else
return false;
#endif
}
void bt_mesh_lpn_msg_received(struct bt_mesh_net_rx *rx);
void bt_mesh_lpn_group_add(u16_t group);
void bt_mesh_lpn_group_del(u16_t *groups, size_t group_count);
void bt_mesh_lpn_disable(bool force);
int bt_mesh_lpn_init(void);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/lpn.h | C | apache-2.0 | 1,407 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define BT_MESH_KEY_PRIMARY 0x0000
#define BT_MESH_KEY_ANY 0xffff
#define BT_MESH_ADDR_IS_UNICAST(addr) ((addr) && (addr) < 0x8000)
#define BT_MESH_ADDR_IS_GROUP(addr) ((addr) >= 0xc000 && (addr) <= 0xff00)
#define BT_MESH_ADDR_IS_VIRTUAL(addr) ((addr) >= 0x8000 && (addr) < 0xc000)
#define BT_MESH_ADDR_IS_RFU(addr) ((addr) >= 0xff00 && (addr) <= 0xfffb)
struct bt_mesh_net;
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/mesh.h | C | apache-2.0 | 495 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _MESH_NET_H_
#define _MESH_NET_H_
#define BT_MESH_NET_FLAG_KR BIT(0)
#define BT_MESH_NET_FLAG_IVU BIT(1)
#define BT_MESH_KR_NORMAL 0x00
#define BT_MESH_KR_PHASE_1 0x01
#define BT_MESH_KR_PHASE_2 0x02
#define BT_MESH_KR_PHASE_3 0x03
#define BT_MESH_IV_UPDATE(flags) ((flags >> 1) & 0x01)
#define BT_MESH_KEY_REFRESH(flags) (flags & 0x01)
/* How many hours in between updating IVU duration */
#define BT_MESH_IVU_MIN_HOURS 96
#define BT_MESH_IVU_HOURS (BT_MESH_IVU_MIN_HOURS / CONFIG_BT_MESH_IVU_DIVIDER)
#define BT_MESH_IVU_TIMEOUT K_HOURS(BT_MESH_IVU_HOURS)
#define BT_MESH_NET_MAX_PDU_LEN 29
#if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
struct net_buf_trace_t {
void *buf;
u8_t addr[12];
};
extern struct net_buf_trace_t net_buf_trace;
#endif
struct bt_mesh_app_key {
u16_t net_idx;
u16_t app_idx;
bool updated;
bool appkey_active;
struct bt_mesh_app_keys {
u8_t id;
u8_t val[16];
} keys[2];
};
struct bt_mesh_subnet {
bt_u32_t beacon_sent; /* Timestamp of last sent beacon */
u8_t beacons_last; /* Number of beacons during last
* observation window
*/
u8_t beacons_cur; /* Number of beaconds observed during
* currently ongoing window.
*/
u8_t beacon_cache[21]; /* Cached last authenticated beacon */
u16_t net_idx; /* NetKeyIndex */
bool kr_flag; /* Key Refresh Flag */
u8_t kr_phase; /* Key Refresh Phase */
u8_t node_id; /* Node Identity State */
bt_u32_t node_id_start; /* Node Identity started timestamp */
u8_t auth[8]; /* Beacon Authentication Value */
bool subnet_active;
struct bt_mesh_subnet_keys {
u8_t net[16]; /* NetKey */
u8_t nid; /* NID */
u8_t enc[16]; /* EncKey */
u8_t net_id[8]; /* Network ID */
#if defined(CONFIG_BT_MESH_GATT_PROXY)
u8_t identity[16]; /* IdentityKey */
#endif
u8_t privacy[16]; /* PrivacyKey */
u8_t beacon[16]; /* BeaconKey */
} keys[2];
};
struct bt_mesh_rpl {
u16_t src;
bool old_iv;
#if defined(CONFIG_BT_SETTINGS)
bool store;
#endif
bt_u32_t seq;
};
#if defined(CONFIG_BT_MESH_FRIEND)
#define FRIEND_SEG_RX CONFIG_BT_MESH_FRIEND_SEG_RX
#define FRIEND_SUB_LIST_SIZE CONFIG_BT_MESH_FRIEND_SUB_LIST_SIZE
#else
#define FRIEND_SEG_RX 0
#define FRIEND_SUB_LIST_SIZE 0
#endif
struct bt_mesh_friend {
u16_t lpn;
u8_t recv_delay;
u8_t fsn:1, send_last:1, pending_req:1, sec_update:1, pending_buf:1, valid:1, established:1;
bt_s32_t poll_to;
u8_t num_elem;
u16_t lpn_counter;
u16_t counter;
u16_t net_idx;
u16_t sub_list[FRIEND_SUB_LIST_SIZE];
struct k_delayed_work timer;
struct bt_mesh_friend_seg {
sys_slist_t queue;
} seg[FRIEND_SEG_RX];
struct net_buf *last;
sys_slist_t queue;
bt_u32_t queue_size;
/* Friend Clear Procedure */
struct {
bt_u32_t start; /* Clear Procedure start */
u16_t frnd; /* Previous Friend's address */
u16_t repeat_sec; /* Repeat timeout in seconds */
struct k_delayed_work timer; /* Repeat timer */
} clear;
};
#if defined(CONFIG_BT_MESH_LOW_POWER)
#define LPN_GROUPS CONFIG_BT_MESH_LPN_GROUPS
#else
#define LPN_GROUPS 0
#endif
/* Low Power Node state */
struct bt_mesh_lpn {
enum __packed {
BT_MESH_LPN_DISABLED, /* LPN feature is disabled */
BT_MESH_LPN_CLEAR, /* Clear in progress */
BT_MESH_LPN_TIMER, /* Waiting for auto timer expiry */
BT_MESH_LPN_ENABLED, /* LPN enabled, but no Friend */
BT_MESH_LPN_REQ_WAIT, /* Wait before scanning for offers */
BT_MESH_LPN_WAIT_OFFER, /* Friend Req sent */
BT_MESH_LPN_ESTABLISHED, /* Friendship established */
BT_MESH_LPN_RECV_DELAY, /* Poll sent, waiting ReceiveDelay */
BT_MESH_LPN_WAIT_UPDATE, /* Waiting for Update or message */
} state;
/* Transaction Number (used for subscription list) */
u8_t xact_next;
u8_t xact_pending;
u8_t sent_req;
/* Address of our Friend when we're a LPN. Unassigned if we don't
* have a friend yet.
*/
u16_t frnd;
/* Value from the friend offer */
u8_t recv_win;
u8_t req_attempts; /* Number of Request attempts */
bt_s32_t poll_timeout;
u8_t groups_changed:1, /* Friend Subscription List needs updating */
pending_poll:1, /* Poll to be sent after subscription */
disable:1, /* Disable LPN after clearing */
fsn:1, /* Friend Sequence Number */
established:1, /* Friendship established */
clear_success:1; /* Friend Clear Confirm received */
/* Friend Queue Size */
u8_t queue_size;
/* LPNCounter */
u16_t counter;
/* Previous Friend of this LPN */
u16_t old_friend;
/* Duration reported for last advertising packet */
u16_t adv_duration;
/* Next LPN related action timer */
struct k_delayed_work timer;
/* Subscribed groups */
u16_t groups[LPN_GROUPS];
/* Bit fields for tracking which groups the Friend knows about */
ATOMIC_DEFINE(added, LPN_GROUPS);
ATOMIC_DEFINE(pending, LPN_GROUPS);
ATOMIC_DEFINE(to_remove, LPN_GROUPS);
};
/* bt_mesh_net.flags */
enum {
BT_MESH_VALID, /* We have been provisioned */
BT_MESH_SUSPENDED, /* Network is temporarily suspended */
BT_MESH_IVU_IN_PROGRESS, /* IV Update in Progress */
BT_MESH_IVU_INITIATOR, /* IV Update initiated by us */
BT_MESH_IVU_TEST, /* IV Update test mode */
BT_MESH_IVU_PENDING, /* Update blocked by SDU in progress */
/* pending storage actions */
BT_MESH_RPL_PENDING,
BT_MESH_KEYS_PENDING,
BT_MESH_NET_PENDING,
BT_MESH_IV_PENDING,
BT_MESH_SEQ_PENDING,
BT_MESH_HB_PUB_PENDING,
BT_MESH_CFG_PENDING,
BT_MESH_MOD_PENDING,
#ifdef CONFIG_BT_MESH_PROVISIONER
BT_MESH_PROV_NODE_PENDING,
#endif
/* Don't touch - intentionally last */
BT_MESH_FLAG_COUNT,
};
struct bt_mesh_net {
bt_u32_t iv_index; /* Current IV Index */
bt_u32_t seq:24, /* Next outgoing sequence number */
iv_update:1, /* 1 if IV Update in Progress */
ivu_initiator:1, /* IV Update initiated by us */
ivu_test:1, /* IV Update test mode */
pending_update:1, /* Update blocked by SDU in progress */
valid:1; /* 0 if unused */
ATOMIC_DEFINE(flags, BT_MESH_FLAG_COUNT);
s64_t last_update; /* Time since last IV Update change */
/* Local network interface */
struct k_work local_work;
sys_slist_t local_queue;
#if defined(CONFIG_BT_MESH_FRIEND)
/* Friend state, unique for each LPN that we're Friends for */
struct bt_mesh_friend frnd[CONFIG_BT_MESH_FRIEND_LPN_COUNT];
#endif
#if defined(CONFIG_BT_MESH_LOW_POWER)
struct bt_mesh_lpn lpn; /* Low Power Node state */
#endif
/* Number of hours in current IV Update state */
u8_t ivu_duration;
/* Timer to track duration in current IV Update state */
struct k_delayed_work ivu_timer;
u8_t dev_key[16];
struct bt_mesh_app_key app_keys[CONFIG_BT_MESH_APP_KEY_COUNT];
struct bt_mesh_subnet sub[CONFIG_BT_MESH_SUBNET_COUNT];
struct bt_mesh_rpl rpl[CONFIG_BT_MESH_CRPL];
#ifdef CONFIG_BT_MESH_PROVISIONER
/* Provisioner and node share arguments from 'iv_index' to 'local_queue' + 'ivu_complete' */
/* Application keys stored by provisioner */
// struct bt_mesh_app_key p_app_keys[CONFIG_BT_MESH_PROVISIONER_APP_KEY_COUNT];
/* Next app_idx can be assigned */
u16_t p_app_idx_next;
/* Network keys stored by provisioner */
// struct bt_mesh_subnet p_sub[CONFIG_BT_MESH_PROVISIONER_SUBNET_COUNT];
/* Next net_idx can be assigned */
u16_t p_net_idx_next;
#endif
};
/* Network interface */
enum bt_mesh_net_if {
BT_MESH_NET_IF_ADV,
BT_MESH_NET_IF_LOCAL,
BT_MESH_NET_IF_PROXY,
BT_MESH_NET_IF_PROXY_CFG,
};
/* Decoding context for Network/Transport data */
struct bt_mesh_net_rx {
struct bt_mesh_subnet *sub;
struct bt_mesh_msg_ctx ctx;
bt_u32_t seq; /* Sequence Number */
u8_t old_iv:1, /* iv_index - 1 was used */
new_key:1, /* Data was encrypted with updated key */
friend_cred:1, /* Data was encrypted with friend cred */
ctl:1, /* Network Control */
net_if:2, /* Network interface */
local_match:1, /* Matched a local element */
friend_match:1; /* Matched an LPN we're friends for */
s8_t rssi;
};
/* Encoding context for Network/Transport data */
struct bt_mesh_net_tx {
struct bt_mesh_subnet *sub;
struct bt_mesh_msg_ctx *ctx;
u16_t src;
u8_t xmit;
u8_t friend_cred:1, aszmic:1, aid:6;
};
extern struct bt_mesh_net bt_mesh;
extern u16_t g_sub_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT];
#define BT_MESH_NET_IVI_TX (bt_mesh.iv_index - atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS))
#define BT_MESH_NET_IVI_RX(rx) (bt_mesh.iv_index - (rx)->old_iv)
#define BT_MESH_NET_HDR_LEN 9
int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys, const u8_t key[16]);
int bt_mesh_net_create(u16_t idx, u8_t flags, const u8_t key[16], bt_u32_t iv_index);
u8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub);
bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, u8_t new_kr, bool new_key);
void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub);
int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub);
void bt_mesh_rpl_reset(void);
bool bt_mesh_net_iv_update(bt_u32_t iv_index, bool iv_update);
void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub);
struct bt_mesh_subnet *bt_mesh_subnet_get(u16_t net_idx);
struct bt_mesh_subnet *bt_mesh_subnet_find(const u8_t net_id[8], u8_t flags, bt_u32_t iv_index, const u8_t auth[8],
bool *new_key);
int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf, bool proxy);
int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf, const struct bt_mesh_send_cb *cb, void *cb_data);
int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf, bool new_key, const struct bt_mesh_send_cb *cb,
void *cb_data);
int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if, struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf);
void bt_mesh_net_recv(struct net_buf_simple *data, s8_t rssi, enum bt_mesh_net_if net_if);
bt_u32_t bt_mesh_next_seq(void);
void bt_mesh_net_start(void);
void bt_mesh_net_init(void);
/* Friendship Credential Management */
struct friend_cred {
u16_t net_idx;
u16_t addr;
u16_t lpn_counter;
u16_t frnd_counter;
struct {
u8_t nid; /* NID */
u8_t enc[16]; /* EncKey */
u8_t privacy[16]; /* PrivacyKey */
} cred[2];
};
int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, const u8_t **enc, const u8_t **priv);
int friend_cred_set(struct friend_cred *cred, u8_t idx, const u8_t net_key[16]);
void friend_cred_refresh(u16_t net_idx);
int friend_cred_update(struct bt_mesh_subnet *sub);
struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, u16_t addr, u16_t lpn_counter, u16_t frnd_counter);
void friend_cred_clear(struct friend_cred *cred);
int friend_cred_del(u16_t net_idx, u16_t addr);
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/net.h | C | apache-2.0 | 11,355 |
/** @file
* @brief Bluetooth Mesh Profile APIs.
*/
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _MESH_EVENT_H_
#define _MESH_EVENT_H_
typedef enum {
BT_MESH_MODEL_EVT_PROV_START = 0x00,
BT_MESH_MODEL_EVT_PROV_DATA,
BT_MESH_MODEL_EVT_APPKEY_ADD,
BT_MESH_MODEL_EVT_APPKEY_UPDATE,
BT_MESH_MODEL_EVT_APPKEY_DEL,
BT_MESH_MODEL_EVT_APPKEY_BIND_STATUS,
BT_MESH_MODEL_EVT_APPKEY_STATUS,
BT_MESH_MODEL_EVT_NETKEY_ADD,
BT_MESH_MODEL_EVT_NETKEY_UPDATE,
BT_MESH_MODEL_EVT_NETKEY_DEL,
BT_MESH_MODEL_EVT_NETKEY_STATUS,
BT_MESH_MODEL_EVT_NET_KRP_STATUS,
BT_MESH_MODEL_EVT_SEQ_UPDATE,
BT_MESH_MODEL_EVT_COMP_DATA_STATUS,
BT_MESH_MODEL_EVT_BEACON_STATUS,
BT_MESH_MODEL_EVT_TTL_STATUS,
BT_MESH_MODEL_EVT_FRIEND_STATUS,
BT_MESH_MODEL_EVT_PROXY_STATUS,
BT_MESH_MODEL_EVT_RELAY_STATUS,
BT_MESH_MODEL_EVT_PUB_STATUS,
BT_MESH_MODEL_EVT_SUB_STATUS,
BT_MESH_MODEL_EVT_SUB_ADD,
BT_MESH_MODEL_EVT_SUB_DEL,
BT_MESH_MODEL_EVT_SUB_LIST,
BT_MESH_MODEL_EVT_SUB_LIST_VND,
BT_MESH_MODEL_EVT_HB_SUB_STATUS,
BT_MESH_MODEL_EVT_HB_PUB_STATUS,
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
BT_MESH_MODEL_EVT_CTRL_RELAY_STATUS,
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
BT_MESH_MODEL_EVT_NODE_RESET_OP,
BT_MESH_MODEL_EVT_NODE_RESET_STATUS,
BT_MESH_MODEL_EVT_RPL_IS_FULL,
} mesh_model_event_e;
typedef struct {
uint16_t source_addr;
void *user_data;
} bt_mesh_model_evt_t;
typedef void (*mesh_model_evt_cb)(mesh_model_event_e event, void *p_arg);
int bt_mesh_event_init(void);
int bt_mesh_event_register(mesh_model_evt_cb event_cb);
mesh_model_evt_cb bt_mesh_event_get_cb_func(void);
#endif /* _GENIE_MESH_API_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/port/mesh_event_port.h | C | apache-2.0 | 1,831 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#ifndef _MESH_HAL_BLE_H_
#define _MESH_HAL_BLE_H_
#include <stdint.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include <net/buf.h>
#include <api/mesh.h>
/** @typedef bt_mesh_le_scan_cb_t
* @brief Callback type for reporting LE scan results.
*
* A function of this type is given to the bt_mesh_le_scan_start() function
* and will be called for any discovered LE device.
*
* @param addr Advertiser LE address and type.
* @param rssi Strength of advertiser signal.
* @param adv_type Type of advertising response from advertiser.
* @param data Buffer containing advertiser data.
*/
typedef void bt_mesh_le_scan_cb_t(const bt_addr_le_t *addr, int8_t rssi,
uint8_t adv_type, struct net_buf_simple *buf);
/** @brief Start advertising
*
* Set advertisement data, scan response data, advertisement parameters
* and start advertising.
*
* @param param Advertising parameters.
* @param ad Data to be used in advertisement packets.
* @param ad_len Number of elements in ad
* @param sd Data to be used in scan response packets.
* @param sd_len Number of elements in sd
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_adv_start(const struct bt_le_adv_param *param,
const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len);
/** @brief Stop advertising
*
* Stops ongoing advertising.
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_adv_stop(void);
/** @brief Start (LE) scanning
*
* Start LE scanning with given parameters and provide results through
* the specified callback.
*
* @param param Scan parameters.
* @param cb Callback to notify scan results.
*
* @return Zero on success or error code otherwise, positive in case
* of protocol error or negative (POSIX) in case of stack internal error
*/
int bt_mesh_scan_start(const struct bt_le_scan_param *param, bt_mesh_le_scan_cb_t cb);
/** @brief Stop (LE) scanning.
*
* Stops ongoing LE scanning.
*
* @return Zero on success or error code otherwise, positive in case
* of protocol error or negative (POSIX) in case of stack internal error
*/
int bt_mesh_scan_stop(void);
/** @brief Register connection callbacks.
*
* Register callbacks to monitor the state of connections.
*
* @param cb Callback struct.
*/
void bt_mesh_conn_cb_register(struct bt_conn_cb *cb);
/** @brief Increment a connection's reference count.
*
* Increment the reference count of a connection object.
*
* @param conn Connection object.
*
* @return Connection object with incremented reference count.
*/
struct bt_conn *bt_mesh_conn_ref(struct bt_conn *conn);
/** @brief Decrement a connection's reference count.
*
* Decrement the reference count of a connection object.
*
* @param conn Connection object.
*/
void bt_mesh_conn_unref(struct bt_conn *conn);
/** @brief Disconnect from a remote device or cancel pending connection.
*
* Disconnect an active connection with the specified reason code or cancel
* pending outgoing connection.
*
* @param conn Connection to disconnect.
* @param reason Reason code for the disconnection.
*
* @return Zero on success or (negative) error code on failure.
*/
int bt_mesh_conn_disconnect(struct bt_conn *conn, uint8_t reason);
/** @brief Register GATT service.
*
* Register GATT service. Applications can make use of
* macros such as BT_GATT_PRIMARY_SERVICE, BT_GATT_CHARACTERISTIC,
* BT_GATT_DESCRIPTOR, etc.
*
* @param svc Service containing the available attributes
*
* @return 0 in case of success or negative value in case of error.
*/
int bt_mesh_gatt_service_register(struct bt_gatt_service *svc);
/** @brief Unregister GATT service.
*
* @param svc Service to be unregistered.
*
* @return 0 in case of success or negative value in case of error.
*/
int bt_mesh_gatt_service_unregister(struct bt_gatt_service *svc);
/** @brief Notify attribute value change.
*
* Send notification of attribute value change, if connection is NULL notify
* all peer that have notification enabled via CCC otherwise do a direct
* notification only the given connection.
*
* The attribute object must be the so called Characteristic Value Descriptor,
* its usually declared with BT_GATT_DESCRIPTOR after BT_GATT_CHARACTERISTIC
* and before BT_GATT_CCC.
*
* @param conn Connection object.
* @param attr Characteristic Value Descriptor attribute.
* @param data Pointer to Attribute data.
* @param len Attribute value length.
*/
int bt_mesh_gatt_notify(struct bt_conn *conn, const struct bt_gatt_attr *attr,
const void *data, uint16_t len);
/** @brief Generic Read Attribute value helper.
*
* Read attribute value storing the result into buffer.
*
* @param conn Connection object.
* @param attr Attribute to read.
* @param buf Buffer to store the value.
* @param buf_len Buffer length.
* @param offset Start offset.
* @param value Attribute value.
* @param value_len Length of the attribute value.
*
* @return int number of bytes read in case of success or negative values in
* case of error.
*/
int bt_mesh_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t buf_len, uint16_t offset,
const void *value, uint16_t value_len);
/** @brief Get ATT MTU for a connection
*
* Get negotiated ATT connection MTU, note that this does not equal the largest
* amount of attribute data that can be transferred within a single packet.
*
* @param conn Connection object.
*
* @return MTU in bytes
*/
uint16_t bt_mesh_gatt_get_mtu(struct bt_conn *conn);
/** @brief Read Service Attribute helper.
*
* Read service attribute value (Spec V4.2, Vol 3, part G,
* table 3.1) storing the result into buffer after
* encoding it.
* NOTE: Only use this with attributes which user_data is a bt_mesh_uuid.
*
* @param conn Connection object.
* @param attr Attribute to read.
* @param buf Buffer to store the value read.
* @param len Buffer length.
* @param offset Start offset.
*
* @return int number of bytes read in case of success or negative values in
* case of error.
*/
int bt_mesh_gatt_attr_read_service(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset);
/** @brief Read Characteristic Attribute helper.
*
* Read characteristic attribute value (Spec V4.2, Vol 3, part G,
* table 3.3) storing the result into buffer after
* encoding it.
* NOTE: Only use this with attributes which user_data is a bt_mesh_gatt_chrc.
*
* @param conn Connection object.
* @param attr Attribute to read.
* @param buf Buffer to store the value read.
* @param len Buffer length.
* @param offset Start offset.
*
* @return number of bytes read in case of success or negative values in
* case of error.
*/
int bt_mesh_gatt_attr_read_chrc(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
uint16_t len, uint16_t offset);
#ifdef CONFIG_BT_MESH_PROVISIONER
typedef ssize_t (*gatt_recv_cb)(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
u16_t len, u16_t offset, u8_t flags);
bool bt_prov_check_gattc_id(int id, const bt_addr_le_t *addr);
int bt_gattc_conn_create(int id, u16_t srvc_uuid);
u16_t bt_mesh_get_srvc_uuid(struct bt_conn *conn);
void bt_mesh_gatt_conn_open(struct bt_conn *conn, void (*open_complete)(struct bt_conn *conn));
u16_t bt_gatt_get_data_in_handle(struct bt_conn *conn);
u16_t bt_gatt_prov_get_mtu(struct bt_conn *conn);
struct bt_conn * bt_mesh_get_curr_conn(void);
void set_my_addr(u8_t index, const u8_t *addr, u8_t type);
void bt_mesh_gatt_recv_callback(gatt_recv_cb recv_callback);
int bt_prov_get_gattc_id(u8_t *addr);
#endif
#endif /* _MESH_HAL_BLE_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/port/mesh_hal_ble.h | C | apache-2.0 | 8,200 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#ifndef _MESH_HAL_SEC_H_
#define _MESH_HAL_SEC_H_
#include <stdint.h>
typedef void (*bt_mesh_dh_key_cb_t)(const uint8_t key[32]);
/* @brief Container for public key callback */
struct bt_mesh_pub_key_cb {
/** @brief Callback type for Public Key generation.
*
* Used to notify of the local public key or that the local key is not
* available (either because of a failure to read it or because it is
* being regenerated).
*
* @param key The local public key, or NULL in case of no key.
*/
void (*func)(const uint8_t key[64]);
struct bt_mesh_pub_key_cb *_next;
};
/** @brief Generate random data.
*
* A random number generation helper which utilizes the Bluetooth
* controller's own RNG.
*
* @param buf Buffer to insert the random data
* @param len Length of random data to generate
*
* @return Zero on success or error code otherwise, positive in case
* of protocol error or negative (POSIX) in case of stack internal error
*/
int bt_mesh_rand(void *buf, size_t len);
/** @brief AES-128 ECB
*
* A function used to perform AES-128 ECB encryption.
* See Core Spec V4.2, Vol 3, Part H, Section 2.2.1.
*
* @param key AES key
* @param plaintext The data before encryption
* @param enc_data The data after encryption
*
* @return 0 on sucess, otherwise negative number
*/
int bt_mesh_aes_encrypt(const uint8_t key[16], const uint8_t plaintext[16], uint8_t enc_data[16]);
int bt_mesh_aes_decrypt(const uint8_t key[16], const uint8_t enc_data[16], uint8_t dec_data[16]);
/* @brief Get the current Public Key.
*
* Get the current ECC Public Key.
*
* @return Current key, or NULL if not available.
*/
const uint8_t *bt_mesh_pub_key_get(void);
/* @brief Calculate a DH Key from a remote Public Key.
*
* Calculate a DH Key from the remote Public Key.
*
* @param remote_pk Remote Public Key.
* @param cb Callback to notify the calculated key.
*
* @return Zero on success or negative error code otherwise
*/
int bt_mesh_dh_key_gen(const uint8_t remote_pk[64], bt_mesh_dh_key_cb_t cb);
/* @brief Generate a new Public Key.
*
* Generate a new ECC Public Key. The callback will persist even after the
* key has been generated, and will be used to notify of new generation
* processes (NULL as key).
*
* @param cb Callback to notify the new key, or NULL to request an update
* without registering any new callback.
*
* @return Zero on success or negative error code otherwise
*/
int bt_mesh_pub_key_gen(struct bt_mesh_pub_key_cb *cb);
#endif /* _MESH_HAL_SEC_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/port/mesh_hal_sec.h | C | apache-2.0 | 2,680 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __PROV_H
#define __PROV_H
void bt_mesh_pb_adv_recv(struct net_buf_simple *buf);
bool bt_prov_active(void);
int bt_mesh_pb_gatt_open(struct bt_conn *conn);
int bt_mesh_pb_gatt_close(struct bt_conn *conn);
int bt_mesh_pb_gatt_recv(struct bt_conn *conn, struct net_buf_simple *buf);
const struct bt_mesh_prov *bt_mesh_prov_get(void);
int bt_mesh_prov_init(const struct bt_mesh_prov *prov);
void bt_mesh_prov_complete(u16_t net_idx, u16_t addr);
void bt_mesh_prov_reset(void);
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/prov.h | C | apache-2.0 | 607 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _PROVISIONER_BEACON_H_
#define _PROVISIONER_BEACON_H_
void provisioner_beacon_recv(struct net_buf_simple *buf);
void bt_mesh_beacon_init(void);
#endif /* _PROVISIONER_BEACON_H_ */ | YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/provisioner_beacon.h | C | apache-2.0 | 807 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _PROVISIONER_MAIN_H_
#define _PROVISIONER_MAIN_H_
#define MESH_NAME_SIZE 31
#ifdef CONFIG_BT_MESH_PROVISIONER
enum {
MESH_NODE_FLAG_STORE = 0x01,
MESH_NODE_FLAG_CLEAR = 0x02,
};
/* Each node information stored by provisioner */
struct bt_mesh_node_t {
char node_name[MESH_NAME_SIZE]; /* Node name */
u8_t dev_uuid[16]; /* Device UUID pointer, stored in provisioner_prov.c */
u16_t oob_info; /* Node OOB information */
u16_t unicast_addr; /* Node unicast address */
u8_t element_num; /* Node element number */
u16_t net_idx; /* Node provision net_idx */
u8_t flags; /* Node key refresh flag and iv update flag */
bt_u32_t iv_index; /* Node IV Index */
u8_t dev_key[16]; /* Node device key */
bool node_active;
u8_t addr_val[6];
u8_t addr_type:4;
u8_t flag:4; /* If node is stored */
} __packed;
/* The following APIs are for key init, node provision & node reset. */
int provisioner_node_provision(int node_index, const u8_t uuid[16], u16_t oob_info,
u16_t unicast_addr, u8_t element_num, u16_t net_idx,
u8_t flags, bt_u32_t iv_index, const u8_t dev_key[16], u8_t *dev_addr);
int provisioner_node_reset(int node_index);
int provisioner_upper_reset_all_nodes(void);
int provisioner_upper_init(void);
/* The following APIs are for provisioner upper layers internal usage. */
const u8_t *provisioner_net_key_get(u16_t net_idx);
struct bt_mesh_subnet *provisioner_subnet_get(u16_t net_idx);
bool provisioner_check_msg_dst_addr(u16_t dst_addr);
const u8_t *provisioner_get_device_key(u16_t dst_addr);
struct bt_mesh_app_key *provisioner_app_key_find(u16_t app_idx);
bt_u32_t provisioner_get_prov_node_count(void);
/* The following APIs are for provisioner application use. */
int bt_mesh_provisioner_store_node_info(struct bt_mesh_node_t *node_info);
int bt_mesh_provisioner_get_all_node_unicast_addr(struct net_buf_simple *buf);
int bt_mesh_provisioner_set_node_name(int node_index, const char *name);
const char *bt_mesh_provisioner_get_node_name(int node_index);
int bt_mesh_provisioner_get_node_index(const char *name);
struct bt_mesh_node_t *bt_mesh_provisioner_get_node_info(u16_t unicast_addr);
bt_u32_t bt_mesh_provisioner_get_net_key_count(void);
bt_u32_t bt_mesh_provisioner_get_app_key_count(void);
int bt_mesh_provisioner_local_app_key_add(const u8_t app_key[16], u16_t net_idx, u16_t *app_idx);
const u8_t *bt_mesh_provisioner_local_app_key_get(u16_t net_idx, u16_t app_idx);
int bt_mesh_provisioner_local_app_key_delete(u16_t net_idx, u16_t app_idx);
int bt_mesh_provisioner_local_net_key_add(const u8_t net_key[16], u16_t *net_idx);
const u8_t *bt_mesh_provisioner_local_net_key_get(u16_t net_idx);
int bt_mesh_provisioner_local_net_key_delete(u16_t net_idx);
int bt_mesh_provisioner_get_own_unicast_addr(u16_t *addr, u8_t *elem_num);
/* Provisioner bind local client model with proper appkey index */
int bt_mesh_provisioner_bind_local_model_app_idx(u16_t elem_addr, u16_t mod_id,
u16_t cid, u16_t app_idx);
/* Provisioner unbind local client model with proper appkey index */
int bt_mesh_provisioner_unbind_local_model_app_idx(u16_t elem_addr, u16_t mod_id,
u16_t cid, u16_t app_idx);
/* This API can be used to change the net_idx binded with the app_idx. */
int bt_mesh_provisioner_bind_local_app_net_idx(u16_t net_idx, u16_t app_idx);
/* Provisioner print own element information */
int bt_mesh_provisioner_print_local_element_info(void);
int bt_mesh_provisioner_print_node_info(void);
/* The following APIs are for temporary provisioner use */
/* Set the net_idx to be assigned for the added netkey */
int bt_mesh_temp_prov_net_idx_set(const u8_t net_key[16], u16_t *net_idx, u8_t *status);
/* Set the app_idx to be assigned for the added appkey */
int bt_mesh_temp_prov_app_idx_set(const u8_t app_key[16], u16_t net_idx, u16_t *app_idx, u8_t *status);
bool provisioner_is_node_provisioned(const u8_t *dev_addr);
bool bt_mesh_is_provisioner_en(void);
struct bt_mesh_app_key *bt_mesh_provisioner_p_app_key_alloc();
struct bt_mesh_node_t *bt_mesh_provisioner_get_node_info_by_id(int node_index);
#endif /* CONFIG_BT_MESH_PROVISIONER */
#endif /* _PROVISIONER_MAIN_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/provisioner_main.h | C | apache-2.0 | 5,075 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _PROVISIONER_PROV_H_
#define _PROVISIONER_PROV_H_
#include "bluetooth/hci.h"
#include "bluetooth/conn.h"
#include "api/mesh/main.h"
#ifndef CONFIG_BT_MESH_PROVISIONER
#define CONFIG_BT_MESH_PBA_SAME_TIME 0
#define CONFIG_BT_MESH_PBG_SAME_TIME 0
#else
#if !defined(CONFIG_BT_MESH_PB_ADV)
#define CONFIG_BT_MESH_PBA_SAME_TIME 0
#else
#define CONFIG_BT_MESH_PBA_SAME_TIME 1
#endif /* !CONFIG_BT_MESH_PB_ADV */
#if !defined(CONFIG_BT_MESH_PB_GATT)
#define CONFIG_BT_MESH_PBG_SAME_TIME 0
#else
#define CONFIG_BT_MESH_PBG_SAME_TIME 1
#endif /* !CONFIG_BT_MESH_PB_GATT */
#define BT_DATA_FLAGS 0x01
#define BT_DATA_SERVICE_UUID 0x03
#define BT_DATA_SERVICE_DATA 0X16
#define RM_AFTER_PROV BIT(0)
#define START_PROV_NOW BIT(1)
#define FLUSHABLE_DEV BIT(2)
#define BT_UUID_MESH_PROV_VAL (0x1827)
#define BT_UUID_MESH_PROXY_VAL (0x1828)
typedef struct _auto_appkey_config {
u8_t auto_add_appkey;
u16_t auto_appkey_idx;
} auto_appkey_config;
struct bt_mesh_unprov_dev_add {
u8_t addr[6];
u8_t addr_type;
u8_t uuid[16];
u8_t bearer;
u16_t oob_info;
uint8_t auto_add_appkey;
};
struct bt_mesh_device_delete {
u8_t addr[6];
u8_t addr_type;
u8_t uuid[16];
};
#define NET_IDX_FLAG BIT(0)
#define FLAGS_FLAG BIT(1)
#define IV_INDEX_FLAG BIT(2)
struct bt_mesh_prov_data_info {
union {
u16_t net_idx;
u8_t flags;
bt_u32_t iv_index;
};
u8_t flag;
};
struct bt_conn;
struct bt_le_conn_param;
struct node_info {
bool provisioned; /* device provisioned flag */
bt_addr_le_t addr; /* device address */
u8_t uuid[16]; /* node uuid */
u16_t oob_info; /* oob info contained in adv pkt */
u8_t element_num; /* element contained in this node */
u16_t unicast_addr; /* primary unicast address of this node */
u16_t net_idx; /* Netkey index got during provisioning */
u8_t flags; /* Key refresh flag and iv update flag */
bt_u32_t iv_index; /* IV Index */
bt_u32_t provisioned_time; /* provison time */
uint8_t auto_add_appkey;
; /*node auto add appkey flag*/
};
#ifdef CONFIG_BT_MESH_PROVISIONER
struct bt_prov_conn_cb {
void (*connected)(struct bt_conn *conn, int id);
void (*disconnected)(struct bt_conn *conn, u8_t reason);
size_t (*prov_write_descr)(struct bt_conn *conn, u8_t *addr);
size_t (*prov_notify)(struct bt_conn *conn, u8_t *data, u16_t len);
size_t (*proxy_write_descr)(struct bt_conn *conn);
size_t (*proxy_notify)(struct bt_conn *conn, u8_t *data, u16_t len);
bool (*le_param_req)(struct bt_conn *conn, struct bt_le_conn_param *param);
void (*le_param_updated)(struct bt_conn *conn, u16_t interval, u16_t latency, u16_t timeout);
#if defined(CONFIG_BT_SMP)
void (*identity_resolved)(struct bt_conn *conn, const bt_addr_le_t *rpa, const bt_addr_le_t *identity);
#endif /* CONFIG_BT_SMP */
#if defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR)
void (*security_changed)(struct bt_conn *conn, bt_security_t level);
#endif /* defined(CONFIG_BT_SMP) || defined(CONFIG_BT_BREDR) */
struct bt_conn_cb *_next;
};
#endif /* CONFIG_BT_MESH_PROVISIONER */
/* The following APIs are for primary provisioner internal use */
/**
* @brief This function is called to decrement the current PB-GATT count.
*
* @return None
*/
void provisioner_pbg_count_dec(void);
/**
* @brief This function is called to increment the current PB-GATT count.
*
* @return None
*/
void provisioner_pbg_count_inc(void);
/**
* @brief This function is called to clear part of the link
* info of the proper device.
*
* @param[in] index: Index of link within the array.
*
* @return None
*/
void provisioner_clear_connecting(int index);
/**
* @brief This function is called to deal with the received PB-ADV pdus.
*
* @param[in] buf: Pointer to the buffer containing generic provisioning pdus
*
* @return Zero-success, other-fail
*/
void provisioner_pb_adv_recv(struct net_buf_simple *buf);
/**
* @brief This function is called to send provisioning invite to start
* provisioning this unprovisioned device.
*
* @param[in] conn: Pointer to the bt_conn structure
* @param[in] index: The 'index' link whose conn will be set
*
* @return Zero-success, other-fail
*/
int provisioner_set_prov_conn(struct bt_conn *conn, int index);
/**
* @brief This function is called to send provisioning invite to start
* provisioning this unprovisioned device.
*
* @param[in] conn: Pointer to the bt_conn structure
* @param[in] addr: Address of the connected device
*
* @return Zero-success, other-fail
*/
int provisioner_pb_gatt_open(struct bt_conn *conn, u8_t *addr);
/**
* @brief This function is called to reset the used information when
* related connection is terminated.
*
* @param[in] conn: Pointer to the bt_conn structure
* @param[in] reason: Connection terminated reason
*
* @return Zero-success, other-fail
*/
int provisioner_pb_gatt_close(struct bt_conn *conn, u8_t reason);
/**
* @brief This function is called to deal with the received PB-GATT provision
* pdus.
*
* @param[in] conn: Pointer to the bt_conn structure
* @param[in] buf: Pointer to the buffer containing provision pdus
*
* @return Zero-success, other-fail
*/
int provisioner_pb_gatt_recv(struct bt_conn *conn, struct net_buf_simple *buf);
/**
* @brief This function is called to initialize provisioner's PB-GATT and PB-ADV
* related informations.
*
* @param[in] prov_info: Pointer to the application-initialized provisioner info.
*
* @return Zero-success, other-fail
*/
int provisioner_prov_init(const struct bt_mesh_provisioner *provisioner_info);
/**
* @brief This function is called to parse the received unprovisioned device
* beacon adv pkts, and if checked, start to provision this device
* using PB-ADV bearer.
*
* @param[in] buf: Pointer to the buffer containing unprovisioned device beacon
*
* @return None
*/
void provisioner_unprov_beacon_recv(struct net_buf_simple *buf);
/**
* @brief This function is called to parse the flags part of the
* received connectable mesh provisioning adv pkts.
*
* @param[in] buf: Pointer to the buffer containing adv flags part
*
* @return True-success, False-fail
*/
bool provisioner_flags_match(struct net_buf_simple *buf);
/**
* @brief This function is called to parse the service uuid part of the
* received connectable mesh provisioning adv pkts.
*
* @param[in] buf: Pointer to the buffer containing service uuid part
*
* @return Zero-fail, other-Service UUID(0x1827 or 0x1828)
*/
u16_t provisioner_srv_uuid_recv(struct net_buf_simple *buf);
/**
* @brief This function is called to parse the service data part of the
* received connectable mesh provisioning adv pkts.
*
* @param[in] buf: Pointer to the buffer containing remianing service data part
* @param[in] addr: Pointer to the received device address
* @param[in] uuid: Service UUID contained in the service uuid part
*
* @return None
*/
void provisioner_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr, u16_t uuid);
/**
* @brief This function is called to get bt_mesh_prov pointer.
*
* @return bt_mesh_prov pointer(prov)
*/
const struct bt_mesh_provisioner *provisioner_get_prov_info(void);
/**
* @brief This function is called to reset all nodes information in provisioner_prov.c.
*
* @return Zero
*/
int provisioner_prov_reset_all_nodes(void);
/* The following APIs are for primary provisioner application use */
/** @brief Add unprovisioned device info to unprov_dev queue
*
* @param[in] add_dev: Pointer to the structure containing the device information
* @param[in] flags: Flags indicate several oprations of the device information
* - Remove device information from queue after been provisioned (BIT0)
* - Start provisioning at once when device is added to queue (BIT1)
* - Device can be flushed when device queue is full (BIT2)
*
* @return Zero on success or (negative) error code otherwise.
*
* @Note: 1. Currently address type only supports public address and static random address.
* 2. If device UUID and/or device address and address type already exist in the
* device queue, but the bearer is different with the existing one, add operation
* will also be successful and it will update the provision bearer supported by
* the device.
*/
int bt_mesh_provisioner_add_unprov_dev(struct bt_mesh_unprov_dev_add *add_dev, u8_t flags);
/** @brief Delete device from queue, reset current provisioning link and reset the node
*
* @param[in] del_dev: Pointer to the structure containing the device information
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_provisioner_delete_device(struct bt_mesh_device_delete *del_dev);
/** @brief Delete unprov device from queue, reset current provisioning link and reset the node
*
* @param[in] del_dev: Pointer to the structure containing the device information
*
* @return Zero on success or (negative) error code otherwise.
*/
int bt_mesh_provisioner_delete_unprov_device(struct bt_mesh_device_delete *del_dev);
/**
* @brief This function is called to set part of the device uuid to be compared before
* starting to provision the device.
*
* @param[in] offset: offset of the device uuid to be compared
* @param[in] length: length of the device uuid to be compared
* @param[in] match: value to be compared
* @param[in] prov_flag: flags indicate when received uuid_match adv pkts, the device
* will be provisioned at once or report to application layer
*
* @return 0 - success, others - fail
*/
int bt_mesh_provisioner_set_dev_uuid_match(u8_t offset, u8_t length, const u8_t *match, bool prov_flag);
/** @brief Callback for provisioner received adv pkt from unprovisioned devices which are
* not in the unprovisioned device queue.
*
* Notify the unprovisioned device beacon and mesh provisioning service adv data to application
*
* @param addr Unprovisioned device address pointer
* @param addr_type Unprovisioned device address type
* @param dev_uuid Unprovisioned device device UUID pointer
* @param bearer Adv packet received from PB-GATT or PB-ADV bearer
* @param adv_type Adv packet type, currently this is not used and we can use bearer to device
* the adv_type(ADV_IND or ADV_NONCONN_IND). Later when we support scan response
* data, this parameter will be used.
*
*/
typedef void (*prov_adv_pkt_cb)(const u8_t addr[6], const u8_t addr_type, const u8_t adv_type, const u8_t dev_uuid[16],
u16_t oob_info, bt_mesh_prov_bearer_t bearer);
/**
* @brief This function is called to register the callback which notifies the
* application layer of the received mesh provisioning or unprovisioned
* device beacon adv pkts(from devices not in the unprov device queue).
*
* @param[in] cb: Callback of the notifying adv pkts function
*
* @return Zero-success, other-fail
*/
int bt_mesh_prov_adv_pkt_cb_register(prov_adv_pkt_cb cb);
/**
* @brief This function is called to change net_idx or flags or iv_index used in provisioning data.
*
* @param[in] info: Pointer of structure containing net_idx or flags or iv_index
*
* @return 0 - success, others - fail
*/
int bt_mesh_provisioner_set_prov_data_info(struct bt_mesh_prov_data_info *info);
/* The following APIs are for temporary provisioner internal/application(bt_mesh_xxx) use */
/**
* @brief This function is called to set temp_prov_flag.
*
* @param[in] flag: Flag set to temp_prov_flag
*
* @return None
*/
void provisioner_temp_prov_flag_set(bool flag);
/**
* @brief This function is called to set unicast address range used for temp prov.
*
* @param[in] min: Minimum unicast address
* @param[in] max: Maximum unicast address
*
* @return status for set unicast address range msg
*/
u8_t bt_mesh_temp_prov_set_unicast_addr(u16_t min, u16_t max);
/**
* @brief This function is called to set flags & iv_index used for temp prov.
*
* @param[in] flags: Key refresh flag and iv update flag
* @param[in] iv_index: IV index
*
* @return 0 - success
*/
int bt_mesh_temp_prov_set_flags_iv_index(u8_t flags, bt_u32_t iv_index);
/**
* @brief This function is called to set netkey index used for temp prov.
*
* @param[in] net_key: Netkey pointer
* @param[in] net_idx: Netkey index
*
* @return status for set netkey index msg
*/
u8_t provisioner_temp_prov_set_net_idx(const u8_t *net_key, u16_t net_idx);
int bt_mesh_prov_input_data(u8_t *num, u8_t size, bool num_flag);
int bt_mesh_prov_output_data(u8_t *num, u8_t size, bool num_flag);
int provisioner_clear_prov_conn(struct bt_conn *conn);
int provisioner_prov_restore_nodes_info(bt_addr_le_t *addr, u8_t uuid[16], u16_t oob_info, u8_t element_num,
u16_t unicast_addr, u16_t net_idx, u8_t flags, bt_u32_t iv_index,
u8_t dev_key[16], bt_u32_t provisioned_time);
auto_appkey_config *get_node_autoconfig_info(u16_t unicast_addr);
int bt_mesh_provisioner_local_provision();
int bt_mesh_provisioner_add_node(struct node_info *node_info, uint8_t dev_key[16]);
#endif /* CONFIG_BT_MESH_PROVISIONER */
#endif /* #ifndef _PROVISIONER_PROV_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/provisioner_prov.h | C | apache-2.0 | 14,081 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _PROVISIONER_PROXY_H_
#define _PROVISIONER_PROXY_H_
#include <net/buf.h>
//#include "mesh_def.h"
//#include "port/mesh_hal_ble.h"
#define BT_MESH_PROXY_NET_PDU 0x00
#define BT_MESH_PROXY_BEACON 0x01
#define BT_MESH_PROXY_CONFIG 0x02
#define BT_MESH_PROXY_PROV 0x03
/**
* @brief This function is called to send proxy protocol messages.
*
* @param[in] conn: Pointer to bt_conn structure
* @param[in] type: Proxy protocol message type
* @param[in] msg: Pointer to the buffer contains sending message.
*
* @return Zero-success, other-fail
*/
int provisioner_proxy_send(struct bt_conn * conn, u8_t type, struct net_buf_simple *msg);
/**
* @brief This function is called to parse received node identity and net
* id adv pkts and create connection if deceided to.
*
* @param[in] buf: Pointer to the buffer contains received message.
*
* @return None
*/
void provisioner_proxy_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr);
/**
* @brief This function is called to initialize proxy provisioner structure
* and register proxy connection related callbacks.
*
* @return Zero-success, other-fail
*/
int provisioner_proxy_init(void);
/**
* @brief This function is called to enable dealing with proxy provisioning
* messages.
*
* @return Zero-success, other-fail
*/
int provisioner_pb_gatt_enable(void);
/**
* @brief This function is called to disable dealing with proxy provisioning
* messages and if proxy provisioning connections exist, the connections
* will be disconnected.
*
* @return Zero-success, other-fail
*/
int provisioner_pb_gatt_disable(void);
/* The following APIs are for application use */
/**
* @brief This function is called to enable receiving node identity and net
* id adv pkts.
*
* @return Zero-success, other-fail
*/
int bt_mesh_provisioner_proxy_enable(void);
/**
* @brief This function is called to disable receiving node identity and net
* id adv pkts, and if proxy connections exist, these connections will
* be disconnected.
*
* @return Zero-success, other-fail
*/
int bt_mesh_provisioner_proxy_disable(void);
int provisioner_proxy_pdu_send(struct net_buf_simple *msg);
#endif /* _PROVISIONER_PROXY_H_ */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/provisioner_proxy.h | C | apache-2.0 | 2,892 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define BT_MESH_PROXY_NET_PDU 0x00
#define BT_MESH_PROXY_BEACON 0x01
#define BT_MESH_PROXY_CONFIG 0x02
#define BT_MESH_PROXY_PROV 0x03
int bt_mesh_proxy_send(struct bt_conn *conn, u8_t type,
struct net_buf_simple *msg);
int bt_mesh_proxy_prov_enable(void);
int bt_mesh_proxy_prov_disable(bool disconnect);
int bt_mesh_proxy_gatt_enable(void);
int bt_mesh_proxy_gatt_disable(void);
void bt_mesh_proxy_gatt_disconnect(void);
uint8_t is_proxy_connected();
void bt_mesh_proxy_beacon_send(struct bt_mesh_subnet *sub);
struct net_buf_simple *bt_mesh_proxy_get_buf(void);
bt_s32_t bt_mesh_proxy_adv_start(void);
void bt_mesh_proxy_adv_stop(void);
void bt_mesh_proxy_identity_start(struct bt_mesh_subnet *sub);
void bt_mesh_proxy_identity_stop(struct bt_mesh_subnet *sub);
bool bt_mesh_proxy_relay(struct net_buf_simple *buf, u16_t dst);
void bt_mesh_proxy_addr_add(struct net_buf_simple *buf, u16_t addr);
int bt_mesh_proxy_init(void);
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/proxy.h | C | apache-2.0 | 1,073 |
/*
* Copyright (c) 2018 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __SETTINGS_H
#define __SETTINGS_H
void bt_mesh_store_net(void);
void bt_mesh_store_iv(bool only_duration);
void bt_mesh_store_seq(void);
void bt_mesh_store_rpl(struct bt_mesh_rpl *rpl);
void bt_mesh_clear_node_rpl(uint16_t addr);
void bt_mesh_clear_all_node_rpl();
void bt_mesh_store_subnet(struct bt_mesh_subnet *sub, bool p_key);
void bt_mesh_store_app_key(struct bt_mesh_app_key *key, bool p_key);
void bt_mesh_store_hb_pub(void);
void bt_mesh_store_cfg(void);
void bt_mesh_store_mod_bind(struct bt_mesh_model *mod);
void bt_mesh_store_mod_sub(struct bt_mesh_model *mod);
void bt_mesh_store_mod_pub(struct bt_mesh_model *mod);
void bt_mesh_clear_net(void);
void bt_mesh_clear_subnet(struct bt_mesh_subnet *sub, bool p_key);
void bt_mesh_clear_app_key(struct bt_mesh_app_key *key, bool p_key);
void bt_mesh_clear_rpl(void);
void bt_mesh_settings_init(void);
void bt_mesh_clear_mesh_node(int node_index);
void bt_mesh_store_mesh_node(int node_index);
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/settings.h | C | apache-2.0 | 1,062 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#if defined(CONFIG_BT_MESH_SELF_TEST)
int bt_mesh_test(void);
#else
static inline int bt_mesh_test(void)
{
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/inc/test.h | C | apache-2.0 | 240 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <ble_types/types.h>
#include <api/mesh.h>
#include "common/log.h"
#include "net.h"
#include "foundation.h"
#include "mesh_event_port.h"
static mesh_model_evt_cb g_bt_mesh_model_evt_cb = NULL;
int bt_mesh_event_register(mesh_model_evt_cb event_cb)
{
if (event_cb == NULL) {
return -1;
}
g_bt_mesh_model_evt_cb = event_cb;
return 0;
}
mesh_model_evt_cb bt_mesh_event_get_cb_func(void)
{
return g_bt_mesh_model_evt_cb;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/ref_impl/mesh_event_port.c | C | apache-2.0 | 657 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <ble_os.h>
#include "mesh_hal_ble.h"
#include <bt_errno.h>
#include <aos/kernel.h>
#ifndef CONFIG_MESH_STACK_ALONE
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include <bluetooth/bluetooth.h>
#include "provisioner_prov.h"
int bt_mesh_adv_start(const struct bt_le_adv_param *param,
const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len)
{
return bt_le_adv_start((const struct bt_le_adv_param *)param,
(const struct bt_data *)ad, ad_len,
(const struct bt_data *)sd, sd_len);
}
int bt_mesh_adv_stop(void)
{
return bt_le_adv_stop();
}
int bt_mesh_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb)
{
return bt_le_scan_start((const struct bt_le_scan_param *)param, cb);
}
int bt_mesh_scan_stop(void)
{
return bt_le_scan_stop();
}
struct bt_conn_cb conn_callbacks;
void bt_mesh_conn_cb_register(struct bt_conn_cb *cb)
{
conn_callbacks.connected = cb->connected;
conn_callbacks.disconnected = cb->disconnected;
bt_conn_cb_register(&conn_callbacks);
}
struct bt_conn * bt_mesh_conn_ref(struct bt_conn * conn)
{
return bt_conn_ref((struct bt_conn *)conn);
}
void bt_mesh_conn_unref(struct bt_conn * conn)
{
bt_conn_unref((struct bt_conn *)conn);
}
int bt_mesh_conn_disconnect(struct bt_conn * conn, uint8_t reason)
{
return bt_conn_disconnect((struct bt_conn *)conn, reason);
}
#define SVC_ENTRY_MAX 16
struct svc_paire_node {
struct bt_gatt_service *msvc;
struct bt_gatt_service svc;
} _svc_paire[SVC_ENTRY_MAX] = {{0}};
/* TODO: manage the services in linked list. */
int bt_mesh_gatt_service_register(struct bt_gatt_service *svc)
{
struct svc_paire_node *node = &_svc_paire[0];
int i = 0;
while (i < SVC_ENTRY_MAX) {
if (node->msvc != NULL) {
node++;
i++;
} else {
break;
}
}
if (i >= SVC_ENTRY_MAX) {
printf("Error: no space left for service register.");
return -1;
}
node->msvc = svc;
node->svc.attrs = (struct bt_gatt_attr *)svc->attrs;
node->svc.attr_count = svc->attr_count;
return bt_gatt_service_register(&(node->svc));
}
int bt_mesh_gatt_service_unregister(struct bt_gatt_service *svc)
{
struct svc_paire_node *node = &_svc_paire[0];
int ret, i = 0;
while (i < SVC_ENTRY_MAX) {
if (node->msvc != svc) {
node++;
i++;
} else {
break;
}
}
if (i >= SVC_ENTRY_MAX) {
return 0;
}
ret = bt_gatt_service_unregister(&(node->svc));
return ret;
}
int bt_mesh_gatt_notify(struct bt_conn * conn, const struct bt_gatt_attr *attr,
const void *data, uint16_t len)
{
return bt_gatt_notify((struct bt_conn *)conn, (const struct bt_gatt_attr *)attr, data, len);
}
int bt_mesh_gatt_attr_read(struct bt_conn * conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t buf_len, uint16_t offset,
const void *value, uint16_t value_len)
{
return bt_gatt_attr_read((struct bt_conn *)conn, (const struct bt_gatt_attr *)attr, buf, buf_len, offset, value, value_len);
}
uint16_t bt_mesh_gatt_get_mtu(struct bt_conn * conn)
{
return bt_gatt_get_mtu((struct bt_conn *)conn);
}
int bt_mesh_gatt_attr_read_service(struct bt_conn * conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
return bt_gatt_attr_read_service((struct bt_conn *)conn, (const struct bt_gatt_attr *)attr, buf, len, offset);
}
int bt_mesh_gatt_attr_read_chrc(struct bt_conn * conn,
const struct bt_gatt_attr *attr, void *buf,
uint16_t len, uint16_t offset)
{
return bt_gatt_attr_read_chrc((struct bt_conn *)conn, (const struct bt_gatt_attr *)attr, buf, len, offset);
}
#ifdef CONFIG_BT_MESH_PROVISIONER
typedef void (*gatt_open_complete_cb)(struct bt_conn *conn);
#define BT_MESH_GATTC_APP_UUID_BYTE 0x97
struct gattc_prov_info {
/* Service to be found depends on the type of adv pkt received */
u16_t srvc_uuid;
u8_t addr[6];
u8_t addr_type;
struct bt_conn *conn;
u16_t mtu;
bool wr_desc_done; /* Indicate if write char descriptor event is received */
u16_t start_handle; /* Service attribute start handle */
u16_t end_handle; /* Service attribute end handle */
u16_t data_in_handle; /* Data In Characteristic attribute handle */
u16_t data_out_handle; /* Data Out Characteristic attribute handle */
u16_t ccc_handle; /* Data Out Characteristic CCC attribute handle */
} gattc_info[CONFIG_BT_MESH_PBG_SAME_TIME];
static struct bt_conn *gatt_conn;
static struct bt_gatt_exchange_params mtu_param;
static struct bt_gatt_discover_params discov_param;
static struct bt_gatt_subscribe_params subscribe_param;
static gatt_open_complete_cb bt_mesh_gatt_open_complete;
static gatt_recv_cb bt_mesh_gatt_recv;
static struct bt_uuid_16 prov_primary_uuid = BT_UUID_INIT_16(0x1827);
static struct bt_uuid_16 prov_character_data_in_uuid = BT_UUID_INIT_16(0x2adb);
static struct bt_uuid_16 prov_descriptor_data_in_uuid = BT_UUID_INIT_16(0x2adb);
static struct bt_uuid_16 prov_character_data_out_uuid = BT_UUID_INIT_16(0x2adc);
//static struct bt_uuid_16 prov_descriptor_data_out_uuid = BT_UUID_INIT_16(0x2adc);
static struct bt_uuid_16 prov_descriptor_ccc_uuid = BT_UUID_INIT_16(0x2902);
static struct bt_uuid_16 proxy_primary_uuid = BT_UUID_INIT_16(0x1828);
static struct bt_uuid_16 proxy_character_data_in_uuid = BT_UUID_INIT_16(0x2add);
static struct bt_uuid_16 proxy_descriptor_data_in_uuid = BT_UUID_INIT_16(0x2add);
static struct bt_uuid_16 proxy_character_data_out_uuid = BT_UUID_INIT_16(0x2ade);
//static struct bt_uuid_16 proxy_descriptor_data_out_uuid = BT_UUID_INIT_16(0x2ade);
static struct bt_uuid_16 proxy_descriptor_ccc_uuid = BT_UUID_INIT_16(0x2902);
int bt_prov_get_gattc_id(u8_t *addr)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (!memcmp(addr, gattc_info[i].addr, 6)) {
return i;
}
}
return -1;
}
bool bt_prov_check_gattc_id(int id, const bt_addr_le_t *addr)
{
u8_t zero[6] = {0};
if (!addr || !memcmp(addr->a.val, zero, 6) || (addr->type > BT_ADDR_LE_RANDOM)) {
//BT_ERR("%s: invalid parameters", __func__);
return false;
}
memcpy(gattc_info[id].addr, addr->a.val, 6);
gattc_info[id].addr_type = addr->type;
return true;
}
void set_my_addr(u8_t index, const u8_t *addr, u8_t type)
{
gattc_info[index].addr_type = type;
memcpy(gattc_info[index].addr, addr, 6);
}
int bt_gattc_conn_create(int id, u16_t srvc_uuid)
{
int err;
bt_addr_le_t peer;
struct bt_le_conn_param conn_param;
struct bt_conn *conn;
/** Min_interval: 250ms
* Max_interval: 250ms
* Slave_latency: 0x0
* Supervision_timeout: 32sec
*/
conn_param.interval_min = 0xC8;
conn_param.interval_max = 0xC8;
conn_param.latency = 0x00;
conn_param.timeout = 0xC80;
peer.type = gattc_info[id].addr_type;
memcpy(peer.a.val, gattc_info[id].addr, 6);
//BT_DBG("type:%u addr: %02x, %02x\r\n", peer.type, peer.a.val[0], peer.a.val[1]);
extern int bt_mesh_scan_disable(void);
err = bt_mesh_scan_disable();
if (err && err != -EALREADY)
{
return err;
}
//add relay to ensure the scan has been disabled
aos_msleep(10);
conn = bt_conn_create_le(&peer, &conn_param);
if (conn == NULL) {
return -EIO;
}
else
{
bt_conn_unref(conn);
}
gattc_info[id].conn = conn;
/* Increment pbg_count */
provisioner_pbg_count_inc();
/* Service to be found after exhanging mtu size */
gattc_info[id].srvc_uuid = srvc_uuid;
gatt_conn = conn;
return 0;
}
struct bt_conn * bt_mesh_get_curr_conn(void)
{
return gatt_conn;
}
u16_t bt_mesh_get_srvc_uuid(struct bt_conn *conn)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
break;
}
}
if (i == CONFIG_BT_MESH_PBG_SAME_TIME) {
return 0;
}
return gattc_info[i].srvc_uuid;
}
void bt_gatt_prov_set_mtu(struct bt_conn *conn, u16_t mtu)
{
int i;
if (mtu > 40) {
mtu = 40;
}
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
gattc_info[i].mtu = mtu;
}
}
}
u16_t bt_gatt_prov_get_mtu(struct bt_conn *conn)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
return gattc_info[i].mtu;
}
}
return 0;
}
void bt_gatt_set_data_in_handle(struct bt_conn *conn, u16_t handle)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
gattc_info[i].data_in_handle = handle;
break;
}
}
}
u16_t bt_gatt_get_data_in_handle(struct bt_conn *conn)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
return gattc_info[i].data_in_handle;
}
}
return 0;
}
void bt_gatt_set_data_out_handle(struct bt_conn *conn, u16_t handle)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
gattc_info[i].data_out_handle = handle;
break;
}
}
}
u16_t bt_gatt_get_data_out_handle(struct bt_conn *conn)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
return gattc_info[i].data_out_handle;
}
}
return 0;
}
void bt_gatt_set_ccc_handle(struct bt_conn *conn, u16_t handle)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
gattc_info[i].ccc_handle = handle;
}
}
}
u16_t bt_gatt_get_ccc_handle(struct bt_conn *conn)
{
int i;
for (i = 0; i < CONFIG_BT_MESH_PBG_SAME_TIME; i++) {
if (conn == gattc_info[i].conn) {
return gattc_info[i].ccc_handle;
}
}
return 0;
}
static u8_t proxy_prov_notify_func(struct bt_conn *conn,
struct bt_gatt_subscribe_params *param,
const void *buf, u16_t len)
{
if (bt_mesh_gatt_recv) {
bt_mesh_gatt_recv(conn, NULL, buf, len, 0, 0);
}
return BT_GATT_ITER_CONTINUE;
}
static u8_t proxy_prov_discover_func(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
struct bt_gatt_discover_params *params)
{
if (params->uuid == &prov_primary_uuid.uuid) {
discov_param.uuid = &prov_character_data_in_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_CHARACTERISTIC;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &prov_character_data_in_uuid.uuid) {
discov_param.uuid = &prov_descriptor_data_in_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_DESCRIPTOR;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &prov_descriptor_data_in_uuid.uuid) {
discov_param.uuid = &prov_character_data_out_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_CHARACTERISTIC;
bt_gatt_set_data_in_handle(conn, attr->handle);
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &prov_character_data_out_uuid.uuid) {
discov_param.uuid = &prov_descriptor_ccc_uuid.uuid;
discov_param.start_handle = attr->handle + 2;
discov_param.type = BT_GATT_DISCOVER_DESCRIPTOR;
subscribe_param.value_handle = attr->handle + 1;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &prov_descriptor_ccc_uuid.uuid) {
bt_gatt_set_ccc_handle(conn, attr->handle);
int err;
subscribe_param.notify = proxy_prov_notify_func;
subscribe_param.value = BT_GATT_CCC_NOTIFY;
subscribe_param.ccc_handle = attr->handle;
bt_gatt_set_ccc_handle(conn, attr->handle);
err = bt_gatt_subscribe(conn, &subscribe_param);
if (err) {
printf("Subscribe failed (err %d)\r\n", err);
return 0;
}
u16_t open_data = 0x0001;
bt_gatt_write_without_response(conn, bt_gatt_get_ccc_handle(conn), &open_data, 2, false);
if (bt_mesh_gatt_open_complete) {
bt_mesh_gatt_open_complete(conn);
}
}
return 0;
}
static u8_t proxy_discover_func(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
struct bt_gatt_discover_params *params)
{
if (params->uuid == &proxy_primary_uuid.uuid) {
discov_param.uuid = &proxy_character_data_in_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_CHARACTERISTIC;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &proxy_character_data_in_uuid.uuid) {
discov_param.uuid = &proxy_descriptor_data_in_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_DESCRIPTOR;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &proxy_descriptor_data_in_uuid.uuid) {
discov_param.uuid = &proxy_character_data_out_uuid.uuid;
discov_param.start_handle = attr->handle + 1;
discov_param.type = BT_GATT_DISCOVER_CHARACTERISTIC;
bt_gatt_set_data_in_handle(conn, attr->handle);
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &proxy_character_data_out_uuid.uuid) {
discov_param.uuid = &proxy_descriptor_ccc_uuid.uuid;
discov_param.start_handle = attr->handle + 2;
discov_param.type = BT_GATT_DISCOVER_DESCRIPTOR;
subscribe_param.value_handle = attr->handle + 1;
bt_gatt_discover(conn, &discov_param);
} else if (params->uuid == &proxy_descriptor_ccc_uuid.uuid) {
bt_gatt_set_ccc_handle(conn, attr->handle);
int err;
subscribe_param.notify = proxy_prov_notify_func;
subscribe_param.value = BT_GATT_CCC_NOTIFY;
subscribe_param.ccc_handle = attr->handle;
bt_gatt_set_ccc_handle(conn, attr->handle);
err = bt_gatt_subscribe(conn, &subscribe_param);
if (err) {
printf("Subscribe failed (err %d)\r\n", err);
return 0;
}
if (bt_mesh_gatt_open_complete) {
bt_mesh_gatt_open_complete(conn);
}
}
return 0;
}
static void proxy_prov_get_mtu_response(struct bt_conn *conn, u8_t err,
struct bt_gatt_exchange_params *params)
{
u16_t mtu;
//u8_t i;
if (err) {
//printf("%s mtu response failed (err %u)\n", __func__, err);
} else {
mtu = bt_gatt_get_mtu(conn);
bt_gatt_prov_set_mtu(conn, mtu);
if (bt_mesh_get_srvc_uuid(conn) == BT_UUID_MESH_PROXY_VAL) {
discov_param.uuid = &proxy_primary_uuid.uuid;
discov_param.func = proxy_discover_func;
} else if (bt_mesh_get_srvc_uuid(conn) == BT_UUID_MESH_PROV_VAL) {
discov_param.uuid = &prov_primary_uuid.uuid;
discov_param.func = proxy_prov_discover_func;
}
discov_param.start_handle = 0x0001;
discov_param.end_handle = 0xffff;
discov_param.type = BT_GATT_DISCOVER_PRIMARY;
bt_gatt_discover(conn, &discov_param);
}
}
void bt_mesh_gatt_conn_open(struct bt_conn *conn, void (*open_complete)(struct bt_conn *conn))
{
mtu_param.func = proxy_prov_get_mtu_response;
bt_mesh_gatt_open_complete = open_complete;
bt_gatt_exchange_mtu(conn, &mtu_param);
return;
}
void bt_mesh_gatt_recv_callback(gatt_recv_cb recv_callback)
{
bt_mesh_gatt_recv = recv_callback;
return;
}
#endif
#else
void bt_mesh_conn_cb_register(struct bt_mesh_conn_cb *cb)
{
return;
}
struct bt_conn * bt_mesh_conn_ref(struct bt_conn * conn)
{
return conn;
}
void bt_mesh_conn_unref(struct bt_conn * conn)
{
return;
}
int bt_mesh_conn_disconnect(struct bt_conn * conn, uint8_t reason)
{
return 0;
}
int bt_gatt_service_register(struct bt_gatt_service *svc)
{
return 0;
}
int bt_gatt_service_unregister(struct bt_gatt_service *svc)
{
return 0;
}
int bt_mesh_gatt_notify(struct bt_conn * conn, const struct bt_gatt_attr *attr,
const void *data, uint16_t len)
{
return 0;
}
int bt_mesh_gatt_attr_read(struct bt_conn * conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t buf_len, uint16_t offset,
const void *value, uint16_t value_len)
{
return 0;
}
uint16_t bt_mesh_gatt_get_mtu(struct bt_conn * conn)
{
return 0;
}
int bt_mesh_gatt_attr_read_service(struct bt_conn * conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
return 0;
}
int bt_mesh_gatt_attr_read_chrc(struct bt_conn * conn,
const struct bt_gatt_attr *attr, void *buf,
uint16_t len, uint16_t offset)
{
return 0;
}
int bt_mesh_adv_start(const struct bt_le_adv_param *param,
const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len)
{
return 0;
}
int bt_mesh_adv_stop(void)
{
return 0;
}
int bt_mesh_scan_start(const struct bt_le_scan_param *param, bt_mesh_le_scan_cb_t cb)
{
return 0;
}
int bt_mesh_scan_stop(void)
{
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/ref_impl/mesh_hal_ble.c | C | apache-2.0 | 18,139 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <bt_errno.h>
#include <stddef.h>
#include <bluetooth/bluetooth.h>
#include <port/mesh_hal_sec.h>
#ifndef CONFIG_MESH_STACK_ALONE
#include <crypto.h>
#include <tinycrypt/constants.h>
#include <tinycrypt/utils.h>
#include <tinycrypt/aes.h>
#include <tinycrypt/cmac_mode.h>
#include <tinycrypt/ccm_mode.h>
int bt_mesh_rand(void *buf, size_t len)
{
return bt_rand(buf, len);
}
int bt_mesh_aes_encrypt(const uint8_t key[16], const uint8_t plaintext[16], uint8_t enc_data[16])
{
return bt_encrypt_be(key, plaintext, enc_data);
}
int bt_mesh_aes_decrypt(const uint8_t key[16], const uint8_t enc_data[16], uint8_t dec_data[16])
{
return bt_decrypt_be(key, enc_data, dec_data);
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/ref_impl/mesh_hal_sec.c | C | apache-2.0 | 769 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_ACCESS)
#include "common/log.h"
#include "mesh.h"
#include "adv.h"
#include "net.h"
#include "lpn.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "provisioner_proxy.h"
#endif
#define MESH_TX_TAG "\t[TX]"
#define MESH_RX_TAG "\t[RX]"
#define MESH_TX_D(f, ...) LOGI(MESH_TX_TAG, "\033[0;34m " f "\033[0m", ##__VA_ARGS__)
#define MESH_RX_D(f, ...) LOGI(MESH_RX_TAG, "\033[0;32m " f "\033[0m", ##__VA_ARGS__)
static const struct bt_mesh_comp *dev_comp = NULL;
static u16_t dev_primary_addr;
static const struct {
const u16_t id;
int (*const init)(struct bt_mesh_model *model, bool primary);
} model_init[] = {
{ BT_MESH_MODEL_ID_CFG_SRV, bt_mesh_cfg_srv_init },
{ BT_MESH_MODEL_ID_HEALTH_SRV, bt_mesh_health_srv_init },
#if defined(CONFIG_BT_MESH_CFG_CLI)
{ BT_MESH_MODEL_ID_CFG_CLI, bt_mesh_cfg_cli_init },
#endif
#if defined(CONFIG_BT_MESH_HEALTH_CLI)
{ BT_MESH_MODEL_ID_HEALTH_CLI, bt_mesh_health_cli_init },
#endif
};
void bt_mesh_model_foreach(void (*func)(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary,
void *user_data),
void *user_data)
{
int i, j;
for (i = 0; i < dev_comp->elem_count; i++) {
struct bt_mesh_elem *elem = &dev_comp->elem[i];
for (j = 0; j < elem->model_count; j++) {
struct bt_mesh_model *model = &elem->models[j];
func(model, elem, false, i == 0, user_data);
}
for (j = 0; j < elem->vnd_model_count; j++) {
struct bt_mesh_model *model = &elem->vnd_models[j];
func(model, elem, true, i == 0, user_data);
}
}
}
bt_s32_t bt_mesh_model_pub_period_get(struct bt_mesh_model *mod)
{
int period;
if (!mod->pub) {
return 0;
}
switch (mod->pub->period >> 6) {
case 0x00:
/* 1 step is 100 ms */
period = K_MSEC((mod->pub->period & BIT_MASK(6)) * 100);
break;
case 0x01:
/* 1 step is 1 second */
period = K_SECONDS(mod->pub->period & BIT_MASK(6));
break;
case 0x02:
/* 1 step is 10 seconds */
period = K_SECONDS((mod->pub->period & BIT_MASK(6)) * 10);
break;
case 0x03:
/* 1 step is 10 minutes */
period = K_MINUTES((mod->pub->period & BIT_MASK(6)) * 10);
break;
default:
// CODE_UNREACHABLE;
while (1)
;
}
if (mod->pub->fast_period) {
return period >> mod->pub->period_div;
} else {
return period;
}
}
static bt_s32_t next_period(struct bt_mesh_model *mod)
{
struct bt_mesh_model_pub *pub = mod->pub;
bt_u32_t elapsed, period;
period = bt_mesh_model_pub_period_get(mod);
if (!period) {
return 0;
}
elapsed = k_uptime_get_32() - pub->period_start;
BT_DBG("Publishing took %ums", elapsed);
if (elapsed > period) {
BT_WARN("Publication sending took longer than the period");
/* Return smallest positive number since 0 means disabled */
return K_MSEC(1);
}
return period - elapsed;
}
static void publish_sent(int err, void *user_data)
{
struct bt_mesh_model *mod = user_data;
bt_s32_t delay;
BT_DBG("err %d", err);
if (mod->pub->count) {
delay = BT_MESH_PUB_TRANSMIT_INT(mod->pub->retransmit);
} else {
delay = next_period(mod);
}
if (delay) {
BT_DBG("Publishing next time in %dms", delay);
k_delayed_work_submit(&mod->pub->timer, delay);
}
}
static const struct bt_mesh_send_cb pub_sent_cb = {
.end = publish_sent,
};
static int publish_retransmit(struct bt_mesh_model *mod)
{
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
struct bt_mesh_model_pub *pub = mod->pub;
struct bt_mesh_app_key *key;
struct bt_mesh_msg_ctx ctx = {
.addr = pub->addr,
.send_ttl = pub->ttl,
};
int err;
struct bt_mesh_net_tx tx = {
.ctx = &ctx,
.src = bt_mesh_model_elem(mod)->addr,
.xmit = bt_mesh_net_transmit_get(),
.friend_cred = pub->cred,
};
key = bt_mesh_app_key_find(pub->key);
if (!key) {
return -EADDRNOTAVAIL;
}
tx.sub = bt_mesh_subnet_get(key->net_idx);
if (!tx.sub) {
BT_ERR("No available subnet found");
return -EINVAL;
}
ctx.net_idx = key->net_idx;
ctx.app_idx = key->app_idx;
net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len);
err = bt_mesh_trans_send(&tx, &sdu, &pub_sent_cb, mod);
pub->count--;
return err;
}
static void mod_publish(struct k_work *work)
{
struct bt_mesh_model_pub *pub = CONTAINER_OF(work, struct bt_mesh_model_pub, timer.work);
bt_s32_t period_ms;
int err;
uint8_t pub_count = BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit);
BT_DBG("");
period_ms = bt_mesh_model_pub_period_get(pub->mod);
if (!period_ms) {
return;
}
BT_DBG("period %u ms", period_ms);
__ASSERT_NO_MSG(pub->update != NULL);
if (pub->count) {
if (pub->count == pub_count) {
pub->period_start = k_uptime_get_32();
err = pub->update(pub->mod);
if (err) {
BT_ERR("Failed to update publication message");
return;
}
}
err = publish_retransmit(pub->mod);
if (err) {
BT_ERR("Failed to retransmit (err %d)", err);
pub->count = pub_count;
/* Continue with normal publication */
if (period_ms) {
k_delayed_work_submit(&pub->timer, period_ms);
}
}
return;
}
if (pub_count == 0) {
pub->period_start = k_uptime_get_32();
err = pub->update(pub->mod);
if (err) {
BT_ERR("Failed to update publication message");
return;
}
}
err = bt_mesh_model_publish(pub->mod);
if (err) {
BT_ERR("Publishing failed (err %d)", err);
}
}
struct bt_mesh_elem *bt_mesh_model_elem(struct bt_mesh_model *mod)
{
if (mod == NULL || dev_comp == NULL || mod->elem_idx >= dev_comp->elem_count) {
return NULL;
}
return &dev_comp->elem[mod->elem_idx];
}
struct bt_mesh_model *bt_mesh_model_get(bool vnd, u8_t elem_idx, u8_t mod_idx)
{
struct bt_mesh_elem *elem;
if (dev_comp == NULL || elem_idx >= dev_comp->elem_count) {
BT_ERR("Invalid element index %u", elem_idx);
return NULL;
}
elem = &dev_comp->elem[elem_idx];
if (vnd) {
if (mod_idx >= elem->vnd_model_count) {
BT_ERR("Invalid vendor model index %u", mod_idx);
return NULL;
}
return &elem->vnd_models[mod_idx];
} else {
if (mod_idx >= elem->model_count) {
BT_ERR("Invalid SIG model index %u", mod_idx);
return NULL;
}
return &elem->models[mod_idx];
}
}
static void mod_init(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
int i;
if (mod->pub) {
mod->pub->mod = mod;
k_delayed_work_init(&mod->pub->timer, mod_publish);
}
for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
mod->keys[i] = BT_MESH_KEY_UNUSED;
}
mod->elem_idx = elem - dev_comp->elem;
if (vnd) {
mod->mod_idx = mod - elem->vnd_models;
} else {
mod->mod_idx = mod - elem->models;
}
if (vnd) {
return;
}
for (i = 0; i < ARRAY_SIZE(model_init); i++) {
if (model_init[i].id == mod->id) {
model_init[i].init(mod, primary);
}
}
}
int bt_mesh_comp_register(const struct bt_mesh_comp *comp)
{
/* There must be at least one element */
if (!comp->elem_count) {
return -EINVAL;
}
dev_comp = comp;
bt_mesh_model_foreach(mod_init, NULL);
return 0;
}
void bt_mesh_comp_provision(u16_t addr)
{
int i;
if (dev_comp == NULL) {
BT_ERR("dev_comp is NULL");
return;
}
dev_primary_addr = addr;
BT_DBG("addr 0x%04x elem_count %zu", addr, dev_comp->elem_count);
for (i = 0; i < dev_comp->elem_count; i++) {
struct bt_mesh_elem *elem = &dev_comp->elem[i];
elem->addr = addr++;
BT_DBG("addr 0x%04x mod_count %u vnd_mod_count %u", elem->addr, elem->model_count, elem->vnd_model_count);
}
}
void bt_mesh_comp_unprovision(void)
{
BT_DBG("");
dev_primary_addr = BT_MESH_ADDR_UNASSIGNED;
bt_mesh_model_foreach(mod_init, NULL);
}
u16_t bt_mesh_primary_addr(void)
{
return dev_primary_addr;
}
u16_t *bt_mesh_model_find_group(struct bt_mesh_model *mod, u16_t addr)
{
int i;
struct bt_mesh_elem *elem = NULL;
for (i = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] == addr) {
BT_INFO("model group match");
return &mod->groups[i];
}
}
/*[Genie begin] add by lgy at 2021-02-09*/
elem = bt_mesh_model_elem(mod);
if (elem && addr == elem->grop_addr) {
BT_INFO("elem group match");
return &elem->grop_addr;
}
for (i = 0; i < CONFIG_BT_MESH_MODEL_GROUP_COUNT; i++) {
if (g_sub_list[i] == addr) {
BT_INFO("global group match");
return &g_sub_list[i];
}
}
// BT_WARN("addr:0x%04x no match", addr);
/*[Genie begin] add by lgy at 2021-02-09*/
return NULL;
}
static struct bt_mesh_model *bt_mesh_elem_find_group(struct bt_mesh_elem *elem, u16_t group_addr)
{
struct bt_mesh_model *model;
u16_t *match;
int i;
for (i = 0; i < elem->model_count; i++) {
model = &elem->models[i];
match = bt_mesh_model_find_group(model, group_addr);
if (match) {
return model;
}
}
for (i = 0; i < elem->vnd_model_count; i++) {
model = &elem->vnd_models[i];
match = bt_mesh_model_find_group(model, group_addr);
if (match) {
return model;
}
}
return NULL;
}
struct bt_mesh_elem *bt_mesh_elem_find(u16_t addr)
{
int i;
for (i = 0; i < dev_comp->elem_count; i++) {
struct bt_mesh_elem *elem = &dev_comp->elem[i];
if (BT_MESH_ADDR_IS_GROUP(addr) || BT_MESH_ADDR_IS_VIRTUAL(addr)) {
if (bt_mesh_elem_find_group(elem, addr)) {
return elem;
}
} else if (elem->addr == addr) {
return elem;
}
}
return NULL;
}
struct bt_mesh_elem *bt_mesh_elem_find_by_id(u8_t id)
{
if (id < dev_comp->elem_count) {
return &dev_comp->elem[id];
}
return NULL;
}
u8_t bt_mesh_elem_count(void)
{
return dev_comp->elem_count;
}
static bool model_has_key(struct bt_mesh_model *mod, u16_t key)
{
int i;
for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
if (mod->keys[i] == key) {
return true;
}
}
return false;
}
static const struct bt_mesh_model_op *find_op(struct bt_mesh_model *models, u8_t model_count, u16_t dst, u16_t app_idx,
bt_u32_t opcode, struct bt_mesh_model **model)
{
u8_t i;
for (i = 0; i < model_count; i++) {
const struct bt_mesh_model_op *op;
*model = &models[i];
if (BT_MESH_ADDR_IS_GROUP(dst) || BT_MESH_ADDR_IS_VIRTUAL(dst)) {
if (!bt_mesh_model_find_group(*model, dst)) {
continue;
}
}
if (!model_has_key(*model, app_idx)) {
continue;
}
for (op = (*model)->op; op->func; op++) {
if (op->opcode == opcode) {
return op;
}
}
}
*model = NULL;
return NULL;
}
static int get_opcode(struct net_buf_simple *buf, bt_u32_t *opcode)
{
switch (buf->data[0] >> 6) {
case 0x00:
case 0x01:
if (buf->data[0] == 0x7f) {
BT_ERR("Ignoring RFU OpCode");
return -EINVAL;
}
*opcode = net_buf_simple_pull_u8(buf);
return 0;
case 0x02:
if (buf->len < 2) {
BT_ERR("Too short payload for 2-octet OpCode");
return -EINVAL;
}
*opcode = net_buf_simple_pull_be16(buf);
return 0;
case 0x03:
if (buf->len < 3) {
BT_ERR("Too short payload for 3-octet OpCode");
return -EINVAL;
}
*opcode = net_buf_simple_pull_u8(buf) << 16;
*opcode |= net_buf_simple_pull_le16(buf);
return 0;
}
// CODE_UNREACHABLE;
while (1)
;
}
bool bt_mesh_fixed_group_match(u16_t addr)
{
/* Check for fixed group addresses */
switch (addr) {
case BT_MESH_ADDR_ALL_NODES:
#ifdef CONFIG_GENIE_MESH_ENABLE
/*[Genie begin] add by lgy at 2020-09-10*/
case BT_MESH_ADDR_GENIE_ALL_NODES:
/*[Genie end] add by lgy at 2020-09-10*/
#endif
return true;
case BT_MESH_ADDR_PROXIES:
/* TODO: Proxy not yet supported */
return false;
case BT_MESH_ADDR_FRIENDS:
return (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED);
case BT_MESH_ADDR_RELAYS:
return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED);
default:
return false;
}
}
void bt_mesh_model_recv(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_model *models = NULL, *model = NULL;
const struct bt_mesh_model_op *op;
bt_u32_t opcode;
u8_t count;
int i;
BT_DBG("app_idx 0x%04x src 0x%04x dst 0x%04x", rx->ctx.app_idx, rx->ctx.addr, rx->ctx.recv_dst);
BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
if (get_opcode(buf, &opcode) < 0) {
BT_WARN("Unable to decode OpCode");
return;
}
BT_DBG("OpCode 0x%08x", opcode);
#ifdef MESH_DEBUG_RX
MESH_RX_D("RSSI: %d\n", rx->rssi);
MESH_RX_D("TTL: %d\n", rx->ctx.recv_ttl);
MESH_RX_D("SRC: 0x%02X\n", rx->ctx.addr);
MESH_RX_D("DST: 0x%02X\n", rx->ctx.recv_dst);
MESH_RX_D("OPCODE: 0x%04X\n", opcode);
MESH_RX_D("Payload size: %d\n", buf->len);
MESH_RX_D("%s\n", bt_hex_real(buf->data, buf->len));
#endif
for (i = 0; i < dev_comp->elem_count; i++) {
struct bt_mesh_elem *elem = &dev_comp->elem[i];
if (BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) {
if (elem->addr != rx->ctx.recv_dst) {
continue;
}
} else if (BT_MESH_ADDR_IS_GROUP(rx->ctx.recv_dst) || BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) {
/* find_op() will do proper model/group matching */
} else if (i != 0 || !bt_mesh_fixed_group_match(rx->ctx.recv_dst)) {
continue;
}
/* SIG models cannot contain 3-byte (vendor) OpCodes, and
* vendor models cannot contain SIG (1- or 2-byte) OpCodes, so
* we only need to do the lookup in one of the model lists.
*/
if (opcode < 0x10000) {
models = elem->models;
count = elem->model_count;
} else {
models = elem->vnd_models;
count = elem->vnd_model_count;
}
op = find_op(models, count, rx->ctx.recv_dst, rx->ctx.app_idx, opcode, &model);
if (op) {
struct net_buf_simple_state state;
if (buf->len < op->min_len) {
BT_ERR("Too short message for OpCode 0x%08x", opcode);
continue;
}
/* The callback will likely parse the buffer, so
* store the parsing state in case multiple models
* receive the message.
*/
net_buf_simple_save(buf, &state);
if (op->func2) {
op->func2(model, &rx->ctx, buf, opcode);
} else {
op->func(model, &rx->ctx, buf);
}
net_buf_simple_restore(buf, &state);
} else {
BT_DBG("No OpCode 0x%08x for elem %d", opcode, i);
}
}
}
void bt_mesh_model_msg_init(struct net_buf_simple *msg, bt_u32_t opcode)
{
net_buf_simple_init(msg, 0);
if (opcode < 0x100) {
/* 1-byte OpCode */
net_buf_simple_add_u8(msg, opcode);
return;
}
if (opcode < 0x10000) {
/* 2-byte OpCode */
net_buf_simple_add_be16(msg, opcode);
return;
}
/* 3-byte OpCode */
net_buf_simple_add_u8(msg, ((opcode >> 16) & 0xff));
net_buf_simple_add_le16(msg, opcode & 0xffff);
}
static int model_send(struct bt_mesh_model *model, struct bt_mesh_net_tx *tx, bool implicit_bind,
struct net_buf_simple *msg, const struct bt_mesh_send_cb *cb, void *cb_data)
{
if (model == NULL || tx == NULL || msg == NULL) {
return -EINVAL;
}
BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->ctx->net_idx, tx->ctx->app_idx, tx->ctx->addr);
BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
if (!bt_mesh_is_provisioned()) {
BT_ERR("Local node is not yet provisioned");
return -EAGAIN;
}
if (net_buf_simple_tailroom(msg) < 4) {
BT_ERR("Not enough tailroom for TransMIC");
return -EINVAL;
}
if (msg->len > BT_MESH_TX_SDU_MAX - 4) {
BT_ERR("Too big message");
return -EMSGSIZE;
}
if (!implicit_bind && !model_has_key(model, tx->ctx->app_idx)) {
BT_ERR("Model not bound to AppKey 0x%04x", tx->ctx->app_idx);
return -EINVAL;
}
#ifdef MESH_DEBUG_TX
MESH_TX_D("TTL: %d\n", tx->ctx->send_ttl);
MESH_TX_D("SRC: 0x%02X\n", bt_mesh_model_elem(model)->addr);
MESH_TX_D("DST: 0x%02X\n", tx->ctx->addr);
MESH_TX_D("msg size: %d\n", msg->len);
MESH_TX_D("%s\n", bt_hex_real(msg->data, msg->len));
#endif
return bt_mesh_trans_send(tx, msg, cb, cb_data);
}
int bt_mesh_model_send(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *msg,
const struct bt_mesh_send_cb *cb, void *cb_data)
{
if (model == NULL || ctx == NULL || msg == NULL) {
return -EINVAL;
}
struct bt_mesh_net_tx tx = {
.sub = bt_mesh_subnet_get(ctx->net_idx),
.ctx = ctx,
.src = bt_mesh_model_elem(model)->addr,
.xmit = bt_mesh_net_transmit_get(),
.friend_cred = 0,
};
if (!tx.sub) {
BT_ERR("No available subnet found");
return -EINVAL;
}
return model_send(model, &tx, false, msg, cb, cb_data);
}
int bt_mesh_model_publish(struct bt_mesh_model *model)
{
if (NULL == model) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
struct bt_mesh_model_pub *pub = model->pub;
struct bt_mesh_app_key *key;
struct bt_mesh_msg_ctx ctx = {};
struct bt_mesh_net_tx tx = {
.ctx = &ctx,
.src = bt_mesh_model_elem(model)->addr,
.xmit = bt_mesh_net_transmit_get(),
};
int err;
BT_DBG("");
if (!pub) {
return -ENOTSUP;
}
if (pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return -EADDRNOTAVAIL;
}
#ifdef CONFIG_BT_MESH_PROVISIONER
key = provisioner_app_key_find(pub->key);
#else
key = bt_mesh_app_key_find(pub->key);
#endif
if (!key) {
return -EADDRNOTAVAIL;
}
if (pub->msg->len + 4 > BT_MESH_TX_SDU_MAX) {
BT_ERR("Message does not fit maximum SDU size");
return -EMSGSIZE;
}
if (pub->count) {
BT_WARN("Clearing publish retransmit timer");
k_delayed_work_cancel(&pub->timer);
}
net_buf_simple_add_mem(&sdu, pub->msg->data, pub->msg->len);
ctx.addr = pub->addr;
ctx.send_ttl = pub->ttl;
ctx.net_idx = key->net_idx;
ctx.app_idx = key->app_idx;
tx.friend_cred = pub->cred;
tx.sub = bt_mesh_subnet_get(ctx.net_idx);
if (!tx.sub) {
BT_ERR("No available subnet found");
return -EINVAL;
}
BT_DBG("Publish Retransmit Count %u Interval %ums", pub->count, BT_MESH_PUB_TRANSMIT_INT(pub->retransmit));
err = model_send(model, &tx, true, &sdu, &pub_sent_cb, model);
if (err) {
/* Don't try retransmissions for this publish attempt */
pub->count = 0U;
/* Make sure the publish timer gets reset */
publish_sent(err, model);
return err;
}
pub->count = BT_MESH_PUB_TRANSMIT_COUNT(pub->retransmit);
return 0;
}
struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem *elem, u16_t company, u16_t id)
{
u8_t i;
for (i = 0; i < elem->vnd_model_count; i++) {
if (elem->vnd_models[i].vnd.company == company && elem->vnd_models[i].vnd.id == id) {
return &elem->vnd_models[i];
}
}
return NULL;
}
struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem *elem, u16_t id)
{
u8_t i;
for (i = 0; i < elem->model_count; i++) {
if (elem->models[i].id == id) {
return &elem->models[i];
}
}
return NULL;
}
const struct bt_mesh_comp *bt_mesh_comp_get(void)
{
return dev_comp;
}
u16_t bt_mesh_model_get_netkey_id(struct bt_mesh_elem *elem)
{
return 0;
}
u16_t bt_mesh_model_get_appkey_id(struct bt_mesh_elem *elem, struct bt_mesh_model *p_model)
{
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/access.c | C | apache-2.0 | 21,582 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2018 Nordic Semiconductor ASA
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <misc/stack.h>
#include <misc/util.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_ADV)
#include "common/log.h"
// #include "host/hci_core.h"
#include "adv.h"
#include "net.h"
#include "foundation.h"
#include "beacon.h"
#include "prov.h"
#include "proxy.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_main.h"
#include "provisioner_prov.h"
#include "provisioner_beacon.h"
#endif
#ifdef GENIE_ULTRA_PROV
#include "genie_storage.h"
#include "genie_provision.h"
#endif
/* Convert from ms to 0.625ms units */
#define ADV_SCAN_UNIT(_ms) ((_ms) * 8 / 5)
/* Window and Interval are equal for continuous scanning */
#ifndef CONFIG_MESH_SCAN_INTERVAL_MS
#define CONFIG_MESH_SCAN_INTERVAL_MS 30
#endif
#ifndef CONFIG_MESH_SCAN_WINDOW_MS
#define CONFIG_MESH_SCAN_WINDOW_MS 30
#endif
#define MESH_SCAN_INTERVAL ADV_SCAN_UNIT(CONFIG_MESH_SCAN_INTERVAL_MS)
#define MESH_SCAN_WINDOW ADV_SCAN_UNIT(CONFIG_MESH_SCAN_WINDOW_MS)
#ifndef CONFIG_ADV_SCAN_INTERVAL_TIMER
#define CONFIG_ADV_SCAN_INTERVAL_TIMER (1)
#endif
#ifndef CONFIG_ADV_INTERVAL_TIMER
#define CONFIG_ADV_INTERVAL_TIMER (20)
#endif
/* Pre-5.0 controllers enforce a minimum interval of 100ms
* whereas 5.0+ controllers can go down to 20ms.
*/
#define ADV_INT_DEFAULT_MS 100
#define ADV_INT_FAST_MS 20
#ifdef CONFIG_GENIE_MESH_ENABLE
#ifndef GENIE_DEFAULT_DURATION
#define GENIE_DEFAULT_DURATION 120
#endif
#endif
#ifndef CONFIG_BT_ADV_STACK_SIZE
#if defined(CONFIG_BT_HOST_CRYPTO)
#define ADV_STACK_SIZE 2048
#else
#define ADV_STACK_SIZE 1024
#endif
#else
#define ADV_STACK_SIZE CONFIG_BT_ADV_STACK_SIZE
#endif
// static K_FIFO_DEFINE(adv_queue);
static struct kfifo adv_queue;
static struct k_thread adv_thread_data;
static BT_STACK_NOINIT(adv_thread_stack, ADV_STACK_SIZE);
int bt_mesh_adv_scan_schd_init();
static const u8_t adv_type[] = {
[BT_MESH_ADV_PROV] = BT_DATA_MESH_PROV,
[BT_MESH_ADV_DATA] = BT_DATA_MESH_MESSAGE,
[BT_MESH_ADV_BEACON] = BT_DATA_MESH_BEACON,
[BT_MESH_ADV_URI] = BT_DATA_URI,
};
NET_BUF_POOL_DEFINE(adv_buf_pool, CONFIG_BT_MESH_ADV_BUF_COUNT, BT_MESH_ADV_DATA_SIZE, BT_MESH_ADV_USER_DATA_SIZE,
NULL);
static struct bt_mesh_adv adv_pool[CONFIG_BT_MESH_ADV_BUF_COUNT];
#ifdef CONFIG_BT_MESH_PROVISIONER
static const bt_addr_le_t *dev_addr;
#endif
static vendor_beacon_cb g_vendor_beacon_cb = NULL;
int bt_mesh_adv_scan_init(void);
static struct bt_mesh_adv *adv_alloc(int id)
{
return &adv_pool[id];
}
static inline void adv_send_start(u16_t duration, int err, const struct bt_mesh_send_cb *cb, void *cb_data)
{
if (cb && cb->start) {
cb->start(duration, err, cb_data);
}
}
static inline void adv_send_end(int err, const struct bt_mesh_send_cb *cb, void *cb_data)
{
if (cb && cb->end) {
cb->end(err, cb_data);
}
}
static inline void adv_send(struct net_buf *buf)
{
extern int bt_le_hci_version_get();
const bt_s32_t adv_int_min =
((bt_le_hci_version_get() >= BT_HCI_VERSION_5_0) ? ADV_INT_FAST_MS : ADV_INT_DEFAULT_MS);
const struct bt_mesh_send_cb *cb = BT_MESH_ADV(buf)->cb;
void *cb_data = BT_MESH_ADV(buf)->cb_data;
struct bt_le_adv_param param = { 0 };
u16_t duration, adv_int;
struct bt_data ad;
int err;
adv_int = MAX(adv_int_min, BT_MESH_TRANSMIT_INT(BT_MESH_ADV(buf)->xmit));
#ifdef CONFIG_GENIE_MESH_ENABLE
duration = GENIE_DEFAULT_DURATION;
#else
if (BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) == 0) {
duration = adv_int;
} else {
duration = (((BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1) * (adv_int)) + 10);
}
#endif
BT_DBG("type %u len %u: %s", BT_MESH_ADV(buf)->type, buf->len, bt_hex(buf->data, buf->len));
BT_DBG("count %u interval %ums duration %ums", BT_MESH_TRANSMIT_COUNT(BT_MESH_ADV(buf)->xmit) + 1, adv_int,
duration);
#ifdef GENIE_ULTRA_PROV
if (BT_MESH_ADV(buf)->tiny_adv == 1) {
ad.type = GENIE_PROV_ADV_TYPE;
} else {
ad.type = adv_type[BT_MESH_ADV(buf)->type];
}
#else
ad.type = adv_type[BT_MESH_ADV(buf)->type];
#endif
ad.data_len = buf->len;
ad.data = buf->data;
if (IS_ENABLED(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR)) {
param.options = BT_LE_ADV_OPT_USE_IDENTITY;
} else {
param.options = 0;
}
param.id = BT_ID_DEFAULT;
param.interval_min = ADV_SCAN_UNIT(adv_int);
param.interval_max = param.interval_min;
err = bt_mesh_adv_enable(¶m, &ad, 1, NULL, 0);
adv_send_start(duration, err, cb, cb_data);
if (err) {
net_buf_unref(buf);
BT_ERR("Advertising failed: err %d", err);
return;
}
BT_DBG("Advertising started. Sleeping %u ms", duration);
k_sleep(K_MSEC(duration));
err = bt_mesh_adv_disable();
net_buf_unref(buf);
adv_send_end(err, cb, cb_data);
if (err) {
net_buf_unref(buf);
BT_ERR("Stopping advertising failed: err %d", err);
return;
}
BT_DBG("Advertising stopped");
}
// static void adv_stack_dump(const struct k_thread *thread, void *user_data)
// {
// #if defined(CONFIG_THREAD_STACK_INFO)
// stack_analyze((char *)user_data, (char *)thread->stack_info.start,
// thread->stack_info.size);
// #endif
// }
static void adv_thread(void *args)
{
BT_DBG("started");
while (1) {
struct net_buf *buf;
if (IS_ENABLED(CONFIG_BT_MESH_PROXY)) {
buf = net_buf_get(&adv_queue, K_NO_WAIT);
while (!buf) {
bt_s32_t timeout;
timeout = bt_mesh_proxy_adv_start();
BT_DBG("Proxy Advertising up to %d ms", timeout);
buf = net_buf_get(&adv_queue, timeout);
bt_mesh_proxy_adv_stop();
}
} else {
buf = net_buf_get(&adv_queue, K_FOREVER);
}
if (!buf) {
continue;
}
/* busy == 0 means this was canceled */
if (BT_MESH_ADV(buf)->busy) {
adv_send(buf);
BT_MESH_ADV(buf)->busy = 0;
} else {
net_buf_unref(buf);
}
// STACK_ANALYZE("adv stack", adv_thread_stack);
// k_thread_foreach(adv_stack_dump, "BT_MESH");
/* Give other threads a chance to run */
k_yield();
}
}
void bt_mesh_adv_update(void)
{
BT_DBG("");
k_fifo_cancel_wait(&adv_queue);
}
struct net_buf *bt_mesh_adv_create_from_pool(struct net_buf_pool *pool, bt_mesh_adv_alloc_t get_id,
enum bt_mesh_adv_type type, u8_t xmit, bt_s32_t timeout)
{
struct bt_mesh_adv *adv;
struct net_buf *buf;
if (atomic_test_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) {
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_GENIE_MESH_GLP
BT_WARN("tx need resume stack while suspended");
bt_mesh_resume();
#else
BT_WARN("Refusing to allocate buffer while suspended");
return NULL;
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
}
buf = net_buf_alloc(pool, timeout);
if (!buf) {
return NULL;
}
adv = get_id(net_buf_id(buf));
BT_MESH_ADV(buf) = adv;
memset(adv, 0, sizeof(*adv));
adv->type = type;
adv->xmit = xmit;
return buf;
}
struct net_buf *bt_mesh_adv_create(enum bt_mesh_adv_type type, u8_t xmit, bt_s32_t timeout)
{
return bt_mesh_adv_create_from_pool(&adv_buf_pool, adv_alloc, type, xmit, timeout);
}
void bt_mesh_adv_send(struct net_buf *buf, const struct bt_mesh_send_cb *cb, void *cb_data)
{
if (NULL == buf) {
BT_WARN("buf is null");
return;
}
BT_DBG("type 0x%02x len %u: %s", BT_MESH_ADV(buf)->type, buf->len, bt_hex(buf->data, buf->len));
BT_MESH_ADV(buf)->cb = cb;
BT_MESH_ADV(buf)->cb_data = cb_data;
BT_MESH_ADV(buf)->busy = 1;
net_buf_put(&adv_queue, net_buf_ref(buf));
}
#ifdef CONFIG_BT_MESH_PROVISIONER
const bt_addr_le_t *bt_mesh_pba_get_addr(void)
{
return dev_addr;
}
#endif
static void bt_mesh_scan_cb(const bt_addr_le_t *addr, s8_t rssi, u8_t adv_type, struct net_buf_simple *buf)
{
#if defined(CONFIG_BT_MESH_PROVISIONER) || defined(GENIE_ULTRA_PROV)
if (adv_type != BT_LE_ADV_NONCONN_IND && adv_type != BT_LE_ADV_IND) {
#else
if (adv_type != BT_LE_ADV_NONCONN_IND) {
#endif
return;
}
// BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_PROVISIONER
dev_addr = addr;
#endif
while (buf->len > 1) {
struct net_buf_simple_state state;
u8_t len, type;
len = net_buf_simple_pull_u8(buf);
/* Check for early termination */
if (len == 0) {
return;
}
if (len > buf->len) {
// BT_WARN("AD malformed");
return;
}
net_buf_simple_save(buf, &state);
type = net_buf_simple_pull_u8(buf);
buf->len = len - 1;
if (adv_type == BT_LE_ADV_NONCONN_IND) {
switch (type) {
case BT_DATA_MESH_MESSAGE:
#if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
net_buf_trace.buf = buf;
memcpy(net_buf_trace.addr, addr->a.val, 6);
net_buf_trace.addr[6] = addr->type;
#endif
bt_mesh_net_recv(buf, rssi, BT_MESH_NET_IF_ADV);
break;
#if defined(CONFIG_BT_MESH_PB_ADV)
case BT_DATA_MESH_PROV:
#ifdef CONFIG_BT_MESH_PROVISIONER
if (bt_mesh_is_provisioner_en()) {
provisioner_pb_adv_recv(buf);
break;
} else
#endif
{
bt_mesh_pb_adv_recv(buf);
}
break;
#endif
case BT_DATA_MESH_BEACON:
#ifdef CONFIG_BT_MESH_PROVISIONER
if (bt_mesh_is_provisioner_en()) {
provisioner_beacon_recv(buf);
} else
#endif
{
bt_mesh_beacon_recv(buf);
}
break;
case BT_DATA_MANUFACTURER_DATA:
if (g_vendor_beacon_cb != NULL) {
g_vendor_beacon_cb(addr, rssi, adv_type, (void *)buf, buf->len);
}
break;
default:
break;
}
} else if (adv_type == BT_LE_ADV_IND) {
u16_t uuid = 0;
#ifdef GENIE_ULTRA_PROV
genie_provision_ultra_prov_handle(type, (void *)buf);
#endif
switch (type) {
#if defined(CONFIG_BT_MESH_PROVISIONER) && defined(CONFIG_BT_MESH_PB_GATT)
case BT_DATA_FLAGS:
if (bt_mesh_is_provisioner_en()) {
if (!provisioner_flags_match(buf)) {
BT_DBG("Flags mismatch, ignore this adv pkt");
return;
}
}
break;
case BT_DATA_UUID16_ALL:
if (bt_mesh_is_provisioner_en()) {
uuid = provisioner_srv_uuid_recv(buf);
if (!uuid) {
BT_DBG("Service UUID mismatch, ignore this adv pkt");
return;
}
}
break;
case BT_DATA_SVC_DATA16:
if (bt_mesh_is_provisioner_en()) {
provisioner_srv_data_recv(buf, addr, uuid);
}
break;
#endif
default:
break;
}
(void)uuid;
}
net_buf_simple_restore(buf, &state);
net_buf_simple_pull(buf, len);
}
}
void bt_mesh_adv_init(void)
{
BT_INFO("enter %s\n", __func__);
k_fifo_init(&adv_queue);
NET_BUF_POOL_INIT(adv_buf_pool);
bt_mesh_adv_scan_schd_init();
k_thread_spawn(&adv_thread_data, "mesh adv", adv_thread_stack, K_THREAD_STACK_SIZEOF(adv_thread_stack), adv_thread,
NULL, 7);
}
extern int bt_le_adv_start_instant(const struct bt_le_adv_param *param, uint8_t *ad_data, size_t ad_len,
uint8_t *sd_data, size_t sd_len);
extern int bt_le_adv_stop_instant(void);
#define SCHD_LOGD(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define SCHD_LOGE(...) LOGE("ADV", ##__VA_ARGS__)
#define CONN_ADV_DATA_TIEMOUT (10)
#define NOCONN_ADV_DATA_TIEMOUT (5)
typedef enum {
SCHD_IDLE = 0,
SCHD_ADV,
SCHD_SCAN,
SCHD_ADV_SCAN,
SCHD_INVAILD,
} adv_scan_schd_state_en;
typedef enum {
ADV_ON = 0,
ADV_OFF,
SCAN_ON,
SCAN_OFF,
ACTION_INVAILD,
} adv_scan_schd_action_en;
typedef int (*adv_scan_schd_func_t)(adv_scan_schd_state_en st);
static int adv_scan_schd_idle_enter(adv_scan_schd_state_en st);
static int adv_scan_schd_idle_exit(adv_scan_schd_state_en st);
static int adv_scan_schd_adv_enter(adv_scan_schd_state_en st);
static int adv_scan_schd_adv_exit(adv_scan_schd_state_en st);
static int adv_scan_schd_scan_enter(adv_scan_schd_state_en st);
static int adv_scan_schd_scan_exit(adv_scan_schd_state_en st);
static int adv_scan_schd_adv_scan_enter(adv_scan_schd_state_en st);
static int adv_scan_schd_adv_scan_exit(adv_scan_schd_state_en st);
struct {
adv_scan_schd_func_t enter;
adv_scan_schd_func_t exit;
} adv_scan_schd_funcs[] = {
{ adv_scan_schd_idle_enter, adv_scan_schd_idle_exit },
{ adv_scan_schd_adv_enter, adv_scan_schd_adv_exit },
{ adv_scan_schd_scan_enter, adv_scan_schd_scan_exit },
{ adv_scan_schd_adv_scan_enter, adv_scan_schd_adv_scan_exit },
};
adv_scan_schd_state_en adv_scan_schd_st_change_map[4][4] = {
{ SCHD_ADV, SCHD_IDLE, SCHD_SCAN, SCHD_IDLE },
{ SCHD_ADV, SCHD_IDLE, SCHD_ADV_SCAN, SCHD_ADV },
{ SCHD_ADV_SCAN, SCHD_SCAN, SCHD_SCAN, SCHD_IDLE },
{ SCHD_ADV_SCAN, SCHD_SCAN, SCHD_ADV_SCAN, SCHD_ADV },
};
struct adv_scan_data_t {
uint8_t ad_data[31];
size_t ad_len;
uint8_t sd_data[31];
size_t sd_len;
struct bt_le_adv_param adv_param;
struct bt_le_scan_param scan_param;
bt_le_scan_cb_t *scan_cb;
};
#define FLAG_RESTART 1
#define FLAG_STOP 2
struct {
struct k_mutex mutex;
k_timer_t timer;
uint8_t flag;
adv_scan_schd_state_en cur_st;
struct adv_scan_data_t param;
} adv_scan_schd = { 0 };
static int adv_scan_schd_idle_enter(adv_scan_schd_state_en st)
{
SCHD_LOGD("idle enter\n");
memset(&adv_scan_schd.param, 0, sizeof(struct adv_scan_data_t));
return 0;
}
static int adv_scan_schd_idle_exit(adv_scan_schd_state_en st)
{
SCHD_LOGD("idle exit\n");
// do nothing
return 0;
}
static int adv_scan_schd_adv_enter(adv_scan_schd_state_en st)
{
SCHD_LOGD("adv on enter\n");
if (st == SCHD_IDLE || st == SCHD_ADV_SCAN || st == SCHD_ADV) {
if (adv_scan_schd.param.ad_len) {
adv_scan_schd.flag = FLAG_RESTART;
k_timer_start(&adv_scan_schd.timer, 1);
return 0;
}
}
return -EINVAL;
;
}
static int adv_scan_schd_adv_exit(adv_scan_schd_state_en st)
{
SCHD_LOGD("adv on exit\n");
int ret = 0;
if (st == SCHD_ADV_SCAN || st == SCHD_IDLE || st == SCHD_ADV) {
adv_scan_schd.flag = FLAG_STOP;
k_timer_stop(&adv_scan_schd.timer);
ret = bt_le_adv_stop_instant();
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("adv stop err %d\n", ret);
return ret;
}
return 0;
}
return -EINVAL;
}
static int adv_scan_schd_scan_enter(adv_scan_schd_state_en st)
{
SCHD_LOGD("scan on enter\n");
int ret = 0;
if (st == SCHD_IDLE || st == SCHD_ADV_SCAN || st == SCHD_SCAN) {
ret = bt_le_scan_start(&adv_scan_schd.param.scan_param, adv_scan_schd.param.scan_cb);
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("scan start err %d\n", ret);
return ret;
}
return 0;
}
return -EINVAL;
}
static int adv_scan_schd_scan_exit(adv_scan_schd_state_en st)
{
SCHD_LOGD("scan on exit\n");
int ret = 0;
if (st == SCHD_ADV_SCAN || st == SCHD_IDLE || st == SCHD_SCAN) {
ret = bt_le_scan_stop();
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("scan stop err %d in %s\n", ret, __func__);
return ret;
}
return 0;
}
return -EINVAL;
}
static int adv_scan_schd_adv_scan_enter(adv_scan_schd_state_en st)
{
SCHD_LOGD("adv scan on enter\n");
if (st == SCHD_ADV || st == SCHD_SCAN || st == SCHD_ADV_SCAN || st == SCHD_IDLE) {
adv_scan_schd.flag = FLAG_RESTART;
k_timer_start(&adv_scan_schd.timer, 1);
return 0;
}
return -EINVAL;
}
static int adv_scan_schd_adv_scan_exit(adv_scan_schd_state_en st)
{
int ret;
SCHD_LOGD("adv scan on exit\n");
if (st == SCHD_ADV || st == SCHD_SCAN || st == SCHD_ADV_SCAN) {
adv_scan_schd.flag = FLAG_STOP;
k_timer_stop(&adv_scan_schd.timer);
ret = bt_le_scan_stop();
// SCHD_LOGE("EALREADY = %d in %s\n", EALREADY, __func__);
if (ret && (ret != -114)) {
SCHD_LOGE("scan stop err %d in %s\n", ret, __func__);
return ret;
}
ret = bt_le_adv_stop();
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("adv stop err %d\n", ret);
return ret;
}
return 0;
}
return -EINVAL;
}
int bt_mesh_adv_scan_schd(adv_scan_schd_state_en st)
{
int ret;
SCHD_LOGD("%d->%d\n", adv_scan_schd.cur_st, st);
if (st < SCHD_INVAILD) {
ret = adv_scan_schd_funcs[adv_scan_schd.cur_st].exit(st);
if (ret) {
return ret;
}
adv_scan_schd.cur_st = SCHD_IDLE;
ret = adv_scan_schd_funcs[st].enter(adv_scan_schd.cur_st);
if (ret) {
return ret;
}
adv_scan_schd.cur_st = st;
return 0;
}
return -EINVAL;
}
int bt_mesh_adv_scan_schd_action(adv_scan_schd_action_en action)
{
int ret;
if (action < ACTION_INVAILD) {
adv_scan_schd_state_en cur_st = adv_scan_schd.cur_st;
adv_scan_schd_state_en target_st = adv_scan_schd_st_change_map[cur_st][action];
k_mutex_lock(&adv_scan_schd.mutex, K_FOREVER);
ret = bt_mesh_adv_scan_schd(target_st);
k_mutex_unlock(&adv_scan_schd.mutex);
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("action %d, cur_st %d target_st %d, ret %d in %s\n", action, cur_st, target_st, ret, __func__);
}
return ret;
}
return -EINVAL;
}
void adv_scan_timer(void *timer, void *arg)
{
int ret;
static enum {
ADV = 0,
SCAN,
ADV_IDLE,
} next_state = ADV;
static int adv_time = 0;
uint32_t next_time = 0;
k_mutex_lock(&adv_scan_schd.mutex, K_FOREVER);
if (adv_scan_schd.flag == FLAG_RESTART) {
next_state = ADV;
adv_scan_schd.flag = 0;
} else if (adv_scan_schd.flag == FLAG_STOP) {
k_mutex_unlock(&adv_scan_schd.mutex);
return;
}
SCHD_LOGD("adv_time %d, next_state %d, flag %d\n", adv_time, next_state, adv_scan_schd.flag);
if (next_state == ADV) {
ret = bt_le_scan_stop();
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("scan stop err %d in %s\n", ret, __func__);
}
struct bt_le_adv_param param = adv_scan_schd.param.adv_param;
param.interval_min = BT_GAP_ADV_SLOW_INT_MIN;
param.interval_max = param.interval_min;
ret = bt_le_adv_start_instant(¶m, adv_scan_schd.param.ad_data, adv_scan_schd.param.ad_len,
adv_scan_schd.param.sd_data, adv_scan_schd.param.sd_len);
if (ret && (ret != -EALREADY) && (ret != -ENOMEM)) {
SCHD_LOGE("adv start err %d\n", ret);
}
if (adv_scan_schd.cur_st == SCHD_ADV_SCAN) {
next_state = SCAN;
} else if (adv_scan_schd.cur_st == SCHD_ADV) {
next_state = ADV_IDLE;
}
adv_time = (!(param.options & BT_LE_ADV_OPT_CONNECTABLE)) ? NOCONN_ADV_DATA_TIEMOUT : CONN_ADV_DATA_TIEMOUT;
next_time = adv_time;
} else if (next_state == SCAN) {
ret = bt_le_adv_stop();
if (ret && (ret != -EALREADY)) {
SCHD_LOGE("adv stop err %d\n", ret);
}
/* Here, we define the adv window of each package in adv duration (120ms or xmit related time)*/
if (adv_scan_schd.param.adv_param.options & BT_LE_ADV_OPT_CONNECTABLE) {
next_time = adv_scan_schd.param.adv_param.interval_min * 5 / 8 - adv_time;
} else {
next_time =
CONFIG_ADV_INTERVAL_TIMER - adv_time; // adv_scan_schd.param.adv_param.interval_min * 5 / 8 - adv_time;
}
if (next_time > CONFIG_ADV_SCAN_INTERVAL_TIMER) {
ret = bt_le_scan_start(&adv_scan_schd.param.scan_param, adv_scan_schd.param.scan_cb);
if (ret) {
SCHD_LOGE("scan err %d\n", ret);
}
}
adv_time = 0;
next_state = ADV;
} else if (next_state == ADV_IDLE) {
if (adv_scan_schd.param.adv_param.options & BT_LE_ADV_OPT_CONNECTABLE) {
next_time = adv_scan_schd.param.adv_param.interval_min * 5 / 8 - adv_time;
} else {
next_time =
CONFIG_ADV_INTERVAL_TIMER - adv_time; // adv_scan_schd.param.adv_param.interval_min * 5 / 8 - adv_time;
}
adv_time = 0;
next_state = ADV;
}
k_mutex_unlock(&adv_scan_schd.mutex);
k_timer_start(&adv_scan_schd.timer, next_time);
}
int bt_mesh_adv_scan_schd_init()
{
memset(&adv_scan_schd, 0, sizeof(adv_scan_schd));
k_timer_init(&adv_scan_schd.timer, adv_scan_timer, &adv_scan_schd);
k_mutex_init(&adv_scan_schd.mutex);
return 0;
}
static int set_ad_data(uint8_t *data, const struct bt_data *ad, size_t ad_len)
{
int i;
int set_len = 0;
for (i = 0; i < ad_len; i++) {
int len = ad[i].data_len;
u8_t type = ad[i].type;
/* Check if ad fit in the remaining buffer */
if (set_len + len + 2 > 31) {
len = 31 - (set_len + 2);
if (type != BT_DATA_NAME_COMPLETE || len <= 0) {
return -EINVAL;
}
type = BT_DATA_NAME_SHORTENED;
}
data[set_len++] = len + 1;
data[set_len++] = type;
memcpy(&data[set_len], ad[i].data, len);
set_len += len;
}
return set_len;
}
int bt_mesh_adv_enable(const struct bt_le_adv_param *param, const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len)
{
if (param == NULL) {
return -EINVAL;
}
BT_ERR("enter %s\n", __func__);
k_mutex_lock(&adv_scan_schd.mutex, K_FOREVER);
adv_scan_schd.param.adv_param = *param;
adv_scan_schd.param.ad_len = set_ad_data(adv_scan_schd.param.ad_data, ad, ad_len);
adv_scan_schd.param.sd_len = set_ad_data(adv_scan_schd.param.sd_data, sd, sd_len);
k_mutex_unlock(&adv_scan_schd.mutex);
bt_mesh_adv_scan_schd_action(ADV_ON);
return 0;
}
int bt_mesh_adv_disable()
{
BT_ERR("enter %s\n", __func__);
bt_mesh_adv_scan_schd_action(ADV_OFF);
return 0;
}
int bt_mesh_scan_enable(void)
{
struct bt_le_scan_param scan_param = { .type = BT_HCI_LE_SCAN_PASSIVE,
.filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE,
.interval = MESH_SCAN_INTERVAL,
.window = MESH_SCAN_WINDOW };
BT_ERR("enter %s\n", __func__);
k_mutex_lock(&adv_scan_schd.mutex, K_FOREVER);
adv_scan_schd.param.scan_param = scan_param;
adv_scan_schd.param.scan_cb = bt_mesh_scan_cb;
k_mutex_unlock(&adv_scan_schd.mutex);
bt_mesh_adv_scan_schd_action(SCAN_ON);
return 0;
}
int bt_mesh_scan_disable(void)
{
BT_ERR("");
bt_mesh_adv_scan_schd_action(SCAN_OFF);
return 0;
}
int bt_mesh_adv_vnd_scan_register(vendor_beacon_cb bacon_cb)
{
if (!bacon_cb) {
return -EINVAL;
}
g_vendor_beacon_cb = bacon_cb;
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/adv.c | C | apache-2.0 | 24,385 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <misc/util.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_BEACON)
#include "common/log.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "prov.h"
#include "crypto.h"
#include "beacon.h"
#include "foundation.h"
#define UNPROVISIONED_INTERVAL K_SECONDS(5)
#define PROVISIONED_INTERVAL K_SECONDS(10)
/* 3 transmissions, 20ms interval */
#define UNPROV_XMIT BT_MESH_TRANSMIT(2, 20)
/* 1 transmission, 20ms interval */
#define PROV_XMIT BT_MESH_TRANSMIT(0, 20)
static struct k_delayed_work beacon_timer;
static bt_u32_t unprov_beacon_interval = UNPROVISIONED_INTERVAL;
static bt_u32_t prov_beacon_interval = PROVISIONED_INTERVAL;
static struct bt_mesh_subnet *cache_check(u8_t data[21])
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (!memcmp(sub->beacon_cache, data, 21)) {
return sub;
}
}
return NULL;
}
static void cache_add(u8_t data[21], struct bt_mesh_subnet *sub)
{
memcpy(sub->beacon_cache, data, 21);
}
static void beacon_complete(int err, void *user_data)
{
struct bt_mesh_subnet *sub = user_data;
BT_DBG("err %d", err);
sub->beacon_sent = k_uptime_get_32();
}
uint32_t unprov_beacon_interval_get()
{
return unprov_beacon_interval;
}
void genie_set_silent_unprov_beacon_interval(bool is_silent)
{
if (is_silent) {
unprov_beacon_interval = K_SECONDS(60);
} else {
unprov_beacon_interval = K_SECONDS(5);
}
return;
}
void bt_mesh_beacon_create(struct bt_mesh_subnet *sub, struct net_buf_simple *buf)
{
u8_t flags = bt_mesh_net_flags(sub);
struct bt_mesh_subnet_keys *keys;
net_buf_simple_add_u8(buf, BEACON_TYPE_SECURE);
if (sub->kr_flag) {
keys = &sub->keys[1];
} else {
keys = &sub->keys[0];
}
net_buf_simple_add_u8(buf, flags);
/* Network ID */
net_buf_simple_add_mem(buf, keys->net_id, 8);
/* IV Index */
net_buf_simple_add_be32(buf, bt_mesh.iv_index);
net_buf_simple_add_mem(buf, sub->auth, 8);
BT_DBG("net_idx 0x%04x flags 0x%02x NetID %s", sub->net_idx, flags, bt_hex(keys->net_id, 8));
BT_DBG("IV Index 0x%08x Auth %s", bt_mesh.iv_index, bt_hex(sub->auth, 8));
}
/* If the interval has passed or is within 5 seconds from now send a beacon */
#define BEACON_THRESHOLD(sub) (K_SECONDS(10 * ((sub)->beacons_last + 1)) - K_SECONDS(5))
static int secure_beacon_send(void)
{
static const struct bt_mesh_send_cb send_cb = {
.end = beacon_complete,
};
#ifndef CONFIG_BT_BQB
bt_u32_t now = k_uptime_get_32();
bt_u32_t time_diff;
#endif
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
struct net_buf *buf;
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
#ifndef CONFIG_BT_BQB
time_diff = now - sub->beacon_sent;
/*[Genie begin] add by lgy at 2021-01-19*/
if (time_diff < K_SECONDS(600)) {
#ifdef CONFIG_GENIE_MESH_GLP
if (time_diff < K_SECONDS(30))
#else
if (time_diff < BEACON_THRESHOLD(sub))
#endif
{
continue;
}
}
/*[Genie end] add by lgy at 2021-01-19*/
#endif
buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, PROV_XMIT, K_NO_WAIT);
if (!buf) {
BT_ERR("Unable to allocate beacon buffer");
return -ENOBUFS;
}
bt_mesh_beacon_create(sub, &buf->b);
bt_mesh_adv_send(buf, &send_cb, sub);
net_buf_unref(buf);
}
return 0;
}
static int unprovisioned_beacon_send(void)
{
#if defined(CONFIG_BT_MESH_PB_ADV)
const struct bt_mesh_prov *prov;
u8_t uri_hash[16] = { 0 };
struct net_buf *buf;
u16_t oob_info;
BT_DBG("");
buf = bt_mesh_adv_create(BT_MESH_ADV_BEACON, UNPROV_XMIT, K_NO_WAIT);
if (!buf) {
BT_ERR("Unable to allocate beacon buffer");
return -ENOBUFS;
}
prov = bt_mesh_prov_get();
net_buf_add_u8(buf, BEACON_TYPE_UNPROVISIONED);
net_buf_add_mem(buf, prov->uuid, 16);
if (prov->uri && bt_mesh_s1(prov->uri, uri_hash) == 0) {
oob_info = prov->oob_info | BT_MESH_PROV_OOB_URI;
} else {
oob_info = prov->oob_info;
}
net_buf_add_be16(buf, oob_info);
net_buf_add_mem(buf, uri_hash, 4);
bt_mesh_adv_send(buf, NULL, NULL);
net_buf_unref(buf);
if (prov->uri) {
size_t len;
buf = bt_mesh_adv_create(BT_MESH_ADV_URI, UNPROV_XMIT, K_NO_WAIT);
if (!buf) {
BT_ERR("Unable to allocate URI buffer");
return -ENOBUFS;
}
len = strlen(prov->uri);
if (net_buf_tailroom(buf) < len) {
BT_WARN("Too long URI to fit advertising data");
} else {
net_buf_add_mem(buf, prov->uri, len);
bt_mesh_adv_send(buf, NULL, NULL);
}
net_buf_unref(buf);
}
#endif /* CONFIG_BT_MESH_PB_ADV */
return 0;
}
static void update_beacon_observation(void)
{
static bool first_half;
int i;
/* Observation period is 20 seconds, whereas the beacon timer
* runs every 10 seconds. We process what's happened during the
* window only after the seconnd half.
*/
first_half = !first_half;
if (first_half) {
return;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
sub->beacons_last = sub->beacons_cur;
sub->beacons_cur = 0;
}
}
static void beacon_send(struct k_work *work)
{
/* Don't send anything if we have an active provisioning link */
if (IS_ENABLED(CONFIG_BT_MESH_PROV) && bt_prov_active()) {
k_delayed_work_submit(&beacon_timer, bt_mesh_get_beacon_interval(BEACON_TYPE_UNPROVISIONED));
return;
}
BT_DBG("");
if (bt_mesh_is_provisioned()) {
update_beacon_observation();
secure_beacon_send();
/* Only resubmit if beaconing is still enabled */
if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED || atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) {
k_delayed_work_submit(&beacon_timer, bt_mesh_get_beacon_interval(BEACON_TYPE_SECURE));
}
} else {
unprovisioned_beacon_send();
k_delayed_work_submit(&beacon_timer, bt_mesh_get_beacon_interval(BEACON_TYPE_UNPROVISIONED));
}
}
static void secure_beacon_recv(struct net_buf_simple *buf)
{
u8_t *data, *net_id, *auth;
struct bt_mesh_subnet *sub;
bt_u32_t iv_index;
bool new_key, kr_change, iv_change;
u8_t flags;
if (buf->len < 21) {
BT_ERR("Too short secure beacon (len %u)", buf->len);
return;
}
sub = cache_check(buf->data);
if (sub) {
/* We've seen this beacon before - just update the stats */
goto update_stats;
}
/* So we can add to the cache if auth matches */
data = buf->data;
flags = net_buf_simple_pull_u8(buf);
net_id = net_buf_simple_pull_mem(buf, 8);
iv_index = net_buf_simple_pull_be32(buf);
auth = buf->data;
BT_DBG("flags 0x%02x id %s iv_index 0x%08x", flags, bt_hex(net_id, 8), iv_index);
sub = bt_mesh_subnet_find(net_id, flags, iv_index, auth, &new_key);
if (!sub) {
BT_DBG("No subnet that matched beacon");
return;
}
if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !new_key) {
BT_WARN("Ignoring Phase 2 KR Update secured using old key");
return;
}
cache_add(data, sub);
/* If we have NetKey0 accept initiation only from it */
if (bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY) && sub->net_idx != BT_MESH_KEY_PRIMARY) {
BT_WARN("Ignoring secure beacon on non-primary subnet");
goto update_stats;
}
BT_DBG("net_idx 0x%04x iv_index 0x%08x, current iv_index 0x%08x", sub->net_idx, iv_index, bt_mesh.iv_index);
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) &&
(atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) == BT_MESH_IV_UPDATE(flags))) {
bt_mesh_beacon_ivu_initiator(false);
}
iv_change = bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(flags));
kr_change = bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(flags), new_key);
if (kr_change) {
bt_mesh_net_beacon_update(sub);
}
if (iv_change) {
/* Update all subnets */
bt_mesh_net_sec_update(NULL);
} else if (kr_change) {
/* Key Refresh without IV Update only impacts one subnet */
bt_mesh_net_sec_update(sub);
}
update_stats:
if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED && sub->beacons_cur < 0xff) {
sub->beacons_cur++;
}
}
bt_u32_t bt_mesh_get_beacon_interval(u8_t type)
{
switch (type) {
case BEACON_TYPE_UNPROVISIONED:
return unprov_beacon_interval;
case BEACON_TYPE_SECURE:
return prov_beacon_interval;
default:
return 0;
}
}
void bt_mesh_set_beacon_interval(u8_t type, bt_u32_t delay)
{
switch (type) {
case BEACON_TYPE_UNPROVISIONED:
unprov_beacon_interval = delay;
return;
case BEACON_TYPE_SECURE:
prov_beacon_interval = delay;
return;
default:
return;
}
}
void bt_mesh_beacon_recv(struct net_buf_simple *buf)
{
u8_t type;
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (buf->len < 1) {
BT_ERR("Too short beacon");
return;
}
type = net_buf_simple_pull_u8(buf);
switch (type) {
case BEACON_TYPE_UNPROVISIONED:
BT_DBG("Ignoring unprovisioned device beacon");
break;
case BEACON_TYPE_SECURE:
secure_beacon_recv(buf);
break;
default:
BT_WARN("Unknown beacon type 0x%02x", type);
break;
}
}
void bt_mesh_beacon_init(void)
{
BT_INFO("enter %s\n", __func__);
k_delayed_work_init(&beacon_timer, beacon_send);
}
void bt_mesh_beacon_ivu_initiator(bool enable)
{
atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_INITIATOR, enable);
if (enable) {
k_work_submit(&beacon_timer.work);
} else if (bt_mesh_beacon_get() == BT_MESH_BEACON_DISABLED) {
k_delayed_work_cancel(&beacon_timer);
}
}
void bt_mesh_beacon_enable(void)
{
int i;
if (!bt_mesh_is_provisioned()) {
k_work_submit(&beacon_timer.work);
return;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
sub->beacons_last = 0;
sub->beacons_cur = 0;
bt_mesh_net_beacon_update(sub);
}
k_work_submit(&beacon_timer.work);
}
void bt_mesh_beacon_disable(void)
{
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR)) {
k_delayed_work_cancel(&beacon_timer);
}
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/beacon.c | C | apache-2.0 | 11,349 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <ble_types/types.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "net.h"
#include "foundation.h"
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
#if defined(CONFIG_BT_MESH_CFG_CLI)
#define CID_NVAL 0xffff
struct comp_data {
u8_t *status;
struct net_buf_simple *comp;
};
static bt_s32_t msg_timeout = K_SECONDS(2);
static struct bt_mesh_cfg_cli *cli;
struct bt_mesh_cfg_cli g_cfg_cli = {};
static void comp_data_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct comp_data *param;
size_t to_copy;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_COMP_DATA_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_DEV_COMP_DATA_STATUS) {
BT_WARN("Unexpected Composition Data Status");
return;
}
param = cli->op_param;
status = net_buf_simple_pull_u8(buf);
if (param) {
to_copy = MIN(net_buf_simple_tailroom(param->comp), buf->len);
net_buf_simple_add_mem(param->comp, buf->data, to_copy);
if (param && param->status) {
*param->status = status;
}
k_sem_give(&cli->op_sync);
}
}
static void state_status_u8(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf,
bt_u32_t expect_status)
{
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (cli->op_pending != expect_status) {
BT_WARN("Unexpected Status (0x%08x != 0x%08x)", cli->op_pending, expect_status);
return;
}
status = net_buf_simple_pull_u8(buf);
if (cli->op_param) {
*((u8_t *)cli->op_param) = status;
k_sem_give(&cli->op_sync);
}
}
static void beacon_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_BEACON_STATUS, &evt_data);
}
#endif
state_status_u8(model, ctx, buf, OP_BEACON_STATUS);
}
static void ttl_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_TTL_STATUS, &evt_data);
}
#endif
state_status_u8(model, ctx, buf, OP_DEFAULT_TTL_STATUS);
}
static void friend_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_FRIEND_STATUS, &evt_data);
}
#endif
state_status_u8(model, ctx, buf, OP_FRIEND_STATUS);
}
static void gatt_proxy_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_PROXY_STATUS, &evt_data);
}
#endif
state_status_u8(model, ctx, buf, OP_GATT_PROXY_STATUS);
}
struct relay_param {
u8_t *status;
u8_t *transmit;
};
static void relay_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct relay_param *param;
uint8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_RELAY_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_RELAY_STATUS) {
BT_WARN("Unexpected Relay Status message");
return;
}
param = cli->op_param;
status = net_buf_simple_pull_u8(buf);
if (param) {
*param->transmit = net_buf_simple_pull_u8(buf);
if (param->status) {
*param->status = status;
}
k_sem_give(&cli->op_sync);
}
}
struct net_key_param {
u8_t *status;
u16_t net_idx;
};
static void net_key_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct net_key_param *param;
u16_t net_idx;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NETKEY_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_NET_KEY_STATUS) {
BT_WARN("Unexpected Net Key Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
net_idx = net_buf_simple_pull_le16(buf);
param = cli->op_param;
if (param && param->net_idx != net_idx) {
BT_WARN("Net Key Status key index does not match");
return;
}
if (param && param->status) {
*param->status = status;
}
if (param) {
k_sem_give(&cli->op_sync);
}
}
struct krp_param {
uint8_t *status;
uint16_t net_idx;
uint8_t *phase;
};
static void net_krp_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct krp_param *param;
u16_t net_idx;
u8_t status, phase;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s\n", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NET_KRP_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_KRP_STATUS) {
BT_WARN("Unexpected KRP Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
net_idx = net_buf_simple_pull_le16(buf);
phase = net_buf_simple_pull_u8(buf);
param = cli->op_param;
if (param) {
if (param->net_idx != net_idx) {
BT_WARN("krp Status key index does not match");
return;
}
if (param->status) {
*param->status = status;
}
if (param->phase) {
*param->phase = phase;
}
k_sem_give(&cli->op_sync);
}
}
struct app_key_param {
u8_t *status;
u16_t net_idx;
u16_t app_idx;
};
static void app_key_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct app_key_param *param;
u16_t net_idx, app_idx;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_APPKEY_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_APP_KEY_STATUS) {
BT_WARN("Unexpected App Key Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
key_idx_unpack(buf, &net_idx, &app_idx);
param = cli->op_param;
if (param && (param->net_idx != net_idx || param->app_idx != app_idx)) {
BT_WARN("App Key Status key indices did not match");
return;
}
if (param && param->status) {
*param->status = status;
}
if (param) {
k_sem_give(&cli->op_sync);
}
}
struct mod_app_param {
u8_t *status;
u16_t elem_addr;
u16_t mod_app_idx;
u16_t mod_id;
u16_t cid;
};
static void mod_app_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, mod_app_idx, mod_id, cid;
struct mod_app_param *param;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_APPKEY_BIND_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_MOD_APP_STATUS) {
BT_WARN("Unexpected Model App Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
elem_addr = net_buf_simple_pull_le16(buf);
mod_app_idx = net_buf_simple_pull_le16(buf);
if (buf->len >= 4) {
cid = net_buf_simple_pull_le16(buf);
} else {
cid = CID_NVAL;
}
mod_id = net_buf_simple_pull_le16(buf);
param = cli->op_param;
if (param) {
if (param->elem_addr != elem_addr || param->mod_app_idx != mod_app_idx || param->mod_id != mod_id ||
param->cid != cid) {
BT_WARN("Model App Status parameters did not match");
return;
}
if (param->status) {
*param->status = status;
}
k_sem_give(&cli->op_sync);
}
}
struct mod_pub_param {
u16_t mod_id;
u16_t cid;
u16_t elem_addr;
u8_t *status;
struct bt_mesh_cfg_mod_pub *pub;
};
static void mod_pub_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t mod_id, cid, elem_addr;
struct mod_pub_param *param;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_PUB_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_MOD_PUB_STATUS) {
BT_WARN("Unexpected Model Pub Status message");
return;
}
param = cli->op_param;
if (param) {
if (param->cid != CID_NVAL) {
if (buf->len < 14) {
BT_WARN("Unexpected Mod Pub Status with SIG Model");
return;
}
cid = sys_get_le16(&buf->data[10]);
mod_id = sys_get_le16(&buf->data[12]);
} else {
if (buf->len > 12) {
BT_WARN("Unexpected Mod Pub Status with Vendor Model");
return;
}
cid = CID_NVAL;
mod_id = sys_get_le16(&buf->data[10]);
}
if (mod_id != param->mod_id || cid != param->cid) {
BT_WARN("Mod Pub Model ID or Company ID mismatch");
return;
}
status = net_buf_simple_pull_u8(buf);
elem_addr = net_buf_simple_pull_le16(buf);
if (elem_addr != param->elem_addr) {
BT_WARN("Model Pub Status for unexpected element (0x%04x)", elem_addr);
return;
}
if (param->status) {
*param->status = status;
}
if (param->pub) {
param->pub->addr = net_buf_simple_pull_le16(buf);
param->pub->app_idx = net_buf_simple_pull_le16(buf);
param->pub->cred_flag = (param->pub->app_idx & BIT(12));
param->pub->app_idx &= BIT_MASK(12);
param->pub->ttl = net_buf_simple_pull_u8(buf);
param->pub->period = net_buf_simple_pull_u8(buf);
param->pub->transmit = net_buf_simple_pull_u8(buf);
}
k_sem_give(&cli->op_sync);
}
}
struct mod_sub_param {
u8_t *status;
u16_t elem_addr;
u16_t *sub_addr;
u16_t *expect_sub;
u16_t mod_id;
u16_t cid;
};
static void mod_sub_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr, mod_id, cid;
struct mod_sub_param *param;
u8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SUB_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_MOD_SUB_STATUS) {
BT_WARN("Unexpected Model Subscription Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
elem_addr = net_buf_simple_pull_le16(buf);
sub_addr = net_buf_simple_pull_le16(buf);
if (buf->len >= 4) {
cid = net_buf_simple_pull_le16(buf);
} else {
cid = CID_NVAL;
}
mod_id = net_buf_simple_pull_le16(buf);
param = cli->op_param;
if (param) {
if (param->elem_addr != elem_addr || param->mod_id != mod_id ||
(param->expect_sub && *param->expect_sub != sub_addr) || param->cid != cid) {
BT_WARN("Model Subscription Status parameters did not match");
return;
}
if (param->sub_addr) {
*param->sub_addr = sub_addr;
}
if (param->status) {
*param->status = status;
}
k_sem_give(&cli->op_sync);
}
}
static void mod_sub_list_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr;
struct mod_sub_param *param;
u8_t status;
u16_t mod_id;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SUB_LIST, &evt_data);
}
#endif
if (cli->op_pending != OP_MOD_SUB_LIST) {
BT_WARN("Unexpected Model App Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
elem_addr = net_buf_simple_pull_le16(buf);
mod_id = net_buf_simple_pull_le16(buf);
param = (struct mod_sub_param *)cli->op_param;
if (param) {
if (param->elem_addr != elem_addr) {
BT_WARN("Model App Status parameters did not match");
return;
}
if (param->status) {
*param->status = status;
}
if (param->sub_addr) {
uint8_t index = 0;
while (buf->len >= 2) {
param->sub_addr[index++] = net_buf_simple_pull_le16(buf);
}
}
k_sem_give(&cli->op_sync);
}
(void)mod_id;
}
static void mod_sub_list_vnd_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u16_t elem_addr;
u16_t company_id;
struct mod_sub_param *param;
u8_t status;
u16_t mod_id;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SUB_LIST_VND, &evt_data);
}
#endif
if (cli->op_pending != OP_MOD_SUB_LIST_VND) {
BT_WARN("Unexpected Model App Status message");
return;
}
status = net_buf_simple_pull_u8(buf);
elem_addr = net_buf_simple_pull_le16(buf);
company_id = net_buf_simple_pull_le16(buf);
mod_id = net_buf_simple_pull_le16(buf);
param = (struct mod_sub_param *)cli->op_param;
if (param) {
if (param->elem_addr != elem_addr) {
BT_WARN("Model App Status parameters did not match");
return;
}
if (param->status) {
*param->status = status;
}
if (param->sub_addr) {
uint8_t index = 0;
while (buf->len >= 2) {
param->sub_addr[index++] = net_buf_simple_pull_le16(buf);
}
}
k_sem_give(&cli->op_sync);
}
(void)mod_id;
(void)company_id;
}
struct hb_sub_param {
u8_t *status;
struct bt_mesh_cfg_hb_sub *sub;
};
static void hb_sub_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct hb_sub_param *param;
uint8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_HB_SUB_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_HEARTBEAT_SUB_STATUS) {
BT_WARN("Unexpected Heartbeat Subscription Status message");
return;
}
param = cli->op_param;
status = net_buf_simple_pull_u8(buf);
if (param) {
param->sub->src = net_buf_simple_pull_le16(buf);
param->sub->dst = net_buf_simple_pull_le16(buf);
param->sub->period = net_buf_simple_pull_u8(buf);
param->sub->count = net_buf_simple_pull_u8(buf);
param->sub->min = net_buf_simple_pull_u8(buf);
param->sub->max = net_buf_simple_pull_u8(buf);
if (param->status) {
*param->status = status;
}
k_sem_give(&cli->op_sync);
}
}
struct hb_pub_param {
u8_t *status;
struct bt_mesh_cfg_hb_pub *pub;
};
static void hb_pub_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct hb_pub_param *param;
uint8_t status;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_HB_PUB_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_HEARTBEAT_PUB_STATUS) {
BT_WARN("Unexpected Heartbeat Publication Status message");
return;
}
param = cli->op_param;
status = net_buf_simple_pull_u8(buf);
if (param && param->pub) {
param->pub->dst = net_buf_simple_pull_le16(buf);
param->pub->count = net_buf_simple_pull_u8(buf);
param->pub->period = net_buf_simple_pull_u8(buf);
param->pub->ttl = net_buf_simple_pull_u8(buf);
param->pub->feat = net_buf_simple_pull_u8(buf);
param->pub->net_idx = net_buf_simple_pull_u8(buf);
}
if (param && param->status) {
*param->status = status;
}
if (param) {
k_sem_give(&cli->op_sync);
}
}
static void node_reset_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NODE_RESET_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_NODE_RESET_STATUS) {
BT_WARN("Unexpected Node Reset Status message");
return;
}
k_sem_give(&cli->op_sync);
}
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
struct cli_cr_param {
u8_t *status;
struct ctrl_relay_param *cr_p;
};
static void cli_ctrl_relay_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct cli_cr_param *param;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = ctx->addr;
evt_data.user_data = buf;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_CTRL_RELAY_STATUS, &evt_data);
}
#endif
if (cli->op_pending != OP_CTRL_RELAY_CONF_STATUS) {
BT_WARN("Unexpected Ctrl Relay Status message");
return;
}
param = cli->op_param;
*param->status = net_buf_simple_pull_u8(buf);
if (param->cr_p) {
param->cr_p->enable = net_buf_simple_pull_u8(buf);
param->cr_p->trd_n = net_buf_simple_pull_u8(buf);
param->cr_p->rssi = net_buf_simple_pull_u8(buf);
param->cr_p->sta_period = net_buf_simple_pull_u8(buf);
param->cr_p->chk_period = net_buf_simple_pull_u8(buf);
param->cr_p->req_period = net_buf_simple_pull_u8(buf);
}
k_sem_give(&cli->op_sync);
}
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
const struct bt_mesh_model_op bt_mesh_cfg_cli_op[] = {
{ OP_DEV_COMP_DATA_STATUS, 15, comp_data_status },
{ OP_BEACON_STATUS, 1, beacon_status },
{ OP_DEFAULT_TTL_STATUS, 1, ttl_status },
{ OP_FRIEND_STATUS, 1, friend_status },
{ OP_GATT_PROXY_STATUS, 1, gatt_proxy_status },
{ OP_RELAY_STATUS, 2, relay_status },
{ OP_NET_KEY_STATUS, 3, net_key_status },
{ OP_APP_KEY_STATUS, 4, app_key_status },
{ OP_MOD_APP_STATUS, 7, mod_app_status },
{ OP_MOD_PUB_STATUS, 12, mod_pub_status },
{ OP_MOD_SUB_STATUS, 7, mod_sub_status },
{ OP_HEARTBEAT_SUB_STATUS, 9, hb_sub_status },
{ OP_HEARTBEAT_PUB_STATUS, 10, hb_pub_status },
{ OP_NODE_RESET_STATUS, 0, node_reset_status },
{ OP_KRP_STATUS, 4, net_krp_status },
{ OP_MOD_SUB_LIST, 5, mod_sub_list_status },
{ OP_MOD_SUB_LIST_VND, 7, mod_sub_list_vnd_status },
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
{ OP_CTRL_RELAY_CONF_STATUS, 7, cli_ctrl_relay_status },
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
BT_MESH_MODEL_OP_END,
};
static int cli_prepare(void *param, bt_u32_t op)
{
if (!cli) {
BT_ERR("No available Configuration Client context!");
return -EINVAL;
}
if (cli->op_pending) {
BT_WARN("Another synchronous operation pending");
return -EBUSY;
}
cli->op_param = param;
cli->op_pending = op;
return 0;
}
static void cli_reset(void)
{
cli->op_pending = 0;
cli->op_param = NULL;
}
static int cli_wait(void)
{
int err;
err = k_sem_take(&cli->op_sync, msg_timeout);
cli_reset();
return err;
}
int bt_mesh_cfg_comp_data_get(u16_t net_idx, u16_t addr, u8_t page, u8_t *status, struct net_buf_simple *comp)
{
if (status && comp == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct comp_data param = {
.status = status,
.comp = comp,
};
int err;
err = cli_prepare(¶m, OP_DEV_COMP_DATA_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_DEV_COMP_DATA_GET);
net_buf_simple_add_u8(&msg, page);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
static int get_state_u8(u16_t net_idx, u16_t addr, bt_u32_t op, bt_u32_t rsp, u8_t *val)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
int err;
err = cli_prepare(val, rsp);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, op);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!val) {
cli_reset();
return 0;
}
return cli_wait();
}
static int set_state_u8(u16_t net_idx, u16_t addr, bt_u32_t op, bt_u32_t rsp, u8_t new_val, u8_t *val)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
int err;
err = cli_prepare(val, rsp);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, op);
net_buf_simple_add_u8(&msg, new_val);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!val) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_beacon_get(u16_t net_idx, u16_t addr, u8_t *status)
{
return get_state_u8(net_idx, addr, OP_BEACON_GET, OP_BEACON_STATUS, status);
}
int bt_mesh_cfg_beacon_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status)
{
if (val > BT_MESH_BEACON_ENABLED) {
return -EINVAL;
}
return set_state_u8(net_idx, addr, OP_BEACON_SET, OP_BEACON_STATUS, val, status);
}
int bt_mesh_cfg_ttl_get(u16_t net_idx, u16_t addr, u8_t *ttl)
{
if (ttl == NULL) {
return -EINVAL;
}
return get_state_u8(net_idx, addr, OP_DEFAULT_TTL_GET, OP_DEFAULT_TTL_STATUS, ttl);
}
int bt_mesh_cfg_ttl_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *ttl)
{
if (ttl == NULL || val == 0x01 || val > BT_MESH_TTL_MAX) {
return -EINVAL;
}
return set_state_u8(net_idx, addr, OP_DEFAULT_TTL_SET, OP_DEFAULT_TTL_STATUS, val, ttl);
}
int bt_mesh_cfg_friend_get(u16_t net_idx, u16_t addr, u8_t *status)
{
return get_state_u8(net_idx, addr, OP_FRIEND_GET, OP_FRIEND_STATUS, status);
}
int bt_mesh_cfg_friend_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status)
{
if (val > BT_MESH_FRIEND_ENABLED) {
return -EINVAL;
}
return set_state_u8(net_idx, addr, OP_FRIEND_SET, OP_FRIEND_STATUS, val, status);
}
int bt_mesh_cfg_gatt_proxy_get(u16_t net_idx, u16_t addr, u8_t *status)
{
return get_state_u8(net_idx, addr, OP_GATT_PROXY_GET, OP_GATT_PROXY_STATUS, status);
}
int bt_mesh_cfg_gatt_proxy_set(u16_t net_idx, u16_t addr, u8_t val, u8_t *status)
{
if (val > BT_MESH_GATT_PROXY_ENABLED) {
return -EINVAL;
}
return set_state_u8(net_idx, addr, OP_GATT_PROXY_SET, OP_GATT_PROXY_STATUS, val, status);
}
int bt_mesh_cfg_relay_get(u16_t net_idx, u16_t addr, u8_t *status, u8_t *transmit)
{
if (transmit == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct relay_param param = {
.status = status,
.transmit = transmit,
};
int err;
err = cli_prepare(¶m, OP_RELAY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_RELAY_GET);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_relay_set(u16_t net_idx, u16_t addr, u8_t new_relay, u8_t new_transmit, u8_t *status, u8_t *transmit)
{
if (transmit == NULL) {
return -EINVAL;
}
if (new_relay > BT_MESH_RELAY_ENABLED) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct relay_param param = {
.status = status,
.transmit = transmit,
};
int err;
err = cli_prepare(¶m, OP_RELAY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_RELAY_SET);
net_buf_simple_add_u8(&msg, new_relay);
net_buf_simple_add_u8(&msg, new_transmit);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_net_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, const u8_t net_key[16], u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 18 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct net_key_param param = {
.status = status,
.net_idx = key_net_idx,
};
int err;
err = cli_prepare(¶m, OP_NET_KEY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_NET_KEY_ADD);
net_buf_simple_add_le16(&msg, key_net_idx);
net_buf_simple_add_mem(&msg, net_key, 16);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_net_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, const u8_t net_key[16], u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 18 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct net_key_param param = {
.status = status,
.net_idx = key_net_idx,
};
int err;
err = cli_prepare(¶m, OP_NET_KEY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_NET_KEY_UPDATE);
net_buf_simple_add_le16(&msg, key_net_idx);
net_buf_simple_add_mem(&msg, net_key, 16);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_krp_set(u16_t net_idx, u16_t addr, u16_t key_net_idx, u8_t *phase, u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct krp_param param = {
.status = status,
.net_idx = key_net_idx,
.phase = phase,
};
int err;
err = cli_prepare(¶m, OP_KRP_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_KRP_SET);
net_buf_simple_add_le16(&msg, key_net_idx);
net_buf_simple_add_u8(&msg, *phase);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_krp_get(u16_t net_idx, u16_t addr, u16_t key_net_idx, u8_t *phase, u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct krp_param param = {
.status = status,
.net_idx = key_net_idx,
.phase = phase,
};
int err;
err = cli_prepare(¶m, OP_KRP_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_KRP_GET);
net_buf_simple_add_le16(&msg, key_net_idx);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_app_key_add(u16_t net_idx, u16_t addr, u16_t key_net_idx, u16_t key_app_idx, const u8_t app_key[16],
u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 1 + 19 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct app_key_param param = {
.status = status,
.net_idx = key_net_idx,
.app_idx = key_app_idx,
};
int err;
err = cli_prepare(¶m, OP_APP_KEY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_APP_KEY_ADD);
key_idx_pack(&msg, key_net_idx, key_app_idx);
net_buf_simple_add_mem(&msg, app_key, 16);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_app_key_update(u16_t net_idx, u16_t addr, u16_t key_net_idx, u16_t key_app_idx, const u8_t app_key[16],
u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 1 + 19 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct app_key_param param = {
.status = status,
.net_idx = key_net_idx,
.app_idx = key_app_idx,
};
int err;
err = cli_prepare(¶m, OP_APP_KEY_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_APP_KEY_UPDATE);
key_idx_pack(&msg, key_net_idx, key_app_idx);
net_buf_simple_add_mem(&msg, app_key, 16);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
static int mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u16_t cid,
u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_app_param param = {
.status = status,
.elem_addr = elem_addr,
.mod_app_idx = mod_app_idx,
.mod_id = mod_id,
.cid = cid,
};
int err;
err = cli_prepare(¶m, OP_MOD_APP_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_APP_BIND);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_le16(&msg, mod_app_idx);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
static int mod_app_unbind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u16_t cid,
u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_app_param param = {
.status = status,
.elem_addr = elem_addr,
.mod_app_idx = mod_app_idx,
.mod_id = mod_id,
.cid = cid,
};
int err;
err = cli_prepare(¶m, OP_MOD_APP_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_APP_UNBIND);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_le16(&msg, mod_app_idx);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_app_unbind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id,
u8_t *status)
{
return mod_app_unbind(net_idx, addr, elem_addr, mod_app_idx, mod_id, CID_NVAL, status);
}
int bt_mesh_cfg_mod_app_unbind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id,
u16_t cid, u8_t *status)
{
if (cid == CID_NVAL) {
return -EINVAL;
}
return mod_app_unbind(net_idx, addr, elem_addr, mod_app_idx, mod_id, cid, status);
}
int bt_mesh_cfg_mod_app_bind(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u8_t *status)
{
return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, CID_NVAL, status);
}
int bt_mesh_cfg_mod_app_bind_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_app_idx, u16_t mod_id, u16_t cid,
u8_t *status)
{
if (cid == CID_NVAL) {
return -EINVAL;
}
return mod_app_bind(net_idx, addr, elem_addr, mod_app_idx, mod_id, cid, status);
}
static int mod_sub(bt_u32_t op, u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid,
u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 8 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_sub_param param = {
.status = status,
.elem_addr = elem_addr,
.expect_sub = &sub_addr,
.mod_id = mod_id,
.cid = cid,
};
int err;
err = cli_prepare(¶m, OP_MOD_SUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, op);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_le16(&msg, sub_addr);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_sub_add(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u8_t *status)
{
return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, mod_id, CID_NVAL, status);
}
int bt_mesh_cfg_mod_sub_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid,
u8_t *status)
{
if (cid == CID_NVAL) {
return -EINVAL;
}
return mod_sub(OP_MOD_SUB_ADD, net_idx, addr, elem_addr, sub_addr, mod_id, cid, status);
}
int bt_mesh_cfg_mod_sub_del(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u8_t *status)
{
return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, mod_id, CID_NVAL, status);
}
int bt_mesh_cfg_mod_sub_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id, u16_t cid,
u8_t *status)
{
if (cid == CID_NVAL) {
return -EINVAL;
}
return mod_sub(OP_MOD_SUB_DEL, net_idx, addr, elem_addr, sub_addr, mod_id, cid, status);
}
int bt_mesh_cfg_mod_sub_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id,
u8_t *status)
{
return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, sub_addr, mod_id, CID_NVAL, status);
}
int bt_mesh_cfg_mod_sub_overwrite_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t sub_addr, u16_t mod_id,
u16_t cid, u8_t *status)
{
if (cid == CID_NVAL) {
return -EINVAL;
}
return mod_sub(OP_MOD_SUB_OVERWRITE, net_idx, addr, elem_addr, sub_addr, mod_id, cid, status);
}
static int mod_sub_va(bt_u32_t op, u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 22 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_sub_param param = {
.status = status,
.elem_addr = elem_addr,
.sub_addr = virt_addr,
.mod_id = mod_id,
.cid = cid,
};
int err;
err = cli_prepare(¶m, OP_MOD_SUB_STATUS);
if (err) {
return err;
}
BT_DBG("net_idx 0x%04x addr 0x%04x elem_addr 0x%04x label %s", net_idx, addr, elem_addr, label);
BT_DBG("mod_id 0x%04x cid 0x%04x", mod_id, cid);
bt_mesh_model_msg_init(&msg, op);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_mem(&msg, label, 16);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_sub_va_add(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status)
{
if (virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, mod_id, CID_NVAL, virt_addr, status);
}
int bt_mesh_cfg_mod_sub_va_add_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status)
{
if (cid == CID_NVAL || virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_ADD, net_idx, addr, elem_addr, label, mod_id, cid, virt_addr, status);
}
int bt_mesh_cfg_mod_sub_va_del(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status)
{
if (virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, mod_id, CID_NVAL, virt_addr, status);
}
int bt_mesh_cfg_mod_sub_va_del_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status)
{
if (cid == CID_NVAL || virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_DEL, net_idx, addr, elem_addr, label, mod_id, cid, virt_addr, status);
}
int bt_mesh_cfg_mod_sub_va_overwrite(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t *virt_addr, u8_t *status)
{
if (virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, label, mod_id, CID_NVAL, virt_addr, status);
}
int bt_mesh_cfg_mod_sub_va_overwrite_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, const u8_t label[16], u16_t mod_id,
u16_t cid, u16_t *virt_addr, u8_t *status)
{
if (cid == CID_NVAL || virt_addr == NULL) {
return -EINVAL;
}
return mod_sub_va(OP_MOD_SUB_VA_OVERWRITE, net_idx, addr, elem_addr, label, mod_id, cid, virt_addr, status);
}
static int mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 6 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_pub_param param = {
.mod_id = mod_id,
.cid = cid,
.elem_addr = elem_addr,
.status = status,
.pub = pub,
};
int err;
err = cli_prepare(¶m, OP_MOD_PUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_PUB_GET);
net_buf_simple_add_le16(&msg, elem_addr);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_pub_get(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub,
u8_t *status)
{
if ((pub == NULL && status) || (pub && status == NULL)) {
return -EINVAL;
}
return mod_pub_get(net_idx, addr, elem_addr, mod_id, CID_NVAL, pub, status);
}
int bt_mesh_cfg_mod_sub_get(u16_t net_idx, u16_t addr, u16_t mod_id, uint16_t *sub, u8_t *status)
{
if ((sub == NULL && status) || (sub && status == NULL)) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_sub_param param = {
.status = status,
.elem_addr = addr,
.sub_addr = sub,
};
int err;
err = cli_prepare(¶m, OP_MOD_SUB_LIST);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_SUB_GET);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_sub_get_vnd(u16_t net_idx, u16_t addr, u16_t mod_id, u16_t cid, uint16_t *sub, u8_t *status)
{
if ((sub == NULL && status) || (sub && status == NULL)) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 6 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_sub_param param = {
.status = status,
.elem_addr = addr,
.sub_addr = sub,
};
int err;
err = cli_prepare(¶m, OP_MOD_SUB_LIST_VND);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_SUB_GET_VND);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, cid);
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_pub_get_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status)
{
if (cid == CID_NVAL || (pub == NULL && status) || (pub && status == NULL)) {
return -EINVAL;
}
return mod_pub_get(net_idx, addr, elem_addr, mod_id, cid, pub, status);
}
static int mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 13 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct mod_pub_param param = {
.mod_id = mod_id,
.cid = cid,
.elem_addr = elem_addr,
.status = status,
.pub = pub,
};
int err;
err = cli_prepare(¶m, OP_MOD_PUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_MOD_PUB_SET);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_le16(&msg, pub->addr);
net_buf_simple_add_le16(&msg, (pub->app_idx & (pub->cred_flag << 12)));
net_buf_simple_add_u8(&msg, pub->ttl);
net_buf_simple_add_u8(&msg, pub->period);
net_buf_simple_add_u8(&msg, pub->transmit);
if (cid != CID_NVAL) {
net_buf_simple_add_le16(&msg, cid);
}
net_buf_simple_add_le16(&msg, mod_id);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_mod_pub_set(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, struct bt_mesh_cfg_mod_pub *pub,
u8_t *status)
{
if (pub == NULL) {
return -EINVAL;
}
return mod_pub_set(net_idx, addr, elem_addr, mod_id, CID_NVAL, pub, status);
}
int bt_mesh_cfg_mod_pub_set_vnd(u16_t net_idx, u16_t addr, u16_t elem_addr, u16_t mod_id, u16_t cid,
struct bt_mesh_cfg_mod_pub *pub, u8_t *status)
{
if (cid == CID_NVAL || pub == NULL) {
return -EINVAL;
}
return mod_pub_set(net_idx, addr, elem_addr, mod_id, cid, pub, status);
}
int bt_mesh_cfg_hb_sub_set(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_sub *sub, u8_t *status)
{
if (sub == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct hb_sub_param param = {
.status = status,
.sub = sub,
};
int err;
err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_SET);
net_buf_simple_add_le16(&msg, sub->src);
net_buf_simple_add_le16(&msg, sub->dst);
net_buf_simple_add_u8(&msg, sub->period);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_hb_sub_get(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_sub *sub, u8_t *status)
{
if (sub == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct hb_sub_param param = {
.status = status,
.sub = sub,
};
int err;
err = cli_prepare(¶m, OP_HEARTBEAT_SUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_GET);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_hb_pub_set(u16_t net_idx, u16_t addr, const struct bt_mesh_cfg_hb_pub *pub, u8_t *status)
{
if (pub == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct hb_pub_param param = {
.status = status,
};
int err;
err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_SET);
net_buf_simple_add_le16(&msg, pub->dst);
net_buf_simple_add_u8(&msg, pub->count);
net_buf_simple_add_u8(&msg, pub->period);
net_buf_simple_add_u8(&msg, pub->ttl);
net_buf_simple_add_le16(&msg, pub->feat);
net_buf_simple_add_le16(&msg, pub->net_idx);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_hb_pub_get(u16_t net_idx, u16_t addr, struct bt_mesh_cfg_hb_pub *pub, u8_t *status)
{
if (pub == NULL) {
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct hb_pub_param param = {
.status = status,
.pub = pub,
};
int err;
err = cli_prepare(¶m, OP_HEARTBEAT_PUB_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_GET);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
int bt_mesh_cfg_ctrl_relay_get(u16_t net_idx, u16_t addr, struct ctrl_relay_param *cr, u8_t *status)
{
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct cli_cr_param param = {
.status = status,
.cr_p = cr,
};
int err;
err = cli_prepare(¶m, OP_CTRL_RELAY_CONF_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(msg, OP_CTRL_RELAY_CONF_GET);
err = bt_mesh_model_send(cli->model, &ctx, msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_cfg_ctrl_relay_set(u16_t net_idx, u16_t addr, const struct ctrl_relay_param *cr, u8_t *status)
{
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 6 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct cli_cr_param param = {
.status = status,
};
int err;
err = cli_prepare(¶m, OP_CTRL_RELAY_CONF_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(msg, OP_CTRL_RELAY_CONF_SET);
net_buf_simple_add_u8(msg, cr->enable);
net_buf_simple_add_u8(msg, cr->trd_n);
net_buf_simple_add_u8(msg, cr->rssi);
net_buf_simple_add_u8(msg, cr->sta_period);
net_buf_simple_add_u8(msg, cr->chk_period);
net_buf_simple_add_u8(msg, cr->req_period);
err = bt_mesh_model_send(cli->model, &ctx, msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!status) {
cli_reset();
return 0;
}
return cli_wait();
}
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
int bt_mesh_cfg_node_reset(u16_t net_idx, u16_t addr)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BT_MESH_KEY_DEV,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
int err;
err = cli_prepare(NULL, OP_NODE_RESET_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_NODE_RESET);
err = bt_mesh_model_send(cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
return cli_wait();
}
bt_s32_t bt_mesh_cfg_cli_timeout_get(void)
{
return msg_timeout / MSEC_PER_SEC;
}
void bt_mesh_cfg_cli_timeout_set(bt_s32_t timeout)
{
msg_timeout = K_SECONDS(timeout);
}
int bt_mesh_cfg_cli_init(struct bt_mesh_model *model, bool primary)
{
BT_DBG("primary %u", primary);
if (!primary) {
BT_ERR("Configuration Client only allowed in primary element");
return -EINVAL;
}
if (!model || !model->user_data) {
BT_ERR("No Configuration Client context provided");
return -EINVAL;
}
cli = model->user_data;
cli->model = model;
/* Configuration Model security is device-key based */
model->keys[0] = BT_MESH_KEY_DEV;
k_sem_init(&cli->op_sync, 0, 1);
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/cfg_cli.c | C | apache-2.0 | 60,328 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <ble_types/types.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "host/testing.h"
#include "mesh.h"
#include "adv.h"
#include "net.h"
#include "lpn.h"
#include "ble_transport.h"
#include "crypto.h"
#include "access.h"
#include "beacon.h"
#include "proxy.h"
#include "foundation.h"
#include "friend.h"
#include "settings.h"
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
#define DEFAULT_TTL 7
#define CONFIG_ENABLE_MESH_KEY_DUMP 1
static struct bt_mesh_cfg_srv *conf;
static struct label {
u16_t ref;
u16_t addr;
u8_t uuid[16];
} labels[CONFIG_BT_MESH_LABEL_COUNT];
struct bt_mesh_cfg_srv g_cfg_srv = {
.relay = BT_MESH_RELAY_ENABLED,
.beacon = BT_MESH_BEACON_ENABLED,
#if defined(CONFIG_BT_MESH_FRIEND)
.frnd = BT_MESH_FRIEND_ENABLED,
#else
.frnd = BT_MESH_FRIEND_NOT_SUPPORTED,
#endif
#if defined(CONFIG_BT_MESH_GATT_PROXY)
.gatt_proxy = BT_MESH_GATT_PROXY_ENABLED,
#else
.gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED,
#endif
.default_ttl = 7,
/* 3 transmissions with 20ms interval */
.net_transmit = BT_MESH_TRANSMIT(2, 20),
/* 3 transmissions with 60ms interval */
.relay_retransmit = BT_MESH_TRANSMIT(2, 60),
};
struct bt_mesh_cfg_srv *get_cfg_srv()
{
return &g_cfg_srv;
}
static void hb_send(struct bt_mesh_model *model)
{
struct bt_mesh_cfg_srv *cfg = model->user_data;
struct bt_mesh_subnet *sub = NULL;
u16_t feat = 0;
struct __packed {
u8_t init_ttl;
u16_t feat;
} hb;
struct bt_mesh_msg_ctx ctx = {
.net_idx = cfg->hb_pub.net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = cfg->hb_pub.dst,
.send_ttl = cfg->hb_pub.ttl,
};
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if (NULL == sub) {
BT_ERR("Subnet is NULL");
return;
}
struct bt_mesh_net_tx tx = {
.sub = sub,
.ctx = &ctx,
.src = bt_mesh_model_elem(model)->addr,
.xmit = bt_mesh_net_transmit_get(),
};
hb.init_ttl = cfg->hb_pub.ttl;
if (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED) {
feat |= BT_MESH_FEAT_RELAY;
}
if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
feat |= BT_MESH_FEAT_PROXY;
}
if (bt_mesh_friend_get() == BT_MESH_FRIEND_ENABLED) {
feat |= BT_MESH_FEAT_FRIEND;
}
#if defined(CONFIG_BT_MESH_LOW_POWER)
if (bt_mesh.lpn.established) {
feat |= BT_MESH_FEAT_LOW_POWER;
}
#endif
hb.feat = sys_cpu_to_be16(feat);
BT_DBG("InitTTL %u feat 0x%04x", cfg->hb_pub.ttl, feat);
bt_mesh_ctl_send(&tx, TRANS_CTL_OP_HEARTBEAT, &hb, sizeof(hb), NULL, NULL, NULL);
}
static int comp_add_elem(struct net_buf_simple *buf, struct bt_mesh_elem *elem, bool primary)
{
struct bt_mesh_model *mod;
int i;
if (net_buf_simple_tailroom(buf) < 4 + (elem->model_count * 2) + (elem->vnd_model_count * 2)) {
BT_ERR("Too large device composition");
return -E2BIG;
}
net_buf_simple_add_le16(buf, elem->loc);
net_buf_simple_add_u8(buf, elem->model_count);
net_buf_simple_add_u8(buf, elem->vnd_model_count);
for (i = 0; i < elem->model_count; i++) {
mod = &elem->models[i];
net_buf_simple_add_le16(buf, mod->id);
}
for (i = 0; i < elem->vnd_model_count; i++) {
mod = &elem->vnd_models[i];
net_buf_simple_add_le16(buf, mod->vnd.company);
net_buf_simple_add_le16(buf, mod->vnd.id);
}
return 0;
}
static int comp_get_page_0(struct net_buf_simple *buf)
{
u16_t feat = 0;
const struct bt_mesh_comp *comp;
int i;
comp = bt_mesh_comp_get();
if (IS_ENABLED(CONFIG_BT_MESH_RELAY)) {
feat |= BT_MESH_FEAT_RELAY;
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
feat |= BT_MESH_FEAT_PROXY;
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
feat |= BT_MESH_FEAT_FRIEND;
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
feat |= BT_MESH_FEAT_LOW_POWER;
}
net_buf_simple_add_le16(buf, comp->cid);
net_buf_simple_add_le16(buf, comp->pid);
net_buf_simple_add_le16(buf, comp->vid);
net_buf_simple_add_le16(buf, CONFIG_BT_MESH_CRPL);
net_buf_simple_add_le16(buf, feat);
for (i = 0; i < comp->elem_count; i++) {
int err;
err = comp_add_elem(buf, &comp->elem[i], i == 0);
if (err) {
return err;
}
}
return 0;
}
static void dev_comp_data_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
u8_t page;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
page = net_buf_simple_pull_u8(buf);
if (page != 0) {
BT_WARN("Composition page %u not available", page);
page = 0;
}
bt_mesh_model_msg_init(&sdu, OP_DEV_COMP_DATA_STATUS);
net_buf_simple_add_u8(&sdu, page);
if (comp_get_page_0(&sdu) < 0) {
BT_ERR("Unable to get composition page 0");
return;
}
if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) {
BT_ERR("Unable to send Device Composition Status response");
}
}
static struct bt_mesh_model *get_model(struct bt_mesh_elem *elem, struct net_buf_simple *buf, bool *vnd)
{
if (buf->len < 4) {
u16_t id;
id = net_buf_simple_pull_le16(buf);
BT_DBG("ID 0x%04x addr 0x%04x", id, elem->addr);
*vnd = false;
return bt_mesh_model_find(elem, id);
} else {
u16_t company, id;
company = net_buf_simple_pull_le16(buf);
id = net_buf_simple_pull_le16(buf);
BT_DBG("Company 0x%04x ID 0x%04x addr 0x%04x", company, id, elem->addr);
*vnd = true;
return bt_mesh_model_find_vnd(elem, company, id);
}
}
static bool app_key_is_valid(u16_t app_idx)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx != BT_MESH_KEY_UNUSED && key->app_idx == app_idx) {
return true;
}
}
return false;
}
static u8_t _mod_pub_set(struct bt_mesh_model *model, u16_t pub_addr, u16_t app_idx, u8_t cred_flag, u8_t ttl,
u8_t period, u8_t retransmit, bool store)
{
if (!model->pub) {
return STATUS_NVAL_PUB_PARAM;
}
if (!IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && cred_flag) {
return STATUS_FEAT_NOT_SUPP;
}
if (!model->pub->update && period) {
return STATUS_NVAL_PUB_PARAM;
}
if (pub_addr == BT_MESH_ADDR_UNASSIGNED) {
if (model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return STATUS_SUCCESS;
}
model->pub->addr = BT_MESH_ADDR_UNASSIGNED;
model->pub->key = 0;
model->pub->cred = 0;
model->pub->ttl = 0;
model->pub->period = 0;
model->pub->retransmit = 0;
model->pub->count = 0;
if (model->pub->update) {
k_delayed_work_cancel(&model->pub->timer);
}
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_store_mod_pub(model);
}
return STATUS_SUCCESS;
}
if (!bt_mesh_app_key_find(app_idx)) {
return STATUS_INVALID_APPKEY;
}
model->pub->addr = pub_addr;
model->pub->key = app_idx;
model->pub->cred = cred_flag;
model->pub->ttl = ttl;
model->pub->period = period;
model->pub->retransmit = retransmit;
if (model->pub->update) {
bt_s32_t period_ms;
period_ms = bt_mesh_model_pub_period_get(model);
BT_DBG("period %u ms", period_ms);
if (period_ms) {
k_delayed_work_submit(&model->pub->timer, period_ms);
} else {
k_delayed_work_cancel(&model->pub->timer);
}
}
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_store_mod_pub(model);
}
return STATUS_SUCCESS;
}
u8_t mod_bind(struct bt_mesh_model *model, u16_t key_idx)
{
int i;
BT_DBG("model %p key_idx 0x%03x", model, key_idx);
if (!app_key_is_valid(key_idx)) {
return STATUS_INVALID_APPKEY;
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
/* Treat existing binding as success */
if (model->keys[i] == key_idx) {
return STATUS_SUCCESS;
}
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
if (model->keys[i] == BT_MESH_KEY_UNUSED) {
model->keys[i] = key_idx;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_bind(model);
}
return STATUS_SUCCESS;
}
}
return STATUS_INSUFF_RESOURCES;
}
u8_t mod_unbind(struct bt_mesh_model *model, u16_t key_idx, bool store)
{
int i;
BT_DBG("model %p key_idx 0x%03x store %u", model, key_idx, store);
if (!app_key_is_valid(key_idx)) {
return STATUS_INVALID_APPKEY;
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
if (model->keys[i] != key_idx) {
continue;
}
model->keys[i] = BT_MESH_KEY_UNUSED;
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_store_mod_bind(model);
}
if (model->pub && model->pub->key == key_idx) {
_mod_pub_set(model, BT_MESH_ADDR_UNASSIGNED, 0, 0, 0, 0, 0, store);
}
}
return STATUS_SUCCESS;
}
struct bt_mesh_app_key *bt_mesh_app_key_alloc(u16_t app_idx)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx == BT_MESH_KEY_UNUSED) {
return key;
}
}
return NULL;
}
static u8_t app_key_set(u16_t net_idx, u16_t app_idx, const u8_t val[16], bool update)
{
struct bt_mesh_app_keys *keys;
struct bt_mesh_app_key *key;
struct bt_mesh_subnet *sub;
BT_DBG("net_idx 0x%04x app_idx %04x update %u val %s", net_idx, app_idx, update, bt_hex(val, 16));
sub = bt_mesh_subnet_get(net_idx);
if (!sub) {
return STATUS_INVALID_NETKEY;
}
if (CONFIG_ENABLE_MESH_KEY_DUMP) {
printf("netkey %d:%s\r\n", net_idx, bt_hex(sub->keys[0].net, 16));
printf("devkey:%s\r\n", bt_hex(bt_mesh.dev_key, 16));
printf("appkey %d:%s\r\n", app_idx, bt_hex(val, 16));
}
key = bt_mesh_app_key_find(app_idx);
if (update) {
if (!key) {
return STATUS_INVALID_APPKEY;
}
if (key->net_idx != net_idx) {
return STATUS_INVALID_BINDING;
}
keys = &key->keys[1];
/* The AppKey Update message shall generate an error when node
* is in normal operation, Phase 2, or Phase 3 or in Phase 1
* when the AppKey Update message on a valid AppKeyIndex when
* the AppKey value is different.
*/
if (sub->kr_phase != BT_MESH_KR_PHASE_1) {
return STATUS_CANNOT_UPDATE;
}
if (key->updated) {
if (memcmp(keys->val, val, 16)) {
return STATUS_CANNOT_UPDATE;
} else {
return STATUS_SUCCESS;
}
}
key->updated = true;
} else {
if (key) {
if (key->net_idx == net_idx && !memcmp(key->keys[0].val, val, 16)) {
return STATUS_SUCCESS;
}
if (key->net_idx == net_idx) {
return STATUS_IDX_ALREADY_STORED;
} else {
return STATUS_INVALID_NETKEY;
}
}
key = bt_mesh_app_key_alloc(app_idx);
if (!key) {
return STATUS_INSUFF_RESOURCES;
}
keys = &key->keys[0];
}
if (bt_mesh_app_id(val, &keys->id)) {
if (update) {
key->updated = false;
}
return STATUS_STORAGE_FAIL;
}
BT_DBG("app_idx 0x%04x AID 0x%02x", app_idx, keys->id);
key->net_idx = net_idx;
key->app_idx = app_idx;
memcpy(keys->val, val, 16);
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
printf("Storing AppKey persistently\n");
bt_mesh_store_app_key(key, 0);
}
return STATUS_SUCCESS;
}
#ifdef CONFIG_GENIE_MESH_ENABLE
s8_t genie_mesh_setup(void)
{
struct bt_mesh_elem *elem;
struct bt_mesh_model *mod;
u8_t elem_cnt, i, j, status;
u16_t primary_addr;
u16_t key_app_idx = 0;
elem_cnt = bt_mesh_elem_count();
primary_addr = bt_mesh_primary_addr();
BT_DBG("start elem %d primary addr %04x", elem_cnt, primary_addr);
for (i = 0; i < elem_cnt; i++) {
elem = bt_mesh_elem_find(primary_addr + i);
if (!elem) {
BT_ERR("can not find elem for addr %d", primary_addr + i);
return -1;
}
for (j = 0; j < elem->model_count; j++) {
mod = bt_mesh_model_find(elem, elem->models[j].id);
status = mod_bind(mod, key_app_idx);
BT_DBG(">>>model %04x app_key[%02x]<<<", elem->models[j].id, status);
}
for (j = 0; j < elem->vnd_model_count; j++) {
mod = bt_mesh_model_find_vnd(elem, elem->vnd_models[j].vnd.company, elem->vnd_models[j].vnd.id);
status = mod_bind(mod, key_app_idx);
BT_DBG(">>>model %04x %04x app_key[%02x]<<<", elem->vnd_models[j].vnd.company, elem->vnd_models[j].vnd.id,
status);
}
}
(void)status;
return 0;
}
#endif
static void app_key_add(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
u16_t key_net_idx, key_app_idx;
u8_t status;
key_idx_unpack(buf, &key_net_idx, &key_app_idx);
BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx);
bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS);
status = app_key_set(key_net_idx, key_app_idx, buf->data, false);
BT_DBG("status 0x%02x", status);
net_buf_simple_add_u8(&msg, status);
key_idx_pack(&msg, key_net_idx, key_app_idx);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send App Key Status response");
}
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
appkey_status add_status = {
.status = status,
.netkey_idx = key_net_idx,
.appkey_idx = key_app_idx,
};
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_APPKEY_ADD, &add_status);
}
#endif
}
static void app_key_update(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
u16_t key_net_idx, key_app_idx;
u8_t status;
key_idx_unpack(buf, &key_net_idx, &key_app_idx);
BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx);
bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS);
status = app_key_set(key_net_idx, key_app_idx, buf->data, true);
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_APPKEY_UPDATE, &status);
}
#endif
BT_DBG("status 0x%02x", status);
net_buf_simple_add_u8(&msg, status);
key_idx_pack(&msg, key_net_idx, key_app_idx);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send App Key Status response");
}
}
struct unbind_data {
u16_t app_idx;
bool store;
};
static void _mod_unbind(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
struct unbind_data *data = user_data;
mod_unbind(mod, data->app_idx, data->store);
}
void bt_mesh_app_key_del(struct bt_mesh_app_key *key, bool store)
{
struct unbind_data data = { .app_idx = key->app_idx, .store = store };
BT_DBG("AppIdx 0x%03x store %u", key->app_idx, store);
bt_mesh_model_foreach(_mod_unbind, &data);
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_clear_app_key(key, 0);
}
key->net_idx = BT_MESH_KEY_UNUSED;
memset(key->keys, 0, sizeof(key->keys));
}
static void app_key_del(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
u16_t key_net_idx, key_app_idx;
struct bt_mesh_app_key *key;
u8_t status;
key_idx_unpack(buf, &key_net_idx, &key_app_idx);
BT_DBG("AppIdx 0x%04x NetIdx 0x%04x", key_app_idx, key_net_idx);
if (!bt_mesh_subnet_get(key_net_idx)) {
status = STATUS_INVALID_NETKEY;
goto send_status;
}
key = bt_mesh_app_key_find(key_app_idx);
if (!key) {
/* Treat as success since the client might have missed a
* previous response and is resending the request.
*/
status = STATUS_SUCCESS;
goto send_status;
}
if (key->net_idx != key_net_idx) {
status = STATUS_INVALID_BINDING;
goto send_status;
}
bt_mesh_app_key_del(key, true);
status = STATUS_SUCCESS;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_APPKEY_DEL, &status);
}
#endif
send_status:
bt_mesh_model_msg_init(&msg, OP_APP_KEY_STATUS);
net_buf_simple_add_u8(&msg, status);
key_idx_pack(&msg, key_net_idx, key_app_idx);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send App Key Status response");
}
}
/* Index list length: 3 bytes for every pair and 2 bytes for an odd idx */
#define IDX_LEN(num) (((num) / 2) * 3 + ((num) % 2) * 2)
static void app_key_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4 + IDX_LEN(CONFIG_BT_MESH_APP_KEY_COUNT));
u16_t get_idx, i, prev;
u8_t status;
get_idx = net_buf_simple_pull_le16(buf);
if (get_idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", get_idx);
return;
}
BT_DBG("idx 0x%04x", get_idx);
bt_mesh_model_msg_init(&msg, OP_APP_KEY_LIST);
if (!bt_mesh_subnet_get(get_idx)) {
status = STATUS_INVALID_NETKEY;
} else {
status = STATUS_SUCCESS;
}
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, get_idx);
if (status != STATUS_SUCCESS) {
goto send_status;
}
prev = BT_MESH_KEY_UNUSED;
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx != get_idx) {
continue;
}
if (prev == BT_MESH_KEY_UNUSED) {
prev = key->app_idx;
continue;
}
key_idx_pack(&msg, prev, key->app_idx);
prev = BT_MESH_KEY_UNUSED;
}
if (prev != BT_MESH_KEY_UNUSED) {
net_buf_simple_add_le16(&msg, prev);
}
send_status:
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send AppKey List");
}
}
static void beacon_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_beacon_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Config Beacon Status response");
}
}
static void beacon_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (!cfg) {
BT_WARN("No Configuration Server context available");
} else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) {
if (buf->data[0] != cfg->beacon) {
cfg->beacon = buf->data[0];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
if (cfg->beacon) {
bt_mesh_beacon_enable();
} else {
bt_mesh_beacon_disable();
}
}
} else {
BT_WARN("Invalid Config Beacon value 0x%02x", buf->data[0]);
return;
}
bt_mesh_model_msg_init(&msg, OP_BEACON_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_beacon_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Config Beacon Status response");
}
}
static void default_ttl_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Default TTL Status response");
}
}
static void default_ttl_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (!cfg) {
BT_WARN("No Configuration Server context available");
} else if (buf->data[0] <= BT_MESH_TTL_MAX && buf->data[0] != 0x01) {
if (cfg->default_ttl != buf->data[0]) {
cfg->default_ttl = buf->data[0];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
}
} else {
BT_WARN("Prohibited Default TTL value 0x%02x", buf->data[0]);
return;
}
bt_mesh_model_msg_init(&msg, OP_DEFAULT_TTL_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_default_ttl_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Default TTL Status response");
}
}
static void send_gatt_proxy_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
bt_mesh_model_msg_init(&msg, OP_GATT_PROXY_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_gatt_proxy_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send GATT Proxy Status");
}
}
static void gatt_proxy_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
send_gatt_proxy_status(model, ctx);
}
static void gatt_proxy_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_cfg_srv *cfg = model->user_data;
struct bt_mesh_subnet *sub;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (buf->data[0] != 0x00 && buf->data[0] != 0x01) {
BT_WARN("Invalid GATT Proxy value 0x%02x", buf->data[0]);
return;
}
if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) || bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_NOT_SUPPORTED) {
goto send_status;
}
if (!cfg) {
BT_WARN("No Configuration Server context available");
goto send_status;
}
BT_DBG("GATT Proxy 0x%02x -> 0x%02x", cfg->gatt_proxy, buf->data[0]);
if (cfg->gatt_proxy == buf->data[0]) {
goto send_status;
}
cfg->gatt_proxy = buf->data[0];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
if (cfg->gatt_proxy == BT_MESH_GATT_PROXY_DISABLED) {
int i;
/* Section 4.2.11.1: "When the GATT Proxy state is set to
* 0x00, the Node Identity state for all subnets shall be set
* to 0x00 and shall not be changed."
*/
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx != BT_MESH_KEY_UNUSED) {
bt_mesh_proxy_identity_stop(sub);
}
}
/* Section 4.2.11: "Upon transition from GATT Proxy state 0x01
* to GATT Proxy state 0x00 the GATT Bearer Server shall
* disconnect all GATT Bearer Clients.
*/
bt_mesh_proxy_gatt_disconnect();
}
bt_mesh_adv_update();
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if ((cfg->hb_pub.feat & BT_MESH_FEAT_PROXY) && sub) {
hb_send(model);
}
send_status:
send_gatt_proxy_status(model, ctx);
}
static void net_transmit_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Config Network Transmit Status");
}
}
static void net_transmit_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
BT_DBG("Transmit 0x%02x (count %u interval %ums)", buf->data[0], BT_MESH_TRANSMIT_COUNT(buf->data[0]),
BT_MESH_TRANSMIT_INT(buf->data[0]));
if (!cfg) {
BT_WARN("No Configuration Server context available");
} else {
cfg->net_transmit = buf->data[0];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
}
bt_mesh_model_msg_init(&msg, OP_NET_TRANSMIT_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_net_transmit_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Network Transmit Status");
}
}
static void relay_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_relay_get());
net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Config Relay Status response");
}
}
static void relay_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (!cfg) {
BT_WARN("No Configuration Server context available");
} else if (buf->data[0] == 0x00 || buf->data[0] == 0x01) {
struct bt_mesh_subnet *sub;
bool change;
if (cfg->relay == BT_MESH_RELAY_NOT_SUPPORTED) {
change = false;
} else {
change = (cfg->relay != buf->data[0]);
cfg->relay = buf->data[0];
cfg->relay_retransmit = buf->data[1];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
}
BT_DBG("Relay 0x%02x (%s) xmit 0x%02x (count %u interval %u)", cfg->relay, change ? "changed" : "not changed",
cfg->relay_retransmit, BT_MESH_TRANSMIT_COUNT(cfg->relay_retransmit),
BT_MESH_TRANSMIT_INT(cfg->relay_retransmit));
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if ((cfg->hb_pub.feat & BT_MESH_FEAT_RELAY) && sub && change) {
hb_send(model);
}
} else {
BT_WARN("Invalid Relay value 0x%02x", buf->data[0]);
return;
}
bt_mesh_model_msg_init(&msg, OP_RELAY_STATUS);
net_buf_simple_add_u8(&msg, bt_mesh_relay_get());
net_buf_simple_add_u8(&msg, bt_mesh_relay_retransmit_get());
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Relay Status response");
}
}
static void send_mod_pub_status(struct bt_mesh_model *cfg_mod, struct bt_mesh_msg_ctx *ctx, u16_t elem_addr,
u16_t pub_addr, bool vnd, struct bt_mesh_model *mod, u8_t status, u8_t *mod_id)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 14 + 4);
bt_mesh_model_msg_init(&msg, OP_MOD_PUB_STATUS);
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, elem_addr);
if (status != STATUS_SUCCESS) {
memset(net_buf_simple_add(&msg, 7), 0, 7);
} else {
u16_t idx_cred;
net_buf_simple_add_le16(&msg, pub_addr);
idx_cred = mod->pub->key | (u16_t)mod->pub->cred << 12;
net_buf_simple_add_le16(&msg, idx_cred);
net_buf_simple_add_u8(&msg, mod->pub->ttl);
net_buf_simple_add_u8(&msg, mod->pub->period);
net_buf_simple_add_u8(&msg, mod->pub->retransmit);
}
if (vnd) {
memcpy(net_buf_simple_add(&msg, 4), mod_id, 4);
} else {
memcpy(net_buf_simple_add(&msg, 2), mod_id, 2);
}
if (bt_mesh_model_send(cfg_mod, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model Publication Status");
}
}
static void mod_pub_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, pub_addr = 0;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id, status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
mod_id = buf->data;
BT_DBG("elem_addr 0x%04x", elem_addr);
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (!mod->pub) {
status = STATUS_NVAL_PUB_PARAM;
goto send_status;
}
pub_addr = mod->pub->addr;
status = STATUS_SUCCESS;
send_status:
send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, status, mod_id);
}
static void mod_pub_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u8_t retransmit, status, pub_ttl, pub_period, cred_flag;
u16_t elem_addr, pub_addr, pub_app_idx;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
pub_addr = net_buf_simple_pull_le16(buf);
pub_app_idx = net_buf_simple_pull_le16(buf);
cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1));
pub_app_idx &= BIT_MASK(12);
pub_ttl = net_buf_simple_pull_u8(buf);
if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) {
BT_ERR("Invalid TTL value 0x%02x", pub_ttl);
return;
}
pub_period = net_buf_simple_pull_u8(buf);
retransmit = net_buf_simple_pull_u8(buf);
mod_id = buf->data;
BT_DBG("elem_addr 0x%04x pub_addr 0x%04x cred_flag %u", elem_addr, pub_addr, cred_flag);
BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", pub_app_idx, pub_ttl, pub_period);
BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, BT_MESH_PUB_TRANSMIT_COUNT(retransmit),
BT_MESH_PUB_TRANSMIT_INT(retransmit));
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, pub_ttl, pub_period, retransmit, true);
send_status:
send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, status, mod_id);
}
#if CONFIG_BT_MESH_LABEL_COUNT > 0
static u8_t va_add(u8_t *label_uuid, u16_t *addr)
{
struct label *free_slot = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(labels); i++) {
if (!labels[i].ref) {
free_slot = &labels[i];
continue;
}
if (!memcmp(labels[i].uuid, label_uuid, 16)) {
*addr = labels[i].addr;
labels[i].ref++;
return STATUS_SUCCESS;
}
}
if (!free_slot) {
return STATUS_INSUFF_RESOURCES;
}
if (bt_mesh_virtual_addr(label_uuid, addr) < 0) {
return STATUS_UNSPECIFIED;
}
free_slot->ref = 1;
free_slot->addr = *addr;
memcpy(free_slot->uuid, label_uuid, 16);
return STATUS_SUCCESS;
}
static u8_t va_del(u8_t *label_uuid, u16_t *addr)
{
int i;
for (i = 0; i < ARRAY_SIZE(labels); i++) {
if (!memcmp(labels[i].uuid, label_uuid, 16)) {
if (addr) {
*addr = labels[i].addr;
}
labels[i].ref--;
return STATUS_SUCCESS;
}
}
if (addr) {
*addr = BT_MESH_ADDR_UNASSIGNED;
}
return STATUS_CANNOT_REMOVE;
}
static size_t mod_sub_list_clear(struct bt_mesh_model *mod)
{
u8_t *label_uuid;
size_t clear_count;
int i;
/* Unref stored labels related to this model */
for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (!BT_MESH_ADDR_IS_VIRTUAL(mod->groups[i])) {
if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) {
mod->groups[i] = BT_MESH_ADDR_UNASSIGNED;
clear_count++;
}
continue;
}
label_uuid = bt_mesh_label_uuid_get(mod->groups[i]);
mod->groups[i] = BT_MESH_ADDR_UNASSIGNED;
clear_count++;
if (label_uuid) {
va_del(label_uuid, NULL);
} else {
BT_ERR("Label UUID not found");
}
}
return clear_count;
}
static void mod_pub_va_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u8_t retransmit, status, pub_ttl, pub_period, cred_flag;
u16_t elem_addr, pub_addr, pub_app_idx;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *label_uuid;
u8_t *mod_id;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
label_uuid = net_buf_simple_pull_mem(buf, 16);
pub_app_idx = net_buf_simple_pull_le16(buf);
cred_flag = ((pub_app_idx >> 12) & BIT_MASK(1));
pub_app_idx &= BIT_MASK(12);
pub_ttl = net_buf_simple_pull_u8(buf);
if (pub_ttl > BT_MESH_TTL_MAX && pub_ttl != BT_MESH_TTL_DEFAULT) {
BT_ERR("Invalid TTL value 0x%02x", pub_ttl);
return;
}
pub_period = net_buf_simple_pull_u8(buf);
retransmit = net_buf_simple_pull_u8(buf);
mod_id = buf->data;
BT_DBG("elem_addr 0x%04x cred_flag %u", elem_addr, cred_flag);
BT_DBG("pub_app_idx 0x%03x, pub_ttl %u pub_period 0x%02x", pub_app_idx, pub_ttl, pub_period);
BT_DBG("retransmit 0x%02x (count %u interval %ums)", retransmit, BT_MESH_PUB_TRANSMIT_COUNT(retransmit),
BT_MESH_PUB_TRANSMIT_INT(retransmit));
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
pub_addr = 0;
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
pub_addr = 0;
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = va_add(label_uuid, &pub_addr);
if (status == STATUS_SUCCESS) {
status = _mod_pub_set(mod, pub_addr, pub_app_idx, cred_flag, pub_ttl, pub_period, retransmit, true);
}
send_status:
send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, status, mod_id);
}
#else
static size_t mod_sub_list_clear(struct bt_mesh_model *mod)
{
size_t clear_count;
int i;
/* Unref stored labels related to this model */
for (i = 0, clear_count = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) {
mod->groups[i] = BT_MESH_ADDR_UNASSIGNED;
clear_count++;
}
}
return clear_count;
}
static void mod_pub_va_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u8_t *mod_id, status;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u16_t elem_addr, pub_addr = 0;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
net_buf_simple_pull(buf, 16);
mod_id = net_buf_simple_pull(buf, 4);
BT_DBG("elem_addr 0x%04x", elem_addr);
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (!mod->pub) {
status = STATUS_NVAL_PUB_PARAM;
goto send_status;
}
pub_addr = mod->pub->addr;
status = STATUS_INSUFF_RESOURCES;
send_status:
send_mod_pub_status(model, ctx, elem_addr, pub_addr, vnd, mod, status, mod_id);
}
#endif /* CONFIG_BT_MESH_LABEL_COUNT > 0 */
static void send_mod_sub_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, u8_t status, u16_t elem_addr,
u16_t sub_addr, u8_t *mod_id, bool vnd)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4);
BT_DBG("status 0x%02x elem_addr 0x%04x sub_addr 0x%04x", status, elem_addr, sub_addr);
bt_mesh_model_msg_init(&msg, OP_MOD_SUB_STATUS);
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, elem_addr);
net_buf_simple_add_le16(&msg, sub_addr);
if (vnd) {
memcpy(net_buf_simple_add(&msg, 4), mod_id, 4);
} else {
memcpy(net_buf_simple_add(&msg, 2), mod_id, 2);
}
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model Subscription Status");
}
}
static void mod_sub_add(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
sub_addr = net_buf_simple_pull_le16(buf);
BT_DBG("elem_addr 0x%04x, sub_addr 0x%04x", elem_addr, sub_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = bt_mesh_mod_sub_add(mod, sub_addr);
send_status:
#ifdef CONFIG_GENIE_MESH_GLP
k_sleep(1300);
#endif
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
static void mod_sub_del(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id;
u16_t *match;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
sub_addr = net_buf_simple_pull_le16(buf);
BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) {
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
/* An attempt to remove a non-existing address shall be treated
* as a success.
*/
status = STATUS_SUCCESS;
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_del(&sub_addr, 1);
}
match = bt_mesh_model_find_group(mod, sub_addr);
if (match) {
*match = BT_MESH_ADDR_UNASSIGNED;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
}
send_status:
#ifdef CONFIG_GENIE_MESH_GLP
k_sleep(1300);
#endif
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
static void mod_sub_overwrite(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
sub_addr = net_buf_simple_pull_le16(buf);
BT_DBG("elem_addr 0x%04x sub_addr 0x%04x", elem_addr, sub_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) {
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups));
}
mod_sub_list_clear(mod);
if (ARRAY_SIZE(mod->groups) > 0) {
mod->groups[0] = sub_addr;
status = STATUS_SUCCESS;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_add(sub_addr);
}
} else {
status = STATUS_INSUFF_RESOURCES;
}
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
static void mod_sub_del_all(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u16_t elem_addr;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
BT_DBG("elem_addr 0x%04x", elem_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups));
}
mod_sub_list_clear(mod);
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
status = STATUS_SUCCESS;
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, BT_MESH_ADDR_UNASSIGNED, mod_id, vnd);
}
static void mod_sub_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4 + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2);
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u16_t addr, id;
int i;
addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(addr)) {
BT_WARN("Prohibited element address");
return;
}
id = net_buf_simple_pull_le16(buf);
BT_DBG("addr 0x%04x id 0x%04x", addr, id);
bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST);
elem = bt_mesh_elem_find(addr);
if (!elem) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, id);
goto send_list;
}
mod = bt_mesh_model_find(elem, id);
if (!mod) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, id);
goto send_list;
}
net_buf_simple_add_u8(&msg, STATUS_SUCCESS);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, id);
for (i = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) {
net_buf_simple_add_le16(&msg, mod->groups[i]);
}
}
send_list:
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model Subscription List");
}
}
static void mod_sub_get_vnd(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 7 + 4 + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2);
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u16_t company, addr, id;
int i;
addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(addr)) {
BT_WARN("Prohibited element address");
return;
}
company = net_buf_simple_pull_le16(buf);
id = net_buf_simple_pull_le16(buf);
BT_DBG("addr 0x%04x company 0x%04x id 0x%04x", addr, company, id);
bt_mesh_model_msg_init(&msg, OP_MOD_SUB_LIST_VND);
elem = bt_mesh_elem_find(addr);
if (!elem) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_ADDRESS);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, company);
net_buf_simple_add_le16(&msg, id);
goto send_list;
}
mod = bt_mesh_model_find_vnd(elem, company, id);
if (!mod) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_MODEL);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, company);
net_buf_simple_add_le16(&msg, id);
goto send_list;
}
net_buf_simple_add_u8(&msg, STATUS_SUCCESS);
net_buf_simple_add_le16(&msg, addr);
net_buf_simple_add_le16(&msg, company);
net_buf_simple_add_le16(&msg, id);
for (i = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) {
net_buf_simple_add_le16(&msg, mod->groups[i]);
}
}
send_list:
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Vendor Model Subscription List");
}
}
#if CONFIG_BT_MESH_LABEL_COUNT > 0
static void mod_sub_va_add(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *label_uuid;
u8_t *mod_id;
u8_t status;
bool vnd;
int i;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
label_uuid = net_buf_simple_pull_mem(buf, 16);
BT_DBG("elem_addr 0x%04x", elem_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
sub_addr = BT_MESH_ADDR_UNASSIGNED;
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
sub_addr = BT_MESH_ADDR_UNASSIGNED;
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = va_add(label_uuid, &sub_addr);
if (status != STATUS_SUCCESS) {
goto send_status;
}
if (bt_mesh_model_find_group(mod, sub_addr)) {
/* Tried to add existing subscription */
status = STATUS_SUCCESS;
goto send_status;
}
for (i = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] == BT_MESH_ADDR_UNASSIGNED) {
mod->groups[i] = sub_addr;
break;
}
}
if (i == ARRAY_SIZE(mod->groups)) {
status = STATUS_INSUFF_RESOURCES;
} else {
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_add(sub_addr);
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
status = STATUS_SUCCESS;
}
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
static void mod_sub_va_del(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *label_uuid;
u8_t *mod_id;
u16_t *match;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
label_uuid = net_buf_simple_pull_mem(buf, 16);
BT_DBG("elem_addr 0x%04x", elem_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
sub_addr = BT_MESH_ADDR_UNASSIGNED;
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
sub_addr = BT_MESH_ADDR_UNASSIGNED;
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = va_del(label_uuid, &sub_addr);
if (sub_addr == BT_MESH_ADDR_UNASSIGNED) {
goto send_status;
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_del(&sub_addr, 1);
}
match = bt_mesh_model_find_group(mod, sub_addr);
if (match) {
*match = BT_MESH_ADDR_UNASSIGNED;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
status = STATUS_SUCCESS;
} else {
status = STATUS_CANNOT_REMOVE;
}
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
static void mod_sub_va_overwrite(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
u16_t elem_addr, sub_addr = BT_MESH_ADDR_UNASSIGNED;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *label_uuid;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
label_uuid = net_buf_simple_pull_mem(buf, 16);
BT_DBG("elem_addr 0x%04x", elem_addr);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_del(mod->groups, ARRAY_SIZE(mod->groups));
}
mod_sub_list_clear(mod);
if (ARRAY_SIZE(mod->groups) > 0) {
status = va_add(label_uuid, &sub_addr);
if (status == STATUS_SUCCESS) {
mod->groups[0] = sub_addr;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(mod);
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_add(sub_addr);
}
}
} else {
status = STATUS_INSUFF_RESOURCES;
}
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, sub_addr, mod_id, vnd);
}
#else
static void mod_sub_va_add(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u16_t elem_addr;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
net_buf_simple_pull(buf, 16);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = STATUS_INSUFF_RESOURCES;
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, BT_MESH_ADDR_UNASSIGNED, mod_id, vnd);
}
static void mod_sub_va_del(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_elem *elem;
u16_t elem_addr;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
net_buf_simple_pull(buf, 16);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
if (!get_model(elem, buf, &vnd)) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = STATUS_INSUFF_RESOURCES;
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, BT_MESH_ADDR_UNASSIGNED, mod_id, vnd);
}
static void mod_sub_va_overwrite(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_elem *elem;
u16_t elem_addr;
u8_t *mod_id;
u8_t status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
net_buf_simple_pull(buf, 18);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
if (!get_model(elem, buf, &vnd)) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = STATUS_INSUFF_RESOURCES;
send_status:
send_mod_sub_status(model, ctx, status, elem_addr, BT_MESH_ADDR_UNASSIGNED, mod_id, vnd);
}
#endif /* CONFIG_BT_MESH_LABEL_COUNT > 0 */
static void send_net_key_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, u16_t idx, u8_t status)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4);
bt_mesh_model_msg_init(&msg, OP_NET_KEY_STATUS);
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, idx);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send NetKey Status");
}
}
static void net_key_add(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
u16_t idx;
int err;
u8_t status;
idx = net_buf_simple_pull_le16(buf);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
BT_DBG("idx 0x%04x", idx);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) {
sub = &bt_mesh.sub[i];
break;
}
}
if (!sub) {
status = STATUS_INSUFF_RESOURCES;
goto add_send_status;
}
}
/* Check for already existing subnet */
if (sub->net_idx == idx) {
u8_t status;
if (memcmp(buf->data, sub->keys[0].net, 16)) {
status = STATUS_IDX_ALREADY_STORED;
} else {
status = STATUS_SUCCESS;
}
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NETKEY_ADD, &status);
}
#endif
send_net_key_status(model, ctx, idx, status);
return;
}
err = bt_mesh_net_keys_create(&sub->keys[0], buf->data);
if (err) {
status = STATUS_UNSPECIFIED;
goto add_send_status;
}
sub->net_idx = idx;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
printf("Storing NetKey persistently\n");
bt_mesh_store_subnet(sub, 0);
}
/* Make sure we have valid beacon data to be sent */
bt_mesh_net_beacon_update(sub);
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
bt_mesh_proxy_beacon_send(sub);
bt_mesh_adv_update();
} else {
sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
}
status = STATUS_SUCCESS;
add_send_status:
send_net_key_status(model, ctx, idx, status);
}
static void net_key_update(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
u16_t idx;
int err;
u8_t status;
idx = net_buf_simple_pull_le16(buf);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
BT_DBG("idx 0x%04x", idx);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
status = STATUS_INVALID_NETKEY;
goto update_send_status;
}
/* The node shall successfully process a NetKey Update message on a
* valid NetKeyIndex when the NetKey value is different and the Key
* Refresh procedure has not been started, or when the NetKey value is
* the same in Phase 1. The NetKey Update message shall generate an
* error when the node is in Phase 2, or Phase 3.
*/
switch (sub->kr_phase) {
case BT_MESH_KR_NORMAL:
if (!memcmp(buf->data, sub->keys[0].net, 16)) {
return;
}
break;
case BT_MESH_KR_PHASE_1:
if (!memcmp(buf->data, sub->keys[1].net, 16)) {
status = STATUS_SUCCESS;
goto update_send_status;
}
/* fall through */
case BT_MESH_KR_PHASE_2:
case BT_MESH_KR_PHASE_3:
status = STATUS_CANNOT_UPDATE;
goto update_send_status;
}
err = bt_mesh_net_keys_create(&sub->keys[1], buf->data);
if (!err && (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || IS_ENABLED(CONFIG_BT_MESH_FRIEND))) {
err = friend_cred_update(sub);
}
if (err) {
status = STATUS_UNSPECIFIED;
goto update_send_status;
}
sub->kr_phase = BT_MESH_KR_PHASE_1;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
printf("Storing NetKey persistently\n");
bt_mesh_store_subnet(sub, 0);
}
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NETKEY_UPDATE, &status);
}
#endif
bt_mesh_net_beacon_update(sub);
status = STATUS_SUCCESS;
update_send_status:
send_net_key_status(model, ctx, idx, status);
}
void hb_pub_disable(struct bt_mesh_cfg_srv *cfg)
{
BT_DBG("");
cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED;
cfg->hb_pub.count = 0;
cfg->hb_pub.ttl = 0;
cfg->hb_pub.period = 0;
k_delayed_work_cancel(&cfg->hb_pub.timer);
}
static void net_key_del(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
u16_t del_idx;
u8_t status;
del_idx = net_buf_simple_pull_le16(buf);
if (del_idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", del_idx);
return;
}
BT_DBG("idx 0x%04x", del_idx);
sub = bt_mesh_subnet_get(del_idx);
if (!sub) {
/* This could be a retry of a previous attempt that had its
* response lost, so pretend that it was a success.
*/
status = STATUS_SUCCESS;
goto send_status;
}
/* The key that the message was encrypted with cannot be removed.
* The NetKey List must contain a minimum of one NetKey.
*/
if (ctx->net_idx == del_idx) {
status = STATUS_CANNOT_REMOVE;
goto send_status;
}
bt_mesh_subnet_del(sub, true);
status = STATUS_SUCCESS;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NETKEY_DEL, &status);
}
#endif
send_status:
send_net_key_status(model, ctx, del_idx, status);
}
static void net_key_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + IDX_LEN(CONFIG_BT_MESH_SUBNET_COUNT));
u16_t prev, i;
bt_mesh_model_msg_init(&msg, OP_NET_KEY_LIST);
prev = BT_MESH_KEY_UNUSED;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (prev == BT_MESH_KEY_UNUSED) {
prev = sub->net_idx;
continue;
}
key_idx_pack(&msg, prev, sub->net_idx);
prev = BT_MESH_KEY_UNUSED;
}
if (prev != BT_MESH_KEY_UNUSED) {
net_buf_simple_add_le16(&msg, prev);
}
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send NetKey List");
}
}
static void node_identity_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
struct bt_mesh_subnet *sub;
u8_t node_id;
u16_t idx;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
idx = net_buf_simple_pull_le16(buf);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY);
node_id = 0x00;
} else {
net_buf_simple_add_u8(&msg, STATUS_SUCCESS);
node_id = sub->node_id;
}
net_buf_simple_add_le16(&msg, idx);
net_buf_simple_add_u8(&msg, node_id);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Node Identity Status");
}
}
static void node_identity_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
struct bt_mesh_subnet *sub;
u8_t node_id;
u16_t idx;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
idx = net_buf_simple_pull_le16(buf);
if (idx > 0xfff) {
BT_WARN("Invalid NetKeyIndex 0x%04x", idx);
return;
}
node_id = net_buf_simple_pull_u8(buf);
if (node_id != 0x00 && node_id != 0x01) {
BT_WARN("Invalid Node ID value 0x%02x", node_id);
return;
}
bt_mesh_model_msg_init(&msg, OP_NODE_IDENTITY_STATUS);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
net_buf_simple_add_u8(&msg, STATUS_INVALID_NETKEY);
net_buf_simple_add_le16(&msg, idx);
net_buf_simple_add_u8(&msg, node_id);
} else {
net_buf_simple_add_u8(&msg, STATUS_SUCCESS);
net_buf_simple_add_le16(&msg, idx);
/* Section 4.2.11.1: "When the GATT Proxy state is set to
* 0x00, the Node Identity state for all subnets shall be set
* to 0x00 and shall not be changed."
*/
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
if (node_id) {
bt_mesh_proxy_identity_start(sub);
} else {
bt_mesh_proxy_identity_stop(sub);
}
bt_mesh_adv_update();
}
net_buf_simple_add_u8(&msg, sub->node_id);
}
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Node Identity Status");
}
}
static void create_mod_app_status(struct net_buf_simple *msg, struct bt_mesh_model *mod, bool vnd, u16_t elem_addr,
u16_t app_idx, u8_t status, u8_t *mod_id)
{
bt_mesh_model_msg_init(msg, OP_MOD_APP_STATUS);
net_buf_simple_add_u8(msg, status);
net_buf_simple_add_le16(msg, elem_addr);
net_buf_simple_add_le16(msg, app_idx);
if (vnd) {
memcpy(net_buf_simple_add(msg, 4), mod_id, 4);
} else {
memcpy(net_buf_simple_add(msg, 2), mod_id, 2);
}
}
static void mod_app_bind(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4);
u16_t elem_addr, key_app_idx;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id, status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
key_app_idx = net_buf_simple_pull_le16(buf);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
/* Configuration Server only allows device key based access */
if (model == mod) {
BT_ERR("Client tried to bind AppKey to Configuration Model");
status = STATUS_CANNOT_BIND;
goto send_status;
}
status = mod_bind(mod, key_app_idx);
if (IS_ENABLED(CONFIG_BT_TESTING) && status == STATUS_SUCCESS) {
bt_test_mesh_model_bound(ctx->addr, mod, key_app_idx);
}
send_status:
BT_DBG("status 0x%02x", status);
create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, mod_id);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model App Bind Status response");
}
}
static void mod_app_unbind(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4);
u16_t elem_addr, key_app_idx;
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id, status;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
key_app_idx = net_buf_simple_pull_le16(buf);
mod_id = buf->data;
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_status;
}
status = mod_unbind(mod, key_app_idx, true);
if (IS_ENABLED(CONFIG_BT_TESTING) && status == STATUS_SUCCESS) {
bt_test_mesh_model_unbound(ctx->addr, mod, key_app_idx);
}
send_status:
BT_DBG("status 0x%02x", status);
create_mod_app_status(&msg, mod, vnd, elem_addr, key_app_idx, status, mod_id);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model App Unbind Status response");
}
}
#define KEY_LIST_LEN (CONFIG_BT_MESH_MODEL_KEY_COUNT * 2)
static void mod_app_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + KEY_LIST_LEN + 4);
struct bt_mesh_model *mod;
struct bt_mesh_elem *elem;
u8_t *mod_id, status;
u16_t elem_addr;
bool vnd;
elem_addr = net_buf_simple_pull_le16(buf);
if (!BT_MESH_ADDR_IS_UNICAST(elem_addr)) {
BT_WARN("Prohibited element address");
return;
}
mod_id = buf->data;
BT_DBG("elem_addr 0x%04x", elem_addr);
elem = bt_mesh_elem_find(elem_addr);
if (!elem) {
mod = NULL;
vnd = (buf->len == 4);
status = STATUS_INVALID_ADDRESS;
goto send_list;
}
mod = get_model(elem, buf, &vnd);
if (!mod) {
status = STATUS_INVALID_MODEL;
goto send_list;
}
status = STATUS_SUCCESS;
send_list:
if (vnd) {
bt_mesh_model_msg_init(&msg, OP_VND_MOD_APP_LIST);
} else {
bt_mesh_model_msg_init(&msg, OP_SIG_MOD_APP_LIST);
}
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, elem_addr);
if (vnd) {
net_buf_simple_add_mem(&msg, mod_id, 4);
} else {
net_buf_simple_add_mem(&msg, mod_id, 2);
}
if (mod) {
int i;
for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
if (mod->keys[i] != BT_MESH_KEY_UNUSED) {
net_buf_simple_add_le16(&msg, mod->keys[i]);
}
}
}
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Model Application List message");
}
}
static void node_reset_status_sent(int err, void *cb_data)
{
BT_DBG("");
#ifdef CONFIG_GENIE_MESH_ENABLE
extern uint8_t genie_reset_get_hw_reset_flag(void);
if (genie_reset_get_hw_reset_flag()) {
return;
}
#endif
bt_mesh_reset();
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NODE_RESET_OP, NULL);
}
#endif
}
static void node_reset(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
static struct bt_mesh_send_cb cb = { NULL, node_reset_status_sent };
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
bt_mesh_model_msg_init(&msg, OP_NODE_RESET_STATUS);
/* Send the response first since we wont have any keys left to
* send it later.
*/
ctx->send_rel = 1;
if (bt_mesh_model_send(model, ctx, &msg, &cb, NULL)) {
BT_ERR("Unable to send Node Reset Status");
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && !is_proxy_connected()) {
bt_mesh_proxy_gatt_disable();
}
}
static void send_friend_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
bt_mesh_model_msg_init(&msg, OP_FRIEND_STATUS);
net_buf_simple_add_u8(&msg, cfg->frnd);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Friend Status");
}
}
static void friend_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
send_friend_status(model, ctx);
}
static void friend_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_cfg_srv *cfg = model->user_data;
struct bt_mesh_subnet *sub;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s", ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (buf->data[0] != 0x00 && buf->data[0] != 0x01) {
BT_WARN("Invalid Friend value 0x%02x", buf->data[0]);
return;
}
if (!cfg) {
BT_WARN("No Configuration Server context available");
goto send_status;
}
BT_DBG("Friend 0x%02x -> 0x%02x", cfg->frnd, buf->data[0]);
if (cfg->frnd == buf->data[0]) {
goto send_status;
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
cfg->frnd = buf->data[0];
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_cfg();
}
if (cfg->frnd == BT_MESH_FRIEND_DISABLED) {
bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY);
}
}
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if ((cfg->hb_pub.feat & BT_MESH_FEAT_FRIEND) && sub) {
hb_send(model);
}
send_status:
send_friend_status(model, ctx);
}
static void lpn_timeout_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 5 + 4);
struct bt_mesh_friend *frnd;
u16_t lpn_addr;
bt_s32_t timeout;
lpn_addr = net_buf_simple_pull_le16(buf);
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x lpn_addr 0x%02x", ctx->net_idx, ctx->app_idx, ctx->addr, lpn_addr);
if (!BT_MESH_ADDR_IS_UNICAST(lpn_addr)) {
BT_WARN("Invalid LPNAddress; ignoring msg");
return;
}
bt_mesh_model_msg_init(&msg, OP_LPN_TIMEOUT_STATUS);
net_buf_simple_add_le16(&msg, lpn_addr);
if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
timeout = 0;
goto send_rsp;
}
frnd = bt_mesh_friend_find(BT_MESH_KEY_ANY, lpn_addr, true, true);
if (!frnd) {
timeout = 0;
goto send_rsp;
}
timeout = k_delayed_work_remaining_get(&frnd->timer) / 100;
send_rsp:
net_buf_simple_add_u8(&msg, timeout);
net_buf_simple_add_u8(&msg, timeout >> 8);
net_buf_simple_add_u8(&msg, timeout >> 16);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send LPN PollTimeout Status");
}
}
void lpn_hb_send()
{
struct bt_mesh_cfg_srv *cfg = conf;
struct bt_mesh_subnet *sub;
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if ((cfg->hb_pub.feat & BT_MESH_FEAT_LOW_POWER) && sub) {
hb_send(cfg->model);
}
}
static void send_krp_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, u16_t idx, u8_t phase,
u8_t status)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 4 + 4);
bt_mesh_model_msg_init(&msg, OP_KRP_STATUS);
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, idx);
net_buf_simple_add_u8(&msg, phase);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Key Refresh State Status");
}
}
static void krp_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
u16_t idx;
idx = net_buf_simple_pull_le16(buf);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
BT_DBG("idx 0x%04x", idx);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY);
} else {
send_krp_status(model, ctx, idx, sub->kr_phase, STATUS_SUCCESS);
}
}
static void krp_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
u8_t phase;
u16_t idx;
idx = net_buf_simple_pull_le16(buf);
phase = net_buf_simple_pull_u8(buf);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
BT_DBG("idx 0x%04x transition 0x%02x", idx, phase);
sub = bt_mesh_subnet_get(idx);
if (!sub) {
send_krp_status(model, ctx, idx, 0x00, STATUS_INVALID_NETKEY);
return;
}
BT_DBG("%u -> %u", sub->kr_phase, phase);
if (phase < BT_MESH_KR_PHASE_2 || phase > BT_MESH_KR_PHASE_3 ||
(sub->kr_phase == BT_MESH_KR_NORMAL && phase == BT_MESH_KR_PHASE_2)) {
BT_WARN("Prohibited transition %u -> %u", sub->kr_phase, phase);
return;
}
if (sub->kr_phase == BT_MESH_KR_PHASE_1 && phase == BT_MESH_KR_PHASE_2) {
sub->kr_phase = BT_MESH_KR_PHASE_2;
sub->kr_flag = 1;
bt_mesh_net_beacon_update(sub);
} else if ((sub->kr_phase == BT_MESH_KR_PHASE_1 || sub->kr_phase == BT_MESH_KR_PHASE_2) &&
phase == BT_MESH_KR_PHASE_3) {
bt_mesh_net_revoke_keys(sub);
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
friend_cred_refresh(ctx->net_idx);
}
sub->kr_phase = BT_MESH_KR_NORMAL;
sub->kr_flag = 0;
bt_mesh_net_beacon_update(sub);
}
send_krp_status(model, ctx, idx, sub->kr_phase, STATUS_SUCCESS);
}
static u8_t hb_log(u16_t val)
{
if (!val) {
return 0x00;
} else if (val == 0xffff) {
return 0xff;
} else {
return 32 - __builtin_clz(val);
}
}
static u8_t hb_pub_count_log(u16_t val)
{
if (!val) {
return 0x00;
} else if (val == 0x01) {
return 0x01;
} else if (val == 0xffff) {
return 0xff;
} else {
return 32 - __builtin_clz(val - 1) + 1;
}
}
u16_t hb_pwr2(u8_t val, u8_t sub)
{
if (!val) {
return 0x0000;
} else if (val == 0xff || val == 0x11) {
return 0xffff;
} else {
return 1 << (val - sub);
}
}
struct hb_pub_param {
u16_t dst;
u8_t count_log;
u8_t period_log;
u8_t ttl;
u16_t feat;
u16_t net_idx;
} __packed;
static void hb_pub_send_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, u8_t status,
struct hb_pub_param *orig_msg)
{
/* Needed size: opcode (1 byte) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 1 + 10 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status);
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_PUB_STATUS);
net_buf_simple_add_u8(&msg, status);
if (orig_msg) {
memcpy(net_buf_simple_add(&msg, sizeof(*orig_msg)), orig_msg, sizeof(*orig_msg));
goto send;
}
net_buf_simple_add_le16(&msg, cfg->hb_pub.dst);
net_buf_simple_add_u8(&msg, hb_pub_count_log(cfg->hb_pub.count));
net_buf_simple_add_u8(&msg, cfg->hb_pub.period);
net_buf_simple_add_u8(&msg, cfg->hb_pub.ttl);
net_buf_simple_add_le16(&msg, cfg->hb_pub.feat);
net_buf_simple_add_le16(&msg, cfg->hb_pub.net_idx);
send:
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Heartbeat Publication Status");
}
}
static void heartbeat_pub_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
BT_DBG("src 0x%04x", ctx->addr);
hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL);
}
static void heartbeat_pub_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct hb_pub_param *param = (void *)buf->data;
struct bt_mesh_cfg_srv *cfg = model->user_data;
u16_t dst, feat, idx;
u8_t status;
BT_DBG("src 0x%04x", ctx->addr);
dst = sys_le16_to_cpu(param->dst);
/* All other address types but virtual are valid */
if (BT_MESH_ADDR_IS_VIRTUAL(dst)) {
status = STATUS_INVALID_ADDRESS;
goto failed;
}
if (param->count_log > 0x11 && param->count_log != 0xff) {
status = STATUS_CANNOT_SET;
goto failed;
}
if (param->period_log > 0x10) {
status = STATUS_CANNOT_SET;
goto failed;
}
if (param->ttl > BT_MESH_TTL_MAX && param->ttl != BT_MESH_TTL_DEFAULT) {
BT_ERR("Invalid TTL value 0x%02x", param->ttl);
return;
}
feat = sys_le16_to_cpu(param->feat);
idx = sys_le16_to_cpu(param->net_idx);
if (idx > 0xfff) {
BT_ERR("Invalid NetKeyIndex 0x%04x", idx);
return;
}
if (!bt_mesh_subnet_get(idx)) {
status = STATUS_INVALID_NETKEY;
goto failed;
}
cfg->hb_pub.dst = dst;
cfg->hb_pub.period = param->period_log;
cfg->hb_pub.feat = feat & BT_MESH_FEAT_SUPPORTED;
cfg->hb_pub.net_idx = idx;
if (dst == BT_MESH_ADDR_UNASSIGNED) {
hb_pub_disable(cfg);
} else {
/* 2^(n-1) */
cfg->hb_pub.count = hb_pwr2(param->count_log, 1);
cfg->hb_pub.ttl = param->ttl;
BT_DBG("period %u ms", hb_pwr2(param->period_log, 1) * 1000);
/* The first Heartbeat message shall be published as soon
* as possible after the Heartbeat Publication Period state
* has been configured for periodic publishing.
*/
if (param->period_log && param->count_log) {
k_work_submit(&cfg->hb_pub.timer.work);
} else {
k_delayed_work_cancel(&cfg->hb_pub.timer);
}
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_hb_pub();
}
hb_pub_send_status(model, ctx, STATUS_SUCCESS, NULL);
return;
failed:
hb_pub_send_status(model, ctx, status, param);
}
static void hb_sub_send_status(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, u8_t status)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 9 + 4);
struct bt_mesh_cfg_srv *cfg = model->user_data;
u16_t period;
s64_t uptime;
BT_DBG("src 0x%04x status 0x%02x", ctx->addr, status);
uptime = k_uptime_get();
if (uptime > cfg->hb_sub.expiry) {
period = 0;
} else {
period = (cfg->hb_sub.expiry - uptime) / 1000;
}
bt_mesh_model_msg_init(&msg, OP_HEARTBEAT_SUB_STATUS);
net_buf_simple_add_u8(&msg, status);
net_buf_simple_add_le16(&msg, cfg->hb_sub.src);
net_buf_simple_add_le16(&msg, cfg->hb_sub.dst);
net_buf_simple_add_u8(&msg, hb_log(period));
net_buf_simple_add_u8(&msg, hb_log(cfg->hb_sub.count));
net_buf_simple_add_u8(&msg, cfg->hb_sub.min_hops);
net_buf_simple_add_u8(&msg, cfg->hb_sub.max_hops);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Heartbeat Subscription Status");
}
}
static void heartbeat_sub_get(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
BT_DBG("src 0x%04x", ctx->addr);
hb_sub_send_status(model, ctx, STATUS_SUCCESS);
}
static void heartbeat_sub_set(struct bt_mesh_model *model, struct bt_mesh_msg_ctx *ctx, struct net_buf_simple *buf)
{
struct bt_mesh_cfg_srv *cfg = model->user_data;
u16_t sub_src, sub_dst;
u8_t sub_period;
bt_s32_t period_ms;
BT_DBG("src 0x%04x", ctx->addr);
sub_src = net_buf_simple_pull_le16(buf);
sub_dst = net_buf_simple_pull_le16(buf);
sub_period = net_buf_simple_pull_u8(buf);
BT_DBG("sub_src 0x%04x sub_dst 0x%04x period 0x%02x", sub_src, sub_dst, sub_period);
if (sub_src != BT_MESH_ADDR_UNASSIGNED && !BT_MESH_ADDR_IS_UNICAST(sub_src)) {
BT_WARN("Prohibited source address");
return;
}
if (BT_MESH_ADDR_IS_VIRTUAL(sub_dst) || BT_MESH_ADDR_IS_RFU(sub_dst) ||
(BT_MESH_ADDR_IS_UNICAST(sub_dst) && sub_dst != bt_mesh_primary_addr())) {
BT_WARN("Prohibited destination address");
return;
}
if (sub_period > 0x11) {
BT_WARN("Prohibited subscription period 0x%02x", sub_period);
return;
}
if (sub_src == BT_MESH_ADDR_UNASSIGNED || sub_dst == BT_MESH_ADDR_UNASSIGNED || sub_period == 0x00) {
/* Only an explicit address change to unassigned should
* trigger clearing of the values according to
* MESH/NODE/CFG/HBS/BV-02-C.
*/
if (sub_src == BT_MESH_ADDR_UNASSIGNED || sub_dst == BT_MESH_ADDR_UNASSIGNED) {
cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED;
cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED;
cfg->hb_sub.min_hops = BT_MESH_TTL_MAX;
cfg->hb_sub.max_hops = 0;
cfg->hb_sub.count = 0;
}
period_ms = 0;
} else {
cfg->hb_sub.src = sub_src;
cfg->hb_sub.dst = sub_dst;
cfg->hb_sub.min_hops = BT_MESH_TTL_MAX;
cfg->hb_sub.max_hops = 0;
cfg->hb_sub.count = 0;
period_ms = hb_pwr2(sub_period, 1) * 1000;
}
/* Let the transport layer know it needs to handle this address */
bt_mesh_set_hb_sub_dst(cfg->hb_sub.dst);
BT_DBG("period_ms %u", period_ms);
if (period_ms) {
cfg->hb_sub.expiry = k_uptime_get() + period_ms;
} else {
cfg->hb_sub.expiry = 0;
}
hb_sub_send_status(model, ctx, STATUS_SUCCESS);
/* MESH/NODE/CFG/HBS/BV-01-C expects the MinHops to be 0x7f after
* disabling subscription, but 0x00 for subsequent Get requests.
*/
if (!period_ms) {
cfg->hb_sub.min_hops = 0;
}
}
const struct bt_mesh_model_op bt_mesh_cfg_srv_op[] = {
{ OP_DEV_COMP_DATA_GET, 1, dev_comp_data_get },
{ OP_APP_KEY_ADD, 19, app_key_add },
{ OP_APP_KEY_UPDATE, 19, app_key_update },
{ OP_APP_KEY_DEL, 3, app_key_del },
{ OP_APP_KEY_GET, 2, app_key_get },
{ OP_BEACON_GET, 0, beacon_get },
{ OP_BEACON_SET, 1, beacon_set },
{ OP_DEFAULT_TTL_GET, 0, default_ttl_get },
{ OP_DEFAULT_TTL_SET, 1, default_ttl_set },
{ OP_GATT_PROXY_GET, 0, gatt_proxy_get },
{ OP_GATT_PROXY_SET, 1, gatt_proxy_set },
{ OP_NET_TRANSMIT_GET, 0, net_transmit_get },
{ OP_NET_TRANSMIT_SET, 1, net_transmit_set },
{ OP_RELAY_GET, 0, relay_get },
{ OP_RELAY_SET, 2, relay_set },
{ OP_MOD_PUB_GET, 4, mod_pub_get },
{ OP_MOD_PUB_SET, 11, mod_pub_set },
{ OP_MOD_PUB_VA_SET, 24, mod_pub_va_set },
{ OP_MOD_SUB_ADD, 6, mod_sub_add },
{ OP_MOD_SUB_VA_ADD, 20, mod_sub_va_add },
{ OP_MOD_SUB_DEL, 6, mod_sub_del },
{ OP_MOD_SUB_VA_DEL, 20, mod_sub_va_del },
{ OP_MOD_SUB_OVERWRITE, 6, mod_sub_overwrite },
{ OP_MOD_SUB_VA_OVERWRITE, 20, mod_sub_va_overwrite },
{ OP_MOD_SUB_DEL_ALL, 4, mod_sub_del_all },
{ OP_MOD_SUB_GET, 4, mod_sub_get },
{ OP_MOD_SUB_GET_VND, 6, mod_sub_get_vnd },
{ OP_NET_KEY_ADD, 18, net_key_add },
{ OP_NET_KEY_UPDATE, 18, net_key_update },
{ OP_NET_KEY_DEL, 2, net_key_del },
{ OP_NET_KEY_GET, 0, net_key_get },
{ OP_NODE_IDENTITY_GET, 2, node_identity_get },
{ OP_NODE_IDENTITY_SET, 3, node_identity_set },
{ OP_MOD_APP_BIND, 6, mod_app_bind },
{ OP_MOD_APP_UNBIND, 6, mod_app_unbind },
{ OP_SIG_MOD_APP_GET, 4, mod_app_get },
{ OP_VND_MOD_APP_GET, 6, mod_app_get },
{ OP_NODE_RESET, 0, node_reset },
{ OP_FRIEND_GET, 0, friend_get },
{ OP_FRIEND_SET, 1, friend_set },
{ OP_LPN_TIMEOUT_GET, 2, lpn_timeout_get },
{ OP_KRP_GET, 2, krp_get },
{ OP_KRP_SET, 3, krp_set },
{ OP_HEARTBEAT_PUB_GET, 0, heartbeat_pub_get },
{ OP_HEARTBEAT_PUB_SET, 9, heartbeat_pub_set },
{ OP_HEARTBEAT_SUB_GET, 0, heartbeat_sub_get },
{ OP_HEARTBEAT_SUB_SET, 5, heartbeat_sub_set },
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
{ OP_CTRL_RELAY_CONF_GET, 0, ctrl_relay_conf_get },
#if !defined(CONFIG_PM_SLEEP)
{ OP_CTRL_RELAY_CONF_SET, 6, ctrl_relay_conf_set },
#endif
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
BT_MESH_MODEL_OP_END,
};
static void hb_publish(struct k_work *work)
{
struct bt_mesh_cfg_srv *cfg = CONTAINER_OF(work, struct bt_mesh_cfg_srv, hb_pub.timer.work);
struct bt_mesh_model *model = cfg->model;
struct bt_mesh_subnet *sub;
u16_t period_ms;
BT_DBG("hb_pub.count: %u", cfg->hb_pub.count);
sub = bt_mesh_subnet_get(cfg->hb_pub.net_idx);
if (!sub) {
BT_ERR("No matching subnet for idx 0x%02x", cfg->hb_pub.net_idx);
cfg->hb_pub.dst = BT_MESH_ADDR_UNASSIGNED;
return;
}
if (cfg->hb_pub.count == 0) {
return;
}
period_ms = hb_pwr2(cfg->hb_pub.period, 1) * 1000;
if (period_ms && cfg->hb_pub.count > 1) {
k_delayed_work_submit(&cfg->hb_pub.timer, period_ms);
}
hb_send(model);
if (cfg->hb_pub.count != 0xffff) {
cfg->hb_pub.count--;
}
}
static bool conf_is_valid(struct bt_mesh_cfg_srv *cfg)
{
if (cfg->relay > 0x02) {
return false;
}
if (cfg->beacon > 0x01) {
return false;
}
if (cfg->default_ttl > BT_MESH_TTL_MAX) {
return false;
}
return true;
}
int bt_mesh_cfg_srv_init(struct bt_mesh_model *model, bool primary)
{
struct bt_mesh_cfg_srv *cfg = model->user_data;
if (!cfg) {
BT_ERR("No Configuration Server context provided");
return -EINVAL;
}
if (!conf_is_valid(cfg)) {
BT_ERR("Invalid values in configuration");
return -EINVAL;
}
/* Configuration Model security is device-key based */
model->keys[0] = BT_MESH_KEY_DEV;
if (!IS_ENABLED(CONFIG_BT_MESH_RELAY)) {
cfg->relay = BT_MESH_RELAY_NOT_SUPPORTED;
}
if (!IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
cfg->frnd = BT_MESH_FRIEND_NOT_SUPPORTED;
}
if (!IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
cfg->gatt_proxy = BT_MESH_GATT_PROXY_NOT_SUPPORTED;
}
k_delayed_work_init(&cfg->hb_pub.timer, hb_publish);
cfg->hb_pub.net_idx = BT_MESH_KEY_UNUSED;
cfg->hb_sub.expiry = 0;
cfg->model = model;
conf = cfg;
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
ctrl_relay_init(model);
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
return 0;
}
static void mod_reset(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
size_t clear_count;
/* Clear model state that isn't otherwise cleared. E.g. AppKey
* binding and model publication is cleared as a consequence
* of removing all app keys, however model subscription clearing
* must be taken care of here.
*/
clear_count = mod_sub_list_clear(mod);
if (IS_ENABLED(CONFIG_BT_SETTINGS) && clear_count) {
bt_mesh_store_mod_sub(mod);
}
}
void bt_mesh_cfg_reset(void)
{
struct bt_mesh_cfg_srv *cfg = conf;
int i;
BT_DBG("");
if (!cfg) {
return;
}
bt_mesh_set_hb_sub_dst(BT_MESH_ADDR_UNASSIGNED);
cfg->hb_sub.src = BT_MESH_ADDR_UNASSIGNED;
cfg->hb_sub.dst = BT_MESH_ADDR_UNASSIGNED;
cfg->hb_sub.expiry = 0;
/* Delete all net keys, which also takes care of all app keys which
* are associated with each net key.
*/
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx != BT_MESH_KEY_UNUSED) {
bt_mesh_subnet_del(sub, true);
}
}
bt_mesh_model_foreach(mod_reset, NULL);
memset(labels, 0, sizeof(labels));
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
ctrl_relay_deinit();
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
}
void bt_mesh_heartbeat(u16_t src, u16_t dst, u8_t hops, u16_t feat)
{
struct bt_mesh_cfg_srv *cfg = conf;
if (!cfg) {
BT_WARN("No configuaration server context available");
return;
}
if (src != cfg->hb_sub.src || dst != cfg->hb_sub.dst) {
BT_WARN("No subscription for received heartbeat");
return;
}
if (k_uptime_get() > cfg->hb_sub.expiry) {
BT_WARN("Heartbeat subscription period expired");
return;
}
cfg->hb_sub.min_hops = MIN(cfg->hb_sub.min_hops, hops);
cfg->hb_sub.max_hops = MAX(cfg->hb_sub.max_hops, hops);
if (cfg->hb_sub.count < 0xffff) {
cfg->hb_sub.count++;
}
BT_DBG("src 0x%04x dst 0x%04x hops %u MIN %u MAX %u count %u", src, dst, hops, cfg->hb_sub.min_hops,
cfg->hb_sub.max_hops, cfg->hb_sub.count);
if (cfg->hb_sub.func) {
cfg->hb_sub.func(hops, feat);
}
}
u8_t bt_mesh_net_transmit_get(void)
{
if (conf) {
return conf->net_transmit;
}
return 0;
}
u8_t bt_mesh_relay_get(void)
{
if (conf) {
return conf->relay;
}
return BT_MESH_RELAY_NOT_SUPPORTED;
}
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
u8_t bt_mesh_relay_set(u8_t relay)
{
if (conf) {
conf->relay = relay;
}
return 0;
}
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
u8_t bt_mesh_friend_get(void)
{
BT_DBG("conf %p conf->frnd 0x%02x", conf, conf->frnd);
if (conf) {
return conf->frnd;
}
return BT_MESH_FRIEND_NOT_SUPPORTED;
}
u8_t bt_mesh_relay_retransmit_get(void)
{
if (conf) {
return conf->relay_retransmit;
}
return 0;
}
u8_t bt_mesh_beacon_get(void)
{
if (conf) {
return conf->beacon;
}
return BT_MESH_BEACON_DISABLED;
}
u8_t bt_mesh_gatt_proxy_get(void)
{
if (conf) {
return conf->gatt_proxy;
}
return BT_MESH_GATT_PROXY_NOT_SUPPORTED;
}
u8_t bt_mesh_default_ttl_get(void)
{
if (conf) {
return conf->default_ttl;
}
return DEFAULT_TTL;
}
u8_t *bt_mesh_label_uuid_get(u16_t addr)
{
int i;
BT_DBG("addr 0x%04x", addr);
for (i = 0; i < ARRAY_SIZE(labels); i++) {
if (labels[i].addr == addr) {
BT_DBG("Found Label UUID for 0x%04x: %s", addr, bt_hex(labels[i].uuid, 16));
return labels[i].uuid;
}
}
BT_WARN("No matching Label UUID for 0x%04x", addr);
return NULL;
}
struct bt_mesh_hb_pub *bt_mesh_hb_pub_get(void)
{
if (!conf) {
return NULL;
}
return &conf->hb_pub;
}
void bt_mesh_hb_pub_disable(void)
{
if (conf) {
hb_pub_disable(conf);
}
}
struct bt_mesh_cfg_srv *bt_mesh_cfg_get(void)
{
return conf;
}
void bt_mesh_subnet_del(struct bt_mesh_subnet *sub, bool store)
{
int i;
BT_DBG("NetIdx 0x%03x store %u", sub->net_idx, store);
if (conf && conf->hb_pub.net_idx == sub->net_idx) {
hb_pub_disable(conf);
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_store_hb_pub();
}
}
/* Delete any app keys bound to this NetKey index */
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx == sub->net_idx) {
bt_mesh_app_key_del(key, store);
}
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
bt_mesh_friend_clear_net_idx(sub->net_idx);
}
if (IS_ENABLED(CONFIG_BT_SETTINGS) && store) {
bt_mesh_clear_subnet(sub, 0);
}
memset(sub, 0, sizeof(*sub));
sub->net_idx = BT_MESH_KEY_UNUSED;
sub->subnet_active = false;
}
u8_t bt_mesh_mod_bind(struct bt_mesh_model *model, u16_t key_idx)
{
return mod_bind(model, key_idx);
}
u8_t bt_mesh_mod_sub_add(struct bt_mesh_model *model, u16_t sub_addr)
{
u8_t status;
int i;
if (!BT_MESH_ADDR_IS_GROUP(sub_addr)) {
status = STATUS_INVALID_ADDRESS;
goto send_status;
}
if (bt_mesh_model_find_group(model, sub_addr)) {
/* Tried to add existing subscription */
BT_DBG("found existing subscription");
status = STATUS_SUCCESS;
goto send_status;
}
for (i = 0; i < ARRAY_SIZE(model->groups); i++) {
if (model->groups[i] == BT_MESH_ADDR_UNASSIGNED) {
model->groups[i] = sub_addr;
break;
}
}
if (i == ARRAY_SIZE(model->groups)) {
status = STATUS_INSUFF_RESOURCES;
} else {
status = STATUS_SUCCESS;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mod_sub(model);
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_group_add(sub_addr);
}
}
send_status:
return status;
}
u8_t bt_mesh_mod_pub_set(struct bt_mesh_model *model, u16_t pub_addr)
{
if (model && model->pub) {
model->pub->addr = pub_addr;
}
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/cfg_srv.c | C | apache-2.0 | 98,225 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdbool.h>
#include <bt_errno.h>
//#include <toolchain.h>
#include <ble_os.h>
#include <ble_types/types.h>
#include <misc/byteorder.h>
#include <misc/util.h>
#ifdef CONFIG_BT_HOST_CRYPTO
#include <tinycrypt/constants.h>
#include <tinycrypt/utils.h>
#include <tinycrypt/aes.h>
#include <tinycrypt/cmac_mode.h>
#include <tinycrypt/ccm_mode.h>
#endif
#include <api/mesh.h>
// #include <bluetooth/crypto.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_CRYPTO)
#include "common/log.h"
#include "mesh.h"
#include "crypto.h"
#include "bt_crypto.h"
#define NET_MIC_LEN(pdu) (((pdu)[1] & 0x80) ? 8 : 4)
#define APP_MIC_LEN(aszmic) ((aszmic) ? 8 : 4)
int bt_mesh_aes_cmac(const u8_t key[16], struct bt_mesh_sg *sg,
size_t sg_len, u8_t mac[16])
{
return bt_crypto_aes_cmac(key, (struct bt_crypto_sg *)sg, sg_len, mac);
}
int bt_mesh_k1(const u8_t *ikm, size_t ikm_len, const u8_t salt[16],
const char *info, u8_t okm[16])
{
int err;
err = bt_mesh_aes_cmac_one(salt, ikm, ikm_len, okm);
if (err < 0) {
return err;
}
return bt_mesh_aes_cmac_one(okm, info, strlen(info), okm);
}
int bt_mesh_k2(const u8_t n[16], const u8_t *p, size_t p_len,
u8_t net_id[1], u8_t enc_key[16], u8_t priv_key[16])
{
struct bt_mesh_sg sg[3];
u8_t salt[16];
u8_t out[16];
u8_t t[16];
u8_t pad;
int err;
BT_DBG("n %s", bt_hex(n, 16));
BT_DBG("p %s", bt_hex(p, p_len));
err = bt_mesh_s1("smk2", salt);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(salt, n, 16, t);
if (err) {
return err;
}
pad = 0x01;
sg[0].data = NULL;
sg[0].len = 0;
sg[1].data = p;
sg[1].len = p_len;
sg[2].data = &pad;
sg[2].len = sizeof(pad);
err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out);
if (err) {
return err;
}
net_id[0] = out[15] & 0x7f;
sg[0].data = out;
sg[0].len = sizeof(out);
pad = 0x02;
err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out);
if (err) {
return err;
}
memcpy(enc_key, out, 16);
pad = 0x03;
err = bt_mesh_aes_cmac(t, sg, ARRAY_SIZE(sg), out);
if (err) {
return err;
}
memcpy(priv_key, out, 16);
BT_DBG("NID 0x%02x enc_key %s", net_id[0], bt_hex(enc_key, 16));
BT_DBG("priv_key %s", bt_hex(priv_key, 16));
return 0;
}
int bt_mesh_k3(const u8_t n[16], u8_t out[8])
{
u8_t id64[] = { 'i', 'd', '6', '4', 0x01 };
u8_t tmp[16];
u8_t t[16];
int err;
err = bt_mesh_s1("smk3", tmp);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(tmp, n, 16, t);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(t, id64, sizeof(id64), tmp);
if (err) {
return err;
}
memcpy(out, tmp + 8, 8);
return 0;
}
int bt_mesh_k4(const u8_t n[16], u8_t out[1])
{
u8_t id6[] = { 'i', 'd', '6', 0x01 };
u8_t tmp[16];
u8_t t[16];
int err;
err = bt_mesh_s1("smk4", tmp);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(tmp, n, 16, t);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(t, id6, sizeof(id6), tmp);
if (err) {
return err;
}
out[0] = tmp[15] & BIT_MASK(6);
return 0;
}
int bt_mesh_id128(const u8_t n[16], const char *s, u8_t out[16])
{
const char *id128 = "id128\x01";
u8_t salt[16];
int err;
err = bt_mesh_s1(s, salt);
if (err) {
return err;
}
return bt_mesh_k1(n, 16, salt, id128, out);
}
static int bt_mesh_ccm_decrypt(const u8_t key[16], u8_t nonce[13],
const u8_t *enc_msg, size_t msg_len,
const u8_t *aad, size_t aad_len,
u8_t *out_msg, size_t mic_size)
{
u8_t msg[16], pmsg[16], cmic[16], cmsg[16], Xn[16], mic[16];
u16_t last_blk, blk_cnt;
size_t i, j;
int err;
if (msg_len < 1 || aad_len >= 0xff00) {
return -EINVAL;
}
/* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(0x0000, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmic);
if (err) {
return err;
}
/* X_0 = e(AppKey, 0x09 || nonce || length) */
if (mic_size == sizeof(u64_t)) {
pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00);
} else {
pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00);
}
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(msg_len, pmsg + 14);
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
/* If AAD is being used to authenticate, include it here */
if (aad_len) {
sys_put_be16(aad_len, pmsg);
for (i = 0; i < sizeof(u16_t); i++) {
pmsg[i] = Xn[i] ^ pmsg[i];
}
j = 0;
aad_len += sizeof(u16_t);
while (aad_len > 16) {
do {
pmsg[i] = Xn[i] ^ aad[j];
i++, j++;
} while (i < 16);
aad_len -= 16;
i = 0;
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
}
for (i = 0; i < aad_len; i++, j++) {
pmsg[i] = Xn[i] ^ aad[j];
}
for (i = aad_len; i < 16; i++) {
pmsg[i] = Xn[i];
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
}
last_blk = msg_len % 16;
blk_cnt = (msg_len + 15) / 16;
if (!last_blk) {
last_blk = 16;
}
for (j = 0; j < blk_cnt; j++) {
if (j + 1 == blk_cnt) {
/* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(j + 1, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmsg);
if (err) {
return err;
}
/* Encrypted = Payload[0-15] ^ C_1 */
for (i = 0; i < last_blk; i++) {
msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i];
}
memcpy(out_msg + (j * 16), msg, last_blk);
/* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */
for (i = 0; i < last_blk; i++) {
pmsg[i] = Xn[i] ^ msg[i];
}
for (i = last_blk; i < 16; i++) {
pmsg[i] = Xn[i] ^ 0x00;
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
/* MIC = C_mic ^ X_1 */
for (i = 0; i < sizeof(mic); i++) {
mic[i] = cmic[i] ^ Xn[i];
}
} else {
/* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(j + 1, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmsg);
if (err) {
return err;
}
/* Encrypted = Payload[0-15] ^ C_1 */
for (i = 0; i < 16; i++) {
msg[i] = enc_msg[(j * 16) + i] ^ cmsg[i];
}
memcpy(out_msg + (j * 16), msg, 16);
/* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */
for (i = 0; i < 16; i++) {
pmsg[i] = Xn[i] ^ msg[i];
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
}
}
if (memcmp(mic, enc_msg + msg_len, mic_size)) {
return -EBADMSG;
}
return 0;
}
static int bt_mesh_ccm_encrypt(const u8_t key[16], u8_t nonce[13],
const u8_t *msg, size_t msg_len,
const u8_t *aad, size_t aad_len,
u8_t *out_msg, size_t mic_size)
{
u8_t pmsg[16], cmic[16], cmsg[16], mic[16], Xn[16];
u16_t blk_cnt, last_blk;
size_t i, j;
int err;
BT_DBG("key %s", bt_hex(key, 16));
BT_DBG("nonce %s", bt_hex(nonce, 13));
BT_DBG("msg (len %zu) %s", msg_len, bt_hex(msg, msg_len));
BT_DBG("aad_len %zu mic_size %zu", aad_len, mic_size);
/* Unsupported AAD size */
if (aad_len >= 0xff00) {
return -EINVAL;
}
/* C_mic = e(AppKey, 0x01 || nonce || 0x0000) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(0x0000, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmic);
if (err) {
return err;
}
/* X_0 = e(AppKey, 0x09 || nonce || length) */
if (mic_size == sizeof(u64_t)) {
pmsg[0] = 0x19 | (aad_len ? 0x40 : 0x00);
} else {
pmsg[0] = 0x09 | (aad_len ? 0x40 : 0x00);
}
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(msg_len, pmsg + 14);
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
/* If AAD is being used to authenticate, include it here */
if (aad_len) {
sys_put_be16(aad_len, pmsg);
for (i = 0; i < sizeof(u16_t); i++) {
pmsg[i] = Xn[i] ^ pmsg[i];
}
j = 0;
aad_len += sizeof(u16_t);
while (aad_len > 16) {
do {
pmsg[i] = Xn[i] ^ aad[j];
i++, j++;
} while (i < 16);
aad_len -= 16;
i = 0;
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
}
for (i = 0; i < aad_len; i++, j++) {
pmsg[i] = Xn[i] ^ aad[j];
}
for (i = aad_len; i < 16; i++) {
pmsg[i] = Xn[i];
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
}
last_blk = msg_len % 16;
blk_cnt = (msg_len + 15) / 16;
if (!last_blk) {
last_blk = 16;
}
for (j = 0; j < blk_cnt; j++) {
if (j + 1 == blk_cnt) {
/* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */
for (i = 0; i < last_blk; i++) {
pmsg[i] = Xn[i] ^ msg[(j * 16) + i];
}
for (i = last_blk; i < 16; i++) {
pmsg[i] = Xn[i] ^ 0x00;
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
/* MIC = C_mic ^ X_1 */
for (i = 0; i < sizeof(mic); i++) {
mic[i] = cmic[i] ^ Xn[i];
}
/* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(j + 1, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmsg);
if (err) {
return err;
}
/* Encrypted = Payload[0-15] ^ C_1 */
for (i = 0; i < last_blk; i++) {
out_msg[(j * 16) + i] =
msg[(j * 16) + i] ^ cmsg[i];
}
} else {
/* X_1 = e(AppKey, X_0 ^ Payload[0-15]) */
for (i = 0; i < 16; i++) {
pmsg[i] = Xn[i] ^ msg[(j * 16) + i];
}
err = bt_encrypt_be(key, pmsg, Xn);
if (err) {
return err;
}
/* C_1 = e(AppKey, 0x01 || nonce || 0x0001) */
pmsg[0] = 0x01;
memcpy(pmsg + 1, nonce, 13);
sys_put_be16(j + 1, pmsg + 14);
err = bt_encrypt_be(key, pmsg, cmsg);
if (err) {
return err;
}
/* Encrypted = Payload[0-15] ^ C_N */
for (i = 0; i < 16; i++) {
out_msg[(j * 16) + i] =
msg[(j * 16) + i] ^ cmsg[i];
}
}
}
memcpy(out_msg + msg_len, mic, mic_size);
return 0;
}
#if defined(CONFIG_BT_MESH_PROXY)
static void create_proxy_nonce(u8_t nonce[13], const u8_t *pdu,
bt_u32_t iv_index)
{
/* Nonce Type */
nonce[0] = 0x03;
/* Pad */
nonce[1] = 0x00;
/* Sequence Number */
nonce[2] = pdu[2];
nonce[3] = pdu[3];
nonce[4] = pdu[4];
/* Source Address */
nonce[5] = pdu[5];
nonce[6] = pdu[6];
/* Pad */
nonce[7] = 0;
nonce[8] = 0;
/* IV Index */
sys_put_be32(iv_index, &nonce[9]);
}
#endif /* PROXY */
static void create_net_nonce(u8_t nonce[13], const u8_t *pdu,
bt_u32_t iv_index)
{
/* Nonce Type */
nonce[0] = 0x00;
/* FRND + TTL */
nonce[1] = pdu[1];
/* Sequence Number */
nonce[2] = pdu[2];
nonce[3] = pdu[3];
nonce[4] = pdu[4];
/* Source Address */
nonce[5] = pdu[5];
nonce[6] = pdu[6];
/* Pad */
nonce[7] = 0;
nonce[8] = 0;
/* IV Index */
sys_put_be32(iv_index, &nonce[9]);
}
int bt_mesh_net_obfuscate(u8_t *pdu, bt_u32_t iv_index,
const u8_t privacy_key[16])
{
u8_t priv_rand[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, };
u8_t tmp[16];
int err, i;
BT_DBG("IVIndex %u, PrivacyKey %s", iv_index, bt_hex(privacy_key, 16));
if (!pdu)
{
return -EINVAL;
}
sys_put_be32(iv_index, &priv_rand[5]);
memcpy(&priv_rand[9], &pdu[7], 7);
BT_DBG("PrivacyRandom %s", bt_hex(priv_rand, 16));
err = bt_encrypt_be(privacy_key, priv_rand, tmp);
if (err) {
return err;
}
for (i = 0; i < 6; i++) {
pdu[1 + i] ^= tmp[i];
}
return 0;
}
int bt_mesh_net_encrypt(const u8_t key[16], struct net_buf_simple *buf,
bt_u32_t iv_index, bool proxy)
{
u8_t mic_len = NET_MIC_LEN(buf->data);
u8_t nonce[13];
int err;
BT_DBG("IVIndex %u EncKey %s mic_len %u", iv_index, bt_hex(key, 16),
mic_len);
BT_DBG("PDU (len %u) %s", buf->len, bt_hex(buf->data, buf->len));
if (!buf || !buf->data)
{
return -EINVAL;
}
#if defined(CONFIG_BT_MESH_PROXY)
if (proxy) {
create_proxy_nonce(nonce, buf->data, iv_index);
} else {
create_net_nonce(nonce, buf->data, iv_index);
}
#else
create_net_nonce(nonce, buf->data, iv_index);
#endif
BT_DBG("Nonce %s", bt_hex(nonce, 13));
err = bt_mesh_ccm_encrypt(key, nonce, &buf->data[7], buf->len - 7,
NULL, 0, &buf->data[7], mic_len);
if (!err) {
net_buf_simple_add(buf, mic_len);
}
return err;
}
int bt_mesh_net_decrypt(const u8_t key[16], struct net_buf_simple *buf,
bt_u32_t iv_index, bool proxy)
{
u8_t mic_len = NET_MIC_LEN(buf->data);
u8_t nonce[13];
BT_DBG("PDU (%u bytes) %s", buf->len, bt_hex(buf->data, buf->len));
BT_DBG("iv_index %u, key %s mic_len %u", iv_index, bt_hex(key, 16),
mic_len);
if (!buf || !buf->data)
{
return -EINVAL;
}
#if defined(CONFIG_BT_MESH_PROXY)
if (proxy) {
create_proxy_nonce(nonce, buf->data, iv_index);
} else {
create_net_nonce(nonce, buf->data, iv_index);
}
#else
create_net_nonce(nonce, buf->data, iv_index);
#endif
BT_DBG("Nonce %s", bt_hex(nonce, 13));
buf->len -= mic_len;
return bt_mesh_ccm_decrypt(key, nonce, &buf->data[7], buf->len - 7,
NULL, 0, &buf->data[7], mic_len);
}
static void create_app_nonce(u8_t nonce[13], bool dev_key, u8_t aszmic,
u16_t src, u16_t dst, bt_u32_t seq_num,
bt_u32_t iv_index)
{
if (dev_key) {
nonce[0] = 0x02;
} else {
nonce[0] = 0x01;
}
sys_put_be32((seq_num | ((bt_u32_t)aszmic << 31)), &nonce[1]);
sys_put_be16(src, &nonce[5]);
sys_put_be16(dst, &nonce[7]);
sys_put_be32(iv_index, &nonce[9]);
}
int bt_mesh_app_encrypt(const u8_t key[16], bool dev_key, u8_t aszmic,
struct net_buf_simple *buf, const u8_t *ad,
u16_t src, u16_t dst, bt_u32_t seq_num, bt_u32_t iv_index)
{
u8_t nonce[13];
int err;
BT_DBG("AppKey %s", bt_hex(key, 16));
BT_DBG("dev_key %u src 0x%04x dst 0x%04x", dev_key, src, dst);
BT_DBG("seq_num 0x%08x iv_index 0x%08x", seq_num, iv_index);
BT_DBG("Clear: %s", bt_hex(buf->data, buf->len));
create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index);
BT_DBG("Nonce %s", bt_hex(nonce, 13));
err = bt_mesh_ccm_encrypt(key, nonce, buf->data, buf->len, ad,
ad ? 16 : 0, buf->data, APP_MIC_LEN(aszmic));
if (!err) {
net_buf_simple_add(buf, APP_MIC_LEN(aszmic));
BT_DBG("Encr: %s", bt_hex(buf->data, buf->len));
}
return err;
}
int bt_mesh_app_decrypt(const u8_t key[16], bool dev_key, u8_t aszmic,
struct net_buf_simple *buf, struct net_buf_simple *out,
const u8_t *ad, u16_t src, u16_t dst, bt_u32_t seq_num,
bt_u32_t iv_index)
{
u8_t nonce[13];
int err;
BT_DBG("EncData (len %u) %s", buf->len, bt_hex(buf->data, buf->len));
create_app_nonce(nonce, dev_key, aszmic, src, dst, seq_num, iv_index);
BT_DBG("AppKey %s", bt_hex(key, 16));
BT_DBG("Nonce %s", bt_hex(nonce, 13));
err = bt_mesh_ccm_decrypt(key, nonce, buf->data, buf->len, ad,
ad ? 16 : 0, out->data, APP_MIC_LEN(aszmic));
if (!err) {
net_buf_simple_add(out, buf->len);
}
return err;
}
/* reversed, 8-bit, poly=0x07 */
static const u8_t crc_table[256] = {
0x00, 0x91, 0xe3, 0x72, 0x07, 0x96, 0xe4, 0x75,
0x0e, 0x9f, 0xed, 0x7c, 0x09, 0x98, 0xea, 0x7b,
0x1c, 0x8d, 0xff, 0x6e, 0x1b, 0x8a, 0xf8, 0x69,
0x12, 0x83, 0xf1, 0x60, 0x15, 0x84, 0xf6, 0x67,
0x38, 0xa9, 0xdb, 0x4a, 0x3f, 0xae, 0xdc, 0x4d,
0x36, 0xa7, 0xd5, 0x44, 0x31, 0xa0, 0xd2, 0x43,
0x24, 0xb5, 0xc7, 0x56, 0x23, 0xb2, 0xc0, 0x51,
0x2a, 0xbb, 0xc9, 0x58, 0x2d, 0xbc, 0xce, 0x5f,
0x70, 0xe1, 0x93, 0x02, 0x77, 0xe6, 0x94, 0x05,
0x7e, 0xef, 0x9d, 0x0c, 0x79, 0xe8, 0x9a, 0x0b,
0x6c, 0xfd, 0x8f, 0x1e, 0x6b, 0xfa, 0x88, 0x19,
0x62, 0xf3, 0x81, 0x10, 0x65, 0xf4, 0x86, 0x17,
0x48, 0xd9, 0xab, 0x3a, 0x4f, 0xde, 0xac, 0x3d,
0x46, 0xd7, 0xa5, 0x34, 0x41, 0xd0, 0xa2, 0x33,
0x54, 0xc5, 0xb7, 0x26, 0x53, 0xc2, 0xb0, 0x21,
0x5a, 0xcb, 0xb9, 0x28, 0x5d, 0xcc, 0xbe, 0x2f,
0xe0, 0x71, 0x03, 0x92, 0xe7, 0x76, 0x04, 0x95,
0xee, 0x7f, 0x0d, 0x9c, 0xe9, 0x78, 0x0a, 0x9b,
0xfc, 0x6d, 0x1f, 0x8e, 0xfb, 0x6a, 0x18, 0x89,
0xf2, 0x63, 0x11, 0x80, 0xf5, 0x64, 0x16, 0x87,
0xd8, 0x49, 0x3b, 0xaa, 0xdf, 0x4e, 0x3c, 0xad,
0xd6, 0x47, 0x35, 0xa4, 0xd1, 0x40, 0x32, 0xa3,
0xc4, 0x55, 0x27, 0xb6, 0xc3, 0x52, 0x20, 0xb1,
0xca, 0x5b, 0x29, 0xb8, 0xcd, 0x5c, 0x2e, 0xbf,
0x90, 0x01, 0x73, 0xe2, 0x97, 0x06, 0x74, 0xe5,
0x9e, 0x0f, 0x7d, 0xec, 0x99, 0x08, 0x7a, 0xeb,
0x8c, 0x1d, 0x6f, 0xfe, 0x8b, 0x1a, 0x68, 0xf9,
0x82, 0x13, 0x61, 0xf0, 0x85, 0x14, 0x66, 0xf7,
0xa8, 0x39, 0x4b, 0xda, 0xaf, 0x3e, 0x4c, 0xdd,
0xa6, 0x37, 0x45, 0xd4, 0xa1, 0x30, 0x42, 0xd3,
0xb4, 0x25, 0x57, 0xc6, 0xb3, 0x22, 0x50, 0xc1,
0xba, 0x2b, 0x59, 0xc8, 0xbd, 0x2c, 0x5e, 0xcf
};
u8_t bt_mesh_fcs_calc(const u8_t *data, u8_t data_len)
{
u8_t fcs = 0xff;
while (data_len--) {
fcs = crc_table[fcs ^ *data++];
}
BT_DBG("fcs 0x%02x", 0xff - fcs);
return 0xff - fcs;
}
bool bt_mesh_fcs_check(struct net_buf_simple *buf, u8_t received_fcs)
{
const u8_t *data = buf->data;
u16_t data_len = buf->len;
u8_t fcs = 0xff;
while (data_len--) {
fcs = crc_table[fcs ^ *data++];
}
return crc_table[fcs ^ received_fcs] == 0xcf;
}
int bt_mesh_virtual_addr(const u8_t virtual_label[16], u16_t *addr)
{
u8_t salt[16];
u8_t tmp[16];
int err;
err = bt_mesh_s1("vtad", salt);
if (err) {
return err;
}
err = bt_mesh_aes_cmac_one(salt, virtual_label, 16, tmp);
if (err) {
return err;
}
*addr = (sys_get_be16(&tmp[14]) & 0x3fff) | 0x8000;
return 0;
}
int bt_mesh_prov_conf_salt(const u8_t conf_inputs[145], u8_t salt[16])
{
const u8_t conf_salt_key[16] = { 0 };
return bt_mesh_aes_cmac_one(conf_salt_key, conf_inputs, 145, salt);
}
int bt_mesh_prov_conf_key(const u8_t dhkey[32], const u8_t conf_salt[16],
u8_t conf_key[16])
{
return bt_mesh_k1(dhkey, 32, conf_salt, "prck", conf_key);
}
int bt_mesh_prov_conf(const u8_t conf_key[16], const u8_t rand[16],
const u8_t auth[16], u8_t conf[16])
{
struct bt_mesh_sg sg[] = { { rand, 16 }, { auth, 16 } };
BT_DBG("ConfirmationKey %s", bt_hex(conf_key, 16));
BT_DBG("RandomDevice %s", bt_hex(rand, 16));
BT_DBG("AuthValue %s", bt_hex(auth, 16));
return bt_mesh_aes_cmac(conf_key, sg, ARRAY_SIZE(sg), conf);
}
int bt_mesh_prov_decrypt(const u8_t key[16], u8_t nonce[13],
const u8_t data[25 + 8], u8_t out[25])
{
return bt_mesh_ccm_decrypt(key, nonce, data, 25, NULL, 0, out, 8);
}
#ifdef CONFIG_BT_MESH_PROVISIONER
int bt_mesh_prov_encrypt(const u8_t key[16], u8_t nonce[13],
const u8_t data[25], u8_t out[33])
{
return bt_mesh_ccm_encrypt(key, nonce, data, 25, NULL, 0, out, 8);
}
#endif
int bt_mesh_beacon_auth(const u8_t beacon_key[16], u8_t flags,
const u8_t net_id[8], bt_u32_t iv_index,
u8_t auth[8])
{
u8_t msg[13], tmp[16];
int err;
BT_DBG("BeaconKey %s", bt_hex(beacon_key, 16));
BT_DBG("NetId %s", bt_hex(net_id, 8));
BT_DBG("IV Index 0x%08x", iv_index);
msg[0] = flags;
memcpy(&msg[1], net_id, 8);
sys_put_be32(iv_index, &msg[9]);
BT_DBG("BeaconMsg %s", bt_hex(msg, sizeof(msg)));
err = bt_mesh_aes_cmac_one(beacon_key, msg, sizeof(msg), tmp);
if (!err) {
memcpy(auth, tmp, 8);
}
return err;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/crypto.c | C | apache-2.0 | 18,677 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <ble_os.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_FRIEND)
#include "common/log.h"
#include "crypto.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#include "friend.h"
#include "bt_errno.h"
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
#ifdef CONFIG_BT_MESH_FRIEND
#define FRIEND_BUF_SIZE (BT_MESH_ADV_DATA_SIZE - BT_MESH_NET_HDR_LEN)
/* We reserve one extra buffer for each friendship, since we need to be able
* to resend the last sent PDU, which sits separately outside of the queue.
*/
#ifdef CONFIG_BT_BQB
#define FRIEND_BUF_COUNT CONFIG_BT_MESH_FRIEND_QUEUE_SIZE
#else
#define FRIEND_BUF_COUNT ((CONFIG_BT_MESH_FRIEND_QUEUE_SIZE + 1) * CONFIG_BT_MESH_FRIEND_LPN_COUNT)
#endif
#define FRIEND_ADV(buf) CONTAINER_OF(BT_MESH_ADV(buf), struct friend_adv, adv)
/* PDUs from Friend to the LPN should only be transmitted once with the
* smallest possible interval (20ms).
*/
#define FRIEND_XMIT BT_MESH_TRANSMIT(0, 20)
struct friend_pdu_info {
u16_t src;
u16_t dst;
u8_t seq[3];
u8_t ttl:7, ctl:1;
bt_u32_t iv_index;
};
NET_BUF_POOL_FIXED_DEFINE(friend_buf_pool, FRIEND_BUF_COUNT, BT_MESH_ADV_DATA_SIZE, NULL);
static struct friend_adv {
struct bt_mesh_adv adv;
u64_t seq_auth;
} adv_pool[FRIEND_BUF_COUNT];
static struct bt_mesh_adv *adv_alloc(int id)
{
return &adv_pool[id].adv;
}
static void discard_buffer(void)
{
struct bt_mesh_friend *frnd = &bt_mesh.frnd[0];
struct net_buf *buf;
int i;
/* Find the Friend context with the most queued buffers */
for (i = 1; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
if (bt_mesh.frnd[i].queue_size > frnd->queue_size) {
frnd = &bt_mesh.frnd[i];
}
}
buf = net_buf_slist_get(&frnd->queue);
__ASSERT_NO_MSG(buf != NULL);
BT_WARN("Discarding buffer %p for LPN 0x%04x", buf, frnd->lpn);
net_buf_unref(buf);
frnd->queue_size--;
}
static struct net_buf *friend_buf_alloc(u16_t src)
{
struct net_buf *buf;
BT_DBG("src 0x%04x", src);
do {
buf = bt_mesh_adv_create_from_pool(&friend_buf_pool, adv_alloc, BT_MESH_ADV_DATA, FRIEND_XMIT, K_NO_WAIT);
if (!buf) {
discard_buffer();
}
} while (!buf);
BT_MESH_ADV(buf)->addr = src;
FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL;
BT_DBG("allocated buf %p", buf);
return buf;
}
static bool is_lpn_unicast(struct bt_mesh_friend *frnd, u16_t addr)
{
if (frnd->lpn == BT_MESH_ADDR_UNASSIGNED) {
return false;
}
return (addr >= frnd->lpn && addr < (frnd->lpn + frnd->num_elem));
}
struct bt_mesh_friend *bt_mesh_friend_find(u16_t net_idx, u16_t lpn_addr, bool valid, bool established)
{
int i;
BT_DBG("net_idx 0x%04x lpn_addr 0x%04x", net_idx, lpn_addr);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (valid && !frnd->valid) {
continue;
}
if (established && !frnd->established) {
continue;
}
if (net_idx != BT_MESH_KEY_ANY && frnd->net_idx != net_idx) {
continue;
}
if (is_lpn_unicast(frnd, lpn_addr)) {
return frnd;
}
}
return NULL;
}
/* Intentionally start a little bit late into the ReceiveWindow when
* it's large enough. This may improve reliability with some platforms,
* like the PTS, where the receiver might not have sufficiently compensated
* for internal latencies required to start scanning.
*/
static bt_s32_t recv_delay(struct bt_mesh_friend *frnd)
{
#if CONFIG_BT_MESH_FRIEND_RECV_WIN > 50
return (bt_s32_t)frnd->recv_delay + (CONFIG_BT_MESH_FRIEND_RECV_WIN / 5);
#else
return frnd->recv_delay;
#endif
}
static void friend_clear(struct bt_mesh_friend *frnd)
{
int i;
BT_DBG("LPN 0x%04x", frnd->lpn);
k_delayed_work_cancel(&frnd->timer);
friend_cred_del(frnd->net_idx, frnd->lpn);
if (frnd->last) {
/* Cancel the sending if necessary */
if (frnd->pending_buf) {
BT_MESH_ADV(frnd->last)->busy = 0;
}
net_buf_unref(frnd->last);
frnd->last = NULL;
}
while (!sys_slist_is_empty(&frnd->queue)) {
net_buf_unref(net_buf_slist_get(&frnd->queue));
}
for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) {
struct bt_mesh_friend_seg *seg = &frnd->seg[i];
while (!sys_slist_is_empty(&seg->queue)) {
net_buf_unref(net_buf_slist_get(&seg->queue));
}
}
frnd->valid = 0;
frnd->established = 0;
frnd->pending_buf = 0;
frnd->fsn = 0;
frnd->queue_size = 0;
frnd->pending_req = 0;
memset(frnd->sub_list, 0, sizeof(frnd->sub_list));
}
void bt_mesh_friend_clear_net_idx(u16_t net_idx)
{
int i;
BT_DBG("net_idx 0x%04x", net_idx);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (frnd->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) {
friend_clear(frnd);
}
}
}
void bt_mesh_friend_sec_update(u16_t net_idx)
{
int i;
BT_DBG("net_idx 0x%04x", net_idx);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (frnd->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (net_idx == BT_MESH_KEY_ANY || frnd->net_idx == net_idx) {
frnd->sec_update = 1;
}
}
}
int bt_mesh_friend_clear(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_clear *msg = (void *)buf->data;
struct bt_mesh_friend *frnd;
u16_t lpn_addr, lpn_counter;
struct bt_mesh_net_tx tx = {
.sub = rx->sub,
.ctx = &rx->ctx,
.src = bt_mesh_primary_addr(),
.xmit = bt_mesh_net_transmit_get(),
};
struct bt_mesh_ctl_friend_clear_confirm cfm;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Clear");
return -EINVAL;
}
lpn_addr = sys_be16_to_cpu(msg->lpn_addr);
lpn_counter = sys_be16_to_cpu(msg->lpn_counter);
BT_DBG("LPN addr 0x%04x counter 0x%04x", lpn_addr, lpn_counter);
frnd = bt_mesh_friend_find(rx->sub->net_idx, lpn_addr, false, false);
if (!frnd) {
BT_WARN("No matching LPN addr 0x%04x", lpn_addr);
return 0;
}
/* A Friend Clear message is considered valid if the result of the
* subtraction of the value of the LPNCounter field of the Friend
* Request message (the one that initiated the friendship) from the
* value of the LPNCounter field of the Friend Clear message, modulo
* 65536, is in the range 0 to 255 inclusive.
*/
if (lpn_counter - frnd->lpn_counter > 255) {
BT_WARN("LPN Counter out of range (old %u new %u)", frnd->lpn_counter, lpn_counter);
return 0;
}
tx.ctx->send_ttl = BT_MESH_TTL_MAX;
cfm.lpn_addr = msg->lpn_addr;
cfm.lpn_counter = msg->lpn_counter;
bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR_CFM, &cfm, sizeof(cfm), NULL, NULL, NULL);
friend_clear(frnd);
return 0;
}
static void friend_sub_add(struct bt_mesh_friend *frnd, u16_t addr)
{
int i;
for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) {
if (frnd->sub_list[i] == BT_MESH_ADDR_UNASSIGNED) {
frnd->sub_list[i] = addr;
return;
}
}
BT_WARN("No space in friend subscription list");
}
static void friend_sub_rem(struct bt_mesh_friend *frnd, u16_t addr)
{
int i;
for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) {
if (frnd->sub_list[i] == addr) {
frnd->sub_list[i] = BT_MESH_ADDR_UNASSIGNED;
return;
}
}
}
static struct net_buf *create_friend_pdu(struct bt_mesh_friend *frnd, struct friend_pdu_info *info,
struct net_buf_simple *sdu)
{
struct bt_mesh_subnet *sub;
const u8_t *enc = NULL, *priv;
struct net_buf *buf;
u8_t nid;
sub = bt_mesh_subnet_get(frnd->net_idx);
__ASSERT_NO_MSG(sub != NULL);
if (!sub) {
return NULL;
}
buf = friend_buf_alloc(info->src);
/* Friend Offer needs master security credentials */
if (info->ctl && TRANS_CTL_OP(sdu->data) == TRANS_CTL_OP_FRIEND_OFFER) {
enc = sub->keys[sub->kr_flag].enc;
priv = sub->keys[sub->kr_flag].privacy;
nid = sub->keys[sub->kr_flag].nid;
} else {
if (friend_cred_get(sub, frnd->lpn, &nid, &enc, &priv)) {
BT_ERR("friend_cred_get failed");
goto failed;
}
}
net_buf_add_u8(buf, (nid | (info->iv_index & 1) << 7));
if (info->ctl) {
net_buf_add_u8(buf, info->ttl | 0x80);
} else {
net_buf_add_u8(buf, info->ttl);
}
net_buf_add_mem(buf, info->seq, sizeof(info->seq));
net_buf_add_be16(buf, info->src);
net_buf_add_be16(buf, info->dst);
net_buf_add_mem(buf, sdu->data, sdu->len);
/* We re-encrypt and obfuscate using the received IVI rather than
* the normal TX IVI (which may be different) since the transport
* layer nonce includes the IVI.
*/
if (bt_mesh_net_encrypt(enc, &buf->b, info->iv_index, false)) {
BT_ERR("Re-encrypting failed");
goto failed;
}
if (bt_mesh_net_obfuscate(buf->data, info->iv_index, priv)) {
BT_ERR("Re-obfuscating failed");
goto failed;
}
return buf;
failed:
net_buf_unref(buf);
return NULL;
}
static struct net_buf *encode_friend_ctl(struct bt_mesh_friend *frnd, u8_t ctl_op, struct net_buf_simple *sdu)
{
struct friend_pdu_info info;
bt_u32_t seq;
BT_DBG("LPN 0x%04x", frnd->lpn);
net_buf_simple_push_u8(sdu, TRANS_CTL_HDR(ctl_op, 0));
info.src = bt_mesh_primary_addr();
info.dst = frnd->lpn;
info.ctl = 1;
info.ttl = 0;
seq = bt_mesh_next_seq();
info.seq[0] = seq >> 16;
info.seq[1] = seq >> 8;
info.seq[2] = seq;
info.iv_index = BT_MESH_NET_IVI_TX;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, &seq);
}
#endif
return create_friend_pdu(frnd, &info, sdu);
}
static struct net_buf *encode_update(struct bt_mesh_friend *frnd, u8_t md)
{
struct bt_mesh_ctl_friend_update *upd;
NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*upd));
struct bt_mesh_subnet *sub = bt_mesh_subnet_get(frnd->net_idx);
__ASSERT_NO_MSG(sub != NULL);
BT_DBG("lpn 0x%04x md 0x%02x", frnd->lpn, md);
net_buf_simple_reserve(&sdu, 1);
upd = net_buf_simple_add(&sdu, sizeof(*upd));
upd->flags = bt_mesh_net_flags(sub);
upd->iv_index = sys_cpu_to_be32(bt_mesh.iv_index);
upd->md = md;
return encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_UPDATE, &sdu);
}
static void enqueue_sub_cfm(struct bt_mesh_friend *frnd, u8_t xact)
{
struct bt_mesh_ctl_friend_sub_confirm *cfm;
NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*cfm));
struct net_buf *buf;
BT_DBG("lpn 0x%04x xact 0x%02x", frnd->lpn, xact);
net_buf_simple_reserve(&sdu, 1);
cfm = net_buf_simple_add(&sdu, sizeof(*cfm));
cfm->xact = xact;
buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_SUB_CFM, &sdu);
if (!buf) {
BT_ERR("Unable to encode Subscription List Confirmation");
return;
}
if (frnd->last) {
BT_DBG("Discarding last PDU");
net_buf_unref(frnd->last);
}
frnd->last = buf;
frnd->send_last = 1;
}
static void friend_recv_delay(struct bt_mesh_friend *frnd)
{
frnd->pending_req = 1;
k_delayed_work_submit(&frnd->timer, recv_delay(frnd));
BT_DBG("Waiting RecvDelay of %d ms", recv_delay(frnd));
}
int bt_mesh_friend_sub_add(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_friend *frnd;
u8_t xact;
if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) {
BT_WARN("Too short Friend Subscription Add");
return -EINVAL;
}
frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true);
if (!frnd) {
BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr);
return 0;
}
if (frnd->pending_buf) {
BT_WARN("Previous buffer not yet sent!");
return 0;
}
friend_recv_delay(frnd);
xact = net_buf_simple_pull_u8(buf);
while (buf->len >= 2) {
friend_sub_add(frnd, net_buf_simple_pull_be16(buf));
}
enqueue_sub_cfm(frnd, xact);
return 0;
}
int bt_mesh_friend_sub_rem(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_friend *frnd;
u8_t xact;
if (buf->len < BT_MESH_FRIEND_SUB_MIN_LEN) {
BT_WARN("Too short Friend Subscription Remove");
return -EINVAL;
}
frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, true);
if (!frnd) {
BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr);
return 0;
}
if (frnd->pending_buf) {
BT_WARN("Previous buffer not yet sent!");
return 0;
}
friend_recv_delay(frnd);
xact = net_buf_simple_pull_u8(buf);
while (buf->len >= 2) {
friend_sub_rem(frnd, net_buf_simple_pull_be16(buf));
}
enqueue_sub_cfm(frnd, xact);
return 0;
}
static void enqueue_buf(struct bt_mesh_friend *frnd, struct net_buf *buf)
{
if (frnd->queue_size >= CONFIG_BT_MESH_FRIEND_QUEUE_SIZE) {
struct net_buf *buf = net_buf_slist_get(&frnd->queue);
__ASSERT_NO_MSG(buf != NULL);
BT_WARN("Discarding buffer %p for LPN 0x%04x", buf, frnd->lpn);
net_buf_unref(buf);
frnd->queue_size--;
}
net_buf_slist_put(&frnd->queue, buf);
frnd->queue_size++;
}
static void enqueue_update(struct bt_mesh_friend *frnd, u8_t md)
{
struct net_buf *buf;
buf = encode_update(frnd, md);
if (!buf) {
BT_ERR("Unable to encode Friend Update");
return;
}
frnd->sec_update = 0;
enqueue_buf(frnd, buf);
}
int bt_mesh_friend_poll(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_poll *msg = (void *)buf->data;
struct bt_mesh_friend *frnd;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Poll");
return -EINVAL;
}
frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false);
if (!frnd) {
BT_WARN("No matching LPN addr 0x%04x", rx->ctx.addr);
return 0;
}
if (msg->fsn & ~1) {
BT_WARN("Prohibited (non-zero) padding bits");
return -EINVAL;
}
if (frnd->pending_buf) {
BT_WARN("Previous buffer not yet sent");
return 0;
}
BT_DBG("msg->fsn %u frnd->fsn %u", (msg->fsn & 1), frnd->fsn);
friend_recv_delay(frnd);
if (!frnd->established) {
BT_DBG("Friendship established with 0x%04x", frnd->lpn);
frnd->established = 1;
}
if (msg->fsn == frnd->fsn && frnd->last) {
BT_DBG("Re-sending last PDU");
frnd->send_last = 1;
} else {
if (frnd->last) {
net_buf_unref(frnd->last);
frnd->last = NULL;
}
frnd->fsn = msg->fsn;
if (sys_slist_is_empty(&frnd->queue)) {
enqueue_update(frnd, 0);
BT_DBG("Enqueued Friend Update to empty queue");
}
}
return 0;
}
static struct bt_mesh_friend *find_clear(u16_t prev_friend)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (frnd->clear.frnd == prev_friend) {
return frnd;
}
}
return NULL;
}
static void friend_clear_sent(int err, void *user_data)
{
struct bt_mesh_friend *frnd = user_data;
k_delayed_work_submit(&frnd->clear.timer, K_SECONDS(frnd->clear.repeat_sec));
frnd->clear.repeat_sec *= 2;
}
static const struct bt_mesh_send_cb clear_sent_cb = {
.end = friend_clear_sent,
};
static void send_friend_clear(struct bt_mesh_friend *frnd)
{
struct bt_mesh_msg_ctx ctx = {
.net_idx = frnd->net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = frnd->clear.frnd,
.send_ttl = BT_MESH_TTL_MAX,
};
struct bt_mesh_net_tx tx = {
.sub = &bt_mesh.sub[0],
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
.xmit = bt_mesh_net_transmit_get(),
};
struct bt_mesh_ctl_friend_clear req = {
.lpn_addr = sys_cpu_to_be16(frnd->lpn),
.lpn_counter = sys_cpu_to_be16(frnd->lpn_counter),
};
BT_DBG("");
bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req, sizeof(req), NULL, &clear_sent_cb, frnd);
}
static void clear_timeout(struct k_work *work)
{
struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, clear.timer.work);
bt_u32_t duration;
BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd);
duration = k_uptime_get_32() - frnd->clear.start;
if (duration > 2 * frnd->poll_to) {
BT_DBG("Clear Procedure timer expired");
frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED;
return;
}
send_friend_clear(frnd);
}
static void clear_procedure_start(struct bt_mesh_friend *frnd)
{
BT_DBG("LPN 0x%04x (old) Friend 0x%04x", frnd->lpn, frnd->clear.frnd);
frnd->clear.start = k_uptime_get_32() + (2 * frnd->poll_to);
frnd->clear.repeat_sec = 1;
send_friend_clear(frnd);
}
int bt_mesh_friend_clear_cfm(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data;
struct bt_mesh_friend *frnd;
u16_t lpn_addr, lpn_counter;
BT_DBG("");
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Clear Confirm");
return -EINVAL;
}
frnd = find_clear(rx->ctx.addr);
if (!frnd) {
BT_WARN("No pending clear procedure for 0x%02x", rx->ctx.addr);
return 0;
}
lpn_addr = sys_be16_to_cpu(msg->lpn_addr);
if (lpn_addr != frnd->lpn) {
BT_WARN("LPN address mismatch (0x%04x != 0x%04x)", lpn_addr, frnd->lpn);
return 0;
}
lpn_counter = sys_be16_to_cpu(msg->lpn_counter);
if (lpn_counter != frnd->lpn_counter) {
BT_WARN("LPN counter mismatch (0x%04x != 0x%04x)", lpn_counter, frnd->lpn_counter);
return 0;
}
k_delayed_work_cancel(&frnd->clear.timer);
frnd->clear.frnd = BT_MESH_ADDR_UNASSIGNED;
return 0;
}
static void enqueue_offer(struct bt_mesh_friend *frnd, s8_t rssi)
{
struct bt_mesh_ctl_friend_offer *off;
NET_BUF_SIMPLE_DEFINE(sdu, 1 + sizeof(*off));
struct net_buf *buf;
BT_DBG("");
net_buf_simple_reserve(&sdu, 1);
off = net_buf_simple_add(&sdu, sizeof(*off));
off->recv_win = CONFIG_BT_MESH_FRIEND_RECV_WIN, off->queue_size = CONFIG_BT_MESH_FRIEND_QUEUE_SIZE,
off->sub_list_size = ARRAY_SIZE(frnd->sub_list), off->rssi = rssi,
off->frnd_counter = sys_cpu_to_be16(frnd->counter);
buf = encode_friend_ctl(frnd, TRANS_CTL_OP_FRIEND_OFFER, &sdu);
if (!buf) {
BT_ERR("Unable to encode Friend Offer");
return;
}
frnd->counter++;
if (frnd->last) {
net_buf_unref(frnd->last);
}
frnd->last = buf;
frnd->send_last = 1;
}
#define RECV_WIN CONFIG_BT_MESH_FRIEND_RECV_WIN
#define RSSI_FACT(crit) (((crit) >> 5) & (u8_t)BIT_MASK(2))
#define RECV_WIN_FACT(crit) (((crit) >> 3) & (u8_t)BIT_MASK(2))
#define MIN_QUEUE_SIZE_LOG(crit) ((crit) & (u8_t)BIT_MASK(3))
#define MIN_QUEUE_SIZE(crit) ((bt_u32_t)BIT(MIN_QUEUE_SIZE_LOG(crit)))
static bt_s32_t offer_delay(struct bt_mesh_friend *frnd, s8_t rssi, u8_t crit)
{
/* Scaling factors. The actual values are 1, 1.5, 2 & 2.5, but we
* want to avoid floating-point arithmetic.
*/
static const u8_t fact[] = { 10, 15, 20, 25 };
bt_s32_t delay;
BT_DBG("ReceiveWindowFactor %u ReceiveWindow %u RSSIFactor %u RSSI %d", fact[RECV_WIN_FACT(crit)], RECV_WIN,
fact[RSSI_FACT(crit)], rssi);
/* Delay = ReceiveWindowFactor * ReceiveWindow - RSSIFactor * RSSI */
delay = (bt_s32_t)fact[RECV_WIN_FACT(crit)] * RECV_WIN;
delay -= (bt_s32_t)fact[RSSI_FACT(crit)] * rssi;
delay /= 10;
BT_DBG("Local Delay calculated as %d ms", delay);
if (delay < 100) {
return K_MSEC(100);
}
return K_MSEC(delay);
}
int bt_mesh_friend_req(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_req *msg = (void *)buf->data;
struct bt_mesh_friend *frnd = NULL;
// u16_t old_friend;
bt_u32_t poll_to;
int i;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Request");
return -EINVAL;
}
if (msg->recv_delay <= 0x09) {
BT_WARN("Prohibited ReceiveDelay (0x%02x)", msg->recv_delay);
return -EINVAL;
}
poll_to = (((bt_u32_t)msg->poll_to[0] << 16) | ((bt_u32_t)msg->poll_to[1] << 8) | ((bt_u32_t)msg->poll_to[2]));
if (poll_to <= 0x000009 || poll_to >= 0x34bc00) {
BT_WARN("Prohibited PollTimeout (0x%06x)", poll_to);
return -EINVAL;
}
if (msg->num_elem == 0x00) {
BT_WARN("Prohibited NumElements value (0x00)");
return -EINVAL;
}
if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr + msg->num_elem - 1)) {
BT_WARN("LPN elements stretch outside of unicast range");
return -EINVAL;
}
if (!MIN_QUEUE_SIZE_LOG(msg->criteria)) {
BT_WARN("Prohibited Minimum Queue Size in Friend Request");
return -EINVAL;
}
if (CONFIG_BT_MESH_FRIEND_QUEUE_SIZE < MIN_QUEUE_SIZE(msg->criteria)) {
BT_WARN("We have a too small Friend Queue size (%u < %u)", CONFIG_BT_MESH_FRIEND_QUEUE_SIZE,
MIN_QUEUE_SIZE(msg->criteria));
return 0;
}
frnd = bt_mesh_friend_find(rx->sub->net_idx, rx->ctx.addr, true, false);
if (frnd) {
BT_WARN("Existing LPN re-requesting Friendship");
friend_clear(frnd);
goto init_friend;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
if (!bt_mesh.frnd[i].valid) {
frnd = &bt_mesh.frnd[i];
frnd->valid = 1;
break;
}
}
if (!frnd) {
BT_WARN("No free Friend contexts for new LPN");
return -ENOMEM;
}
init_friend:
frnd->lpn = rx->ctx.addr;
frnd->num_elem = msg->num_elem;
frnd->net_idx = rx->sub->net_idx;
frnd->recv_delay = msg->recv_delay;
frnd->poll_to = poll_to * 100;
frnd->lpn_counter = sys_be16_to_cpu(msg->lpn_counter);
frnd->clear.frnd = sys_be16_to_cpu(msg->prev_addr);
BT_DBG("LPN 0x%04x rssi %d recv_delay %u poll_to %ums", frnd->lpn, rx->rssi, frnd->recv_delay, frnd->poll_to);
if (BT_MESH_ADDR_IS_UNICAST(frnd->clear.frnd) && !bt_mesh_elem_find(frnd->clear.frnd)) {
clear_procedure_start(frnd);
}
k_delayed_work_submit(&frnd->timer, offer_delay(frnd, rx->rssi, msg->criteria));
friend_cred_create(rx->sub, frnd->lpn, frnd->lpn_counter, frnd->counter);
enqueue_offer(frnd, rx->rssi);
return 0;
}
static struct bt_mesh_friend_seg *get_seg(struct bt_mesh_friend *frnd, u16_t src, u64_t *seq_auth)
{
struct bt_mesh_friend_seg *unassigned = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(frnd->seg); i++) {
struct bt_mesh_friend_seg *seg = &frnd->seg[i];
struct net_buf *buf = (void *)sys_slist_peek_head(&seg->queue);
if (buf && BT_MESH_ADV(buf)->addr == src && FRIEND_ADV(buf)->seq_auth == *seq_auth) {
return seg;
}
if (!unassigned && !buf) {
unassigned = seg;
}
}
return unassigned;
}
static void enqueue_friend_pdu(struct bt_mesh_friend *frnd, enum bt_mesh_friend_pdu_type type, struct net_buf *buf)
{
struct bt_mesh_friend_seg *seg;
struct friend_adv *adv;
BT_DBG("type %u", type);
if (type == BT_MESH_FRIEND_PDU_SINGLE) {
if (frnd->sec_update) {
enqueue_update(frnd, 1);
}
enqueue_buf(frnd, buf);
return;
}
adv = FRIEND_ADV(buf);
seg = get_seg(frnd, BT_MESH_ADV(buf)->addr, &adv->seq_auth);
if (!seg) {
BT_ERR("No free friend segment RX contexts for 0x%04x", BT_MESH_ADV(buf)->addr);
net_buf_unref(buf);
return;
}
net_buf_slist_put(&seg->queue, buf);
if (type == BT_MESH_FRIEND_PDU_COMPLETE) {
if (frnd->sec_update) {
enqueue_update(frnd, 1);
}
/* Only acks should have a valid SeqAuth in the Friend queue
* (otherwise we can't easily detect them there), so clear
* the SeqAuth information from the segments before merging.
*/
SYS_SLIST_FOR_EACH_CONTAINER(&seg->queue, buf, node)
{
FRIEND_ADV(buf)->seq_auth = TRANS_SEQ_AUTH_NVAL;
frnd->queue_size++;
}
sys_slist_merge_slist(&frnd->queue, &seg->queue);
while (frnd->queue_size > CONFIG_BT_MESH_FRIEND_QUEUE_SIZE) {
struct net_buf *buf = net_buf_slist_get(&frnd->queue);
__ASSERT_NO_MSG(buf != NULL);
BT_WARN("Discarding buffer %p for LPN 0x%04x", buf, frnd->lpn);
net_buf_unref(buf);
frnd->queue_size--;
}
}
}
static void buf_send_start(u16_t duration, int err, void *user_data)
{
struct bt_mesh_friend *frnd = user_data;
BT_DBG("err %d", err);
frnd->pending_buf = 0;
/* Friend Offer doesn't follow the re-sending semantics */
if (!frnd->established) {
net_buf_unref(frnd->last);
frnd->last = NULL;
}
}
static void buf_send_end(int err, void *user_data)
{
struct bt_mesh_friend *frnd = user_data;
BT_DBG("err %d", err);
if (frnd->pending_req) {
BT_WARN("Another request before previous completed sending");
return;
}
if (frnd->established) {
k_delayed_work_submit(&frnd->timer, frnd->poll_to);
BT_DBG("Waiting %u ms for next poll", frnd->poll_to);
} else {
/* Friend offer timeout is 1 second */
k_delayed_work_submit(&frnd->timer, K_SECONDS(1));
BT_DBG("Waiting for first poll");
}
}
static void friend_timeout(struct k_work *work)
{
struct bt_mesh_friend *frnd = CONTAINER_OF(work, struct bt_mesh_friend, timer.work);
static const struct bt_mesh_send_cb buf_sent_cb = {
.start = buf_send_start,
.end = buf_send_end,
};
__ASSERT_NO_MSG(frnd->pending_buf == 0);
BT_DBG("lpn 0x%04x send_last %u last %p", frnd->lpn, frnd->send_last, frnd->last);
if (frnd->send_last && frnd->last) {
BT_DBG("Sending frnd->last %p", frnd->last);
frnd->send_last = 0;
goto send_last;
}
if (frnd->established && !frnd->pending_req) {
BT_WARN("Friendship lost with 0x%04x", frnd->lpn);
friend_clear(frnd);
return;
}
frnd->last = net_buf_slist_get(&frnd->queue);
if (!frnd->last) {
BT_WARN("Friendship not established with 0x%04x", frnd->lpn);
friend_clear(frnd);
return;
}
BT_DBG("Sending buf %p from Friend Queue of LPN 0x%04x", frnd->last, frnd->lpn);
frnd->queue_size--;
send_last:
frnd->pending_req = 0;
frnd->pending_buf = 1;
bt_mesh_adv_send(frnd->last, &buf_sent_cb, frnd);
}
int bt_mesh_friend_init(void)
{
int i;
NET_BUF_POOL_INIT(friend_buf_pool);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
int j;
frnd->net_idx = BT_MESH_KEY_UNUSED;
sys_slist_init(&frnd->queue);
k_delayed_work_init(&frnd->timer, friend_timeout);
k_delayed_work_init(&frnd->clear.timer, clear_timeout);
for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) {
sys_slist_init(&frnd->seg[j].queue);
}
}
return 0;
}
static void friend_purge_old_ack(struct bt_mesh_friend *frnd, u64_t *seq_auth, u16_t src)
{
sys_snode_t *cur, *prev = NULL;
BT_DBG("SeqAuth %llx src 0x%04x", *seq_auth, src);
for (cur = sys_slist_peek_head(&frnd->queue); cur != NULL; prev = cur, cur = sys_slist_peek_next(cur)) {
struct net_buf *buf = (void *)cur;
if (BT_MESH_ADV(buf)->addr == src && FRIEND_ADV(buf)->seq_auth == *seq_auth) {
BT_DBG("Removing old ack from Friend Queue");
sys_slist_remove(&frnd->queue, prev, cur);
frnd->queue_size--;
/* Make sure old slist entry state doesn't remain */
buf->frags = NULL;
net_buf_unref(buf);
break;
}
}
}
static void friend_lpn_enqueue_rx(struct bt_mesh_friend *frnd, struct bt_mesh_net_rx *rx,
enum bt_mesh_friend_pdu_type type, u64_t *seq_auth, struct net_buf_simple *sbuf)
{
struct friend_pdu_info info;
struct net_buf *buf;
BT_DBG("LPN 0x%04x queue_size %u", frnd->lpn, frnd->queue_size);
if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) {
friend_purge_old_ack(frnd, seq_auth, rx->ctx.addr);
}
info.src = rx->ctx.addr;
info.dst = rx->ctx.recv_dst;
if (rx->net_if == BT_MESH_NET_IF_LOCAL) {
info.ttl = rx->ctx.recv_ttl;
} else {
info.ttl = rx->ctx.recv_ttl - 1;
}
info.ctl = rx->ctl;
info.seq[0] = (rx->seq >> 16);
info.seq[1] = (rx->seq >> 8);
info.seq[2] = rx->seq;
info.iv_index = BT_MESH_NET_IVI_RX(rx);
buf = create_friend_pdu(frnd, &info, sbuf);
if (!buf) {
BT_ERR("Failed to encode Friend buffer");
return;
}
if (seq_auth) {
FRIEND_ADV(buf)->seq_auth = *seq_auth;
}
enqueue_friend_pdu(frnd, type, buf);
BT_DBG("Queued message for LPN 0x%04x, queue_size %u", frnd->lpn, frnd->queue_size);
}
static void friend_lpn_enqueue_tx(struct bt_mesh_friend *frnd, struct bt_mesh_net_tx *tx,
enum bt_mesh_friend_pdu_type type, u64_t *seq_auth, struct net_buf_simple *sbuf)
{
struct friend_pdu_info info;
struct net_buf *buf;
bt_u32_t seq;
BT_DBG("LPN 0x%04x", frnd->lpn);
if (type == BT_MESH_FRIEND_PDU_SINGLE && seq_auth) {
friend_purge_old_ack(frnd, seq_auth, tx->src);
}
info.src = tx->src;
info.dst = tx->ctx->addr;
info.ttl = tx->ctx->send_ttl;
info.ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED);
seq = bt_mesh_next_seq();
info.seq[0] = seq >> 16;
info.seq[1] = seq >> 8;
info.seq[2] = seq;
info.iv_index = BT_MESH_NET_IVI_TX;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, &seq);
}
#endif
buf = create_friend_pdu(frnd, &info, sbuf);
if (!buf) {
BT_ERR("Failed to encode Friend buffer");
return;
}
if (seq_auth) {
FRIEND_ADV(buf)->seq_auth = *seq_auth;
}
enqueue_friend_pdu(frnd, type, buf);
BT_DBG("Queued message for LPN 0x%04x", frnd->lpn);
}
static bool friend_lpn_matches(struct bt_mesh_friend *frnd, u16_t net_idx, u16_t addr)
{
int i;
if (!frnd->established) {
return false;
}
if (net_idx != frnd->net_idx) {
return false;
}
if (BT_MESH_ADDR_IS_UNICAST(addr)) {
return is_lpn_unicast(frnd, addr);
}
for (i = 0; i < ARRAY_SIZE(frnd->sub_list); i++) {
if (frnd->sub_list[i] == addr) {
return true;
}
}
return false;
}
bool bt_mesh_friend_match(u16_t net_idx, u16_t addr)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (friend_lpn_matches(frnd, net_idx, addr)) {
BT_DBG("LPN 0x%04x matched address 0x%04x", frnd->lpn, addr);
return true;
}
}
BT_DBG("No matching LPN for address 0x%04x", addr);
return false;
}
void bt_mesh_friend_enqueue_rx(struct bt_mesh_net_rx *rx, enum bt_mesh_friend_pdu_type type, u64_t *seq_auth,
struct net_buf_simple *sbuf)
{
int i;
if (!rx->friend_match || (rx->ctx.recv_ttl <= 1 && rx->net_if != BT_MESH_NET_IF_LOCAL) ||
bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) {
return;
}
BT_DBG("recv_ttl %u net_idx 0x%04x src 0x%04x dst 0x%04x", rx->ctx.recv_ttl, rx->sub->net_idx, rx->ctx.addr,
rx->ctx.recv_dst);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (friend_lpn_matches(frnd, rx->sub->net_idx, rx->ctx.recv_dst)) {
friend_lpn_enqueue_rx(frnd, rx, type, seq_auth, sbuf);
}
}
}
bool bt_mesh_friend_enqueue_tx(struct bt_mesh_net_tx *tx, enum bt_mesh_friend_pdu_type type, u64_t *seq_auth,
struct net_buf_simple *sbuf)
{
bool matched = false;
int i;
if (!bt_mesh_friend_match(tx->sub->net_idx, tx->ctx->addr) || bt_mesh_friend_get() != BT_MESH_FRIEND_ENABLED) {
return matched;
}
BT_DBG("net_idx 0x%04x dst 0x%04x src 0x%04x", tx->sub->net_idx, tx->ctx->addr, tx->src);
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
if (friend_lpn_matches(frnd, tx->sub->net_idx, tx->ctx->addr)) {
friend_lpn_enqueue_tx(frnd, tx, type, seq_auth, sbuf);
matched = true;
}
}
return matched;
}
void bt_mesh_friend_clear_incomplete(struct bt_mesh_subnet *sub, u16_t src, u16_t dst, u64_t *seq_auth)
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.frnd); i++) {
struct bt_mesh_friend *frnd = &bt_mesh.frnd[i];
int j;
if (!friend_lpn_matches(frnd, sub->net_idx, dst)) {
continue;
}
for (j = 0; j < ARRAY_SIZE(frnd->seg); j++) {
struct bt_mesh_friend_seg *seg = &frnd->seg[j];
struct net_buf *buf;
buf = (void *)sys_slist_peek_head(&seg->queue);
if (!buf) {
continue;
}
if (BT_MESH_ADV(buf)->addr != src) {
continue;
}
if (FRIEND_ADV(buf)->seq_auth != *seq_auth) {
continue;
}
BT_WARN("Clearing incomplete segments for 0x%04x", src);
while (!sys_slist_is_empty(&seg->queue)) {
net_buf_unref(net_buf_slist_get(&seg->queue));
}
}
}
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/friend.c | C | apache-2.0 | 34,885 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <ble_types/types.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "net.h"
#include "foundation.h"
#ifdef CONFIG_BT_MESH_HEALTH_CLI
static bt_s32_t msg_timeout = K_SECONDS(2);
static struct bt_mesh_health_cli *health_cli;
struct bt_mesh_health_cli g_health_cli;
struct health_fault_param {
u16_t cid;
u8_t *expect_test_id;
u8_t *test_id;
u8_t *faults;
size_t *fault_count;
};
static void health_fault_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct health_fault_param *param;
u8_t test_id;
u16_t cid;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s",
ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (health_cli->op_pending != OP_HEALTH_FAULT_STATUS) {
BT_WARN("Unexpected Health Fault Status message");
return;
}
param = health_cli->op_param;
test_id = net_buf_simple_pull_u8(buf);
if (param && param->expect_test_id && test_id != *param->expect_test_id) {
BT_WARN("Health fault with unexpected Test ID");
return;
}
cid = net_buf_simple_pull_le16(buf);
if (param)
{
if (cid != param->cid) {
BT_WARN("Health fault with unexpected Company ID");
return;
}
if (param->test_id) {
*param->test_id = test_id;
}
if (buf->len > *param->fault_count) {
BT_WARN("Got more faults than there's space for");
} else {
*param->fault_count = buf->len;
}
memcpy(param->faults, buf->data, *param->fault_count);
k_sem_give(&health_cli->op_sync);
}
}
static void health_current_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct bt_mesh_health_cli *cli = model->user_data;
u8_t test_id;
u16_t cid;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s",
ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
test_id = net_buf_simple_pull_u8(buf);
cid = net_buf_simple_pull_le16(buf);
BT_DBG("Test ID 0x%02x Company ID 0x%04x Fault Count %u",
test_id, cid, buf->len);
if (!cli->current_status) {
BT_WARN("No Current Status callback available");
return;
}
cli->current_status(cli, ctx->addr, test_id, cid, buf->data, buf->len);
}
struct health_period_param {
u8_t *divisor;
};
static void health_period_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct health_period_param *param;
u8_t divisor;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s",
ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (health_cli->op_pending != OP_HEALTH_PERIOD_STATUS) {
BT_WARN("Unexpected Health Period Status message");
return;
}
param = health_cli->op_param;
if (param) {
divisor = net_buf_simple_pull_u8(buf);
if(param->divisor){
*param->divisor = divisor;
}
k_sem_give(&health_cli->op_sync);
}
}
struct health_attention_param {
u8_t *attention;
};
static void health_attention_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct health_attention_param *param;
BT_DBG("net_idx 0x%04x app_idx 0x%04x src 0x%04x len %u: %s",
ctx->net_idx, ctx->app_idx, ctx->addr, buf->len,
bt_hex(buf->data, buf->len));
if (health_cli->op_pending != OP_ATTENTION_STATUS) {
BT_WARN("Unexpected Health Attention Status message");
return;
}
param = health_cli->op_param;
if (param && param->attention) {
*param->attention = net_buf_simple_pull_u8(buf);
}
if (param) {
k_sem_give(&health_cli->op_sync);
}
}
const struct bt_mesh_model_op bt_mesh_health_cli_op[] = {
{ OP_HEALTH_FAULT_STATUS, 3, health_fault_status },
{ OP_HEALTH_CURRENT_STATUS, 3, health_current_status },
{ OP_HEALTH_PERIOD_STATUS, 1, health_period_status },
{ OP_ATTENTION_STATUS, 1, health_attention_status },
BT_MESH_MODEL_OP_END,
};
static int cli_prepare(void *param, bt_u32_t op)
{
if (!health_cli) {
BT_ERR("No available Health Client context!");
return -EINVAL;
}
if (health_cli->op_pending) {
BT_WARN("Another synchronous operation pending");
return -EBUSY;
}
health_cli->op_param = param;
health_cli->op_pending = op;
return 0;
}
static void cli_reset(void)
{
health_cli->op_pending = 0;
health_cli->op_param = NULL;
}
static int cli_wait(void)
{
int err;
err = k_sem_take(&health_cli->op_sync, msg_timeout);
cli_reset();
return err;
}
int bt_mesh_health_attention_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t *attention)
{
if (attention == NULL)
{
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_attention_param param = {
.attention = attention,
};
int err;
err = cli_prepare(¶m, OP_ATTENTION_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_ATTENTION_GET);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
return cli_wait();
}
int bt_mesh_health_attention_set(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t attention, u8_t *updated_attention)
{
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_attention_param param = {
.attention = updated_attention,
};
int err;
err = cli_prepare(¶m, OP_ATTENTION_STATUS);
if (err) {
return err;
}
if (updated_attention) {
bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET);
} else {
bt_mesh_model_msg_init(&msg, OP_ATTENTION_SET_UNREL);
}
net_buf_simple_add_u8(&msg, attention);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!updated_attention) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_health_period_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t *divisor)
{
if (divisor == NULL)
{
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 0 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_period_param param = {
.divisor = divisor,
};
int err;
err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_GET);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
return cli_wait();
}
int bt_mesh_health_period_set(u16_t net_idx, u16_t addr, u16_t app_idx,
u8_t divisor, u8_t *updated_divisor)
{
if (divisor > 15)
{
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_period_param param = {
.divisor = updated_divisor,
};
int err;
err = cli_prepare(¶m, OP_HEALTH_PERIOD_STATUS);
if (err) {
return err;
}
if (updated_divisor) {
bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET);
} else {
bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_SET_UNREL);
}
net_buf_simple_add_u8(&msg, divisor);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!updated_divisor) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_health_fault_test(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t test_id, u8_t *faults,
size_t *fault_count)
{
if (fault_count == NULL){
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 3 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_fault_param param = {
.cid = cid,
.expect_test_id = &test_id,
.faults = faults,
.fault_count = fault_count,
};
int err;
err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS);
if (err) {
return err;
}
if (faults) {
bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST);
} else {
bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_TEST_UNREL);
}
net_buf_simple_add_u8(&msg, test_id);
net_buf_simple_add_le16(&msg, cid);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!faults) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_health_fault_clear(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t *test_id, u8_t *faults,
size_t *fault_count)
{
if (faults == NULL || fault_count == NULL)
{
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_fault_param param = {
.cid = cid,
.test_id = test_id,
.faults = faults,
.fault_count = fault_count,
};
int err;
err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS);
if (err) {
return err;
}
if (test_id) {
bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR);
} else {
bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_CLEAR_UNREL);
}
net_buf_simple_add_le16(&msg, cid);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
if (!test_id) {
cli_reset();
return 0;
}
return cli_wait();
}
int bt_mesh_health_fault_get(u16_t net_idx, u16_t addr, u16_t app_idx,
u16_t cid, u8_t *test_id, u8_t *faults,
size_t *fault_count)
{
if (test_id == NULL || faults == NULL || fault_count == NULL)
{
return -EINVAL;
}
NET_BUF_SIMPLE_DEFINE(msg, 2 + 2 + 4);
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = app_idx,
.addr = addr,
.send_ttl = BT_MESH_TTL_DEFAULT,
};
struct health_fault_param param = {
.cid = cid,
.test_id = test_id,
.faults = faults,
.fault_count = fault_count,
};
int err;
err = cli_prepare(¶m, OP_HEALTH_FAULT_STATUS);
if (err) {
return err;
}
bt_mesh_model_msg_init(&msg, OP_HEALTH_FAULT_GET);
net_buf_simple_add_le16(&msg, cid);
err = bt_mesh_model_send(health_cli->model, &ctx, &msg, NULL, NULL);
if (err) {
BT_ERR("model_send() failed (err %d)", err);
cli_reset();
return err;
}
return cli_wait();
}
bt_s32_t bt_mesh_health_cli_timeout_get(void)
{
return msg_timeout;
}
void bt_mesh_health_cli_timeout_set(bt_s32_t timeout)
{
msg_timeout = timeout;
}
int bt_mesh_health_cli_set(struct bt_mesh_model *model)
{
if (!model || !model->user_data) {
BT_ERR("No Health Client context for given model");
return -EINVAL;
}
health_cli = model->user_data;
return 0;
}
int bt_mesh_health_cli_init(struct bt_mesh_model *model, bool primary)
{
if (model == NULL)
{
return -EINVAL;
}
struct bt_mesh_health_cli *cli = model->user_data;
BT_DBG("primary %u", primary);
if (!cli) {
BT_ERR("No Health Client context provided");
return -EINVAL;
}
cli = model->user_data;
cli->model = model;
k_sem_init(&cli->op_sync, 0, 1);
/* Set the default health client pointer */
if (!health_cli) {
health_cli = cli;
}
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/health_cli.c | C | apache-2.0 | 12,062 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <ble_types/types.h>
#include <misc/byteorder.h>
#include <misc/util.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "mesh.h"
#include "adv.h"
#include "net.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#define HEALTH_TEST_STANDARD 0x00
/* Health Server context of the primary element */
struct bt_mesh_health_srv *health_srv;
struct bt_mesh_model_pub g_health_pub = {
.msg = NET_BUF_SIMPLE(1 + 3 + 0),
};
struct bt_mesh_health_srv g_health_srv;
static void health_get_registered(struct bt_mesh_model *mod,
u16_t company_id,
struct net_buf_simple *msg)
{
struct bt_mesh_health_srv *srv = mod->user_data;
u8_t *test_id;
BT_DBG("Company ID 0x%04x", company_id);
bt_mesh_model_msg_init(msg, OP_HEALTH_FAULT_STATUS);
test_id = net_buf_simple_add(msg, 1);
net_buf_simple_add_le16(msg, company_id);
if (srv->cb && srv->cb->fault_get_reg) {
u8_t fault_count = net_buf_simple_tailroom(msg) - 4;
int err;
err = srv->cb->fault_get_reg(mod, company_id, test_id,
net_buf_simple_tail(msg),
&fault_count);
if (err) {
BT_ERR("Failed to get faults (err %d)", err);
*test_id = HEALTH_TEST_STANDARD;
} else {
net_buf_simple_add(msg, fault_count);
}
} else {
BT_WARN("No callback for getting faults");
*test_id = HEALTH_TEST_STANDARD;
}
}
static size_t health_get_current(struct bt_mesh_model *mod,
struct net_buf_simple *msg)
{
struct bt_mesh_health_srv *srv = mod->user_data;
const struct bt_mesh_comp *comp;
u8_t *test_id, *company_ptr;
u16_t company_id;
u8_t fault_count;
int err;
bt_mesh_model_msg_init(msg, OP_HEALTH_CURRENT_STATUS);
test_id = net_buf_simple_add(msg, 1);
company_ptr = net_buf_simple_add(msg, sizeof(company_id));
comp = bt_mesh_comp_get();
if (srv->cb && srv->cb->fault_get_cur) {
fault_count = net_buf_simple_tailroom(msg);
err = srv->cb->fault_get_cur(mod, test_id, &company_id,
net_buf_simple_tail(msg),
&fault_count);
if (err) {
BT_ERR("Failed to get faults (err %d)", err);
sys_put_le16(comp->cid, company_ptr);
*test_id = HEALTH_TEST_STANDARD;
fault_count = 0;
} else {
sys_put_le16(company_id, company_ptr);
net_buf_simple_add(msg, fault_count);
}
} else {
BT_WARN("No callback for getting faults");
sys_put_le16(comp->cid, company_ptr);
*test_id = HEALTH_TEST_STANDARD;
fault_count = 0;
}
return fault_count;
}
static void health_fault_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
u16_t company_id;
company_id = net_buf_simple_pull_le16(buf);
BT_DBG("company_id 0x%04x", company_id);
health_get_registered(model, company_id, &sdu);
if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) {
BT_ERR("Unable to send Health Current Status response");
}
}
static void health_fault_clear_unrel(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct bt_mesh_health_srv *srv = model->user_data;
u16_t company_id;
company_id = net_buf_simple_pull_le16(buf);
BT_DBG("company_id 0x%04x", company_id);
if (srv->cb && srv->cb->fault_clear) {
srv->cb->fault_clear(model, company_id);
}
}
static void health_fault_clear(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
struct bt_mesh_health_srv *srv = model->user_data;
u16_t company_id;
company_id = net_buf_simple_pull_le16(buf);
BT_DBG("company_id 0x%04x", company_id);
if (srv->cb && srv->cb->fault_clear) {
srv->cb->fault_clear(model, company_id);
}
health_get_registered(model, company_id, &sdu);
if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) {
BT_ERR("Unable to send Health Current Status response");
}
}
static void health_fault_test_unrel(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
struct bt_mesh_health_srv *srv = model->user_data;
u16_t company_id;
u8_t test_id;
test_id = net_buf_simple_pull_u8(buf);
company_id = net_buf_simple_pull_le16(buf);
BT_DBG("test 0x%02x company 0x%04x", test_id, company_id);
if (srv->cb && srv->cb->fault_test) {
srv->cb->fault_test(model, test_id, company_id);
}
}
static void health_fault_test(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(sdu, BT_MESH_TX_SDU_MAX);
struct bt_mesh_health_srv *srv = model->user_data;
u16_t company_id;
u8_t test_id;
BT_DBG("");
test_id = net_buf_simple_pull_u8(buf);
company_id = net_buf_simple_pull_le16(buf);
BT_DBG("test 0x%02x company 0x%04x", test_id, company_id);
if (srv->cb && srv->cb->fault_test) {
int err;
err = srv->cb->fault_test(model, test_id, company_id);
if (err) {
BT_WARN("Running fault test failed with err %d", err);
return;
}
}
health_get_registered(model, company_id, &sdu);
if (bt_mesh_model_send(model, ctx, &sdu, NULL, NULL)) {
BT_ERR("Unable to send Health Current Status response");
}
}
static void send_attention_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
struct bt_mesh_health_srv *srv = model->user_data;
u8_t time;
time = k_delayed_work_remaining_get(&srv->attn_timer) / 1000;
BT_DBG("%u second%s", time, (time == 1) ? "" : "s");
bt_mesh_model_msg_init(&msg, OP_ATTENTION_STATUS);
net_buf_simple_add_u8(&msg, time);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Attention Status");
}
}
static void attention_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
BT_DBG("");
send_attention_status(model, ctx);
}
static void attention_set_unrel(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t time;
time = net_buf_simple_pull_u8(buf);
BT_DBG("%u second%s", time, (time == 1) ? "" : "s");
bt_mesh_attention(model, time);
}
static void attention_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
BT_DBG("");
attention_set_unrel(model, ctx, buf);
send_attention_status(model, ctx);
}
static void send_health_period_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx)
{
/* Needed size: opcode (2 bytes) + msg + MIC */
NET_BUF_SIMPLE_DEFINE(msg, 2 + 1 + 4);
bt_mesh_model_msg_init(&msg, OP_HEALTH_PERIOD_STATUS);
net_buf_simple_add_u8(&msg, model->pub->period_div);
if (bt_mesh_model_send(model, ctx, &msg, NULL, NULL)) {
BT_ERR("Unable to send Health Period Status");
}
}
static void health_period_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
BT_DBG("");
send_health_period_status(model, ctx);
}
static void health_period_set_unrel(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t period;
period = net_buf_simple_pull_u8(buf);
if (period > 15) {
BT_WARN("Prohibited period value %u", period);
return;
}
BT_DBG("period %u", period);
if(0 != period){
model->pub->fast_period = 1;
}
model->pub->period_div = period;
}
static void health_period_set(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
BT_DBG("");
health_period_set_unrel(model, ctx, buf);
send_health_period_status(model, ctx);
}
const struct bt_mesh_model_op bt_mesh_health_srv_op[] = {
{ OP_HEALTH_FAULT_GET, 2, health_fault_get },
{ OP_HEALTH_FAULT_CLEAR, 2, health_fault_clear },
{ OP_HEALTH_FAULT_CLEAR_UNREL, 2, health_fault_clear_unrel },
{ OP_HEALTH_FAULT_TEST, 3, health_fault_test },
{ OP_HEALTH_FAULT_TEST_UNREL, 3, health_fault_test_unrel },
{ OP_HEALTH_PERIOD_GET, 0, health_period_get },
{ OP_HEALTH_PERIOD_SET, 1, health_period_set },
{ OP_HEALTH_PERIOD_SET_UNREL, 1, health_period_set_unrel },
{ OP_ATTENTION_GET, 0, attention_get },
{ OP_ATTENTION_SET, 1, attention_set },
{ OP_ATTENTION_SET_UNREL, 1, attention_set_unrel },
BT_MESH_MODEL_OP_END,
};
static int health_pub_update(struct bt_mesh_model *mod)
{
struct bt_mesh_model_pub *pub = mod->pub;
size_t count;
BT_DBG("");
count = health_get_current(mod, pub->msg);
if (!count) {
pub->period_div = 0;
}
return 0;
}
int bt_mesh_fault_update(struct bt_mesh_elem *elem)
{
struct bt_mesh_model *mod;
if (!elem) {
return -EINVAL;
}
mod = bt_mesh_model_find(elem, BT_MESH_MODEL_ID_HEALTH_SRV);
if (!mod) {
return -EINVAL;
}
/* Let periodic publishing, if enabled, take care of sending the
* Health Current Status.
*/
if (bt_mesh_model_pub_period_get(mod)) {
return 0;
}
health_pub_update(mod);
return bt_mesh_model_publish(mod);
}
static void attention_off(struct k_work *work)
{
struct bt_mesh_health_srv *srv = CONTAINER_OF(work,
struct bt_mesh_health_srv,
attn_timer.work);
BT_DBG("");
if (srv->cb && srv->cb->attn_off) {
srv->cb->attn_off(srv->model);
}
}
int bt_mesh_health_srv_init(struct bt_mesh_model *model, bool primary)
{
struct bt_mesh_health_srv *srv = model->user_data;
if (!srv) {
if (!primary) {
return 0;
}
BT_ERR("No Health Server context provided");
return -EINVAL;
}
if (!model->pub) {
BT_ERR("Health Server has no publication support");
return -EINVAL;
}
model->pub->update = health_pub_update;
k_delayed_work_init(&srv->attn_timer, attention_off);
srv->model = model;
if (primary) {
health_srv = srv;
}
return 0;
}
void bt_mesh_attention(struct bt_mesh_model *model, u8_t time)
{
if(0 == time) {
BT_DBG("reset attention timer");
}
struct bt_mesh_health_srv *srv;
if (!model) {
srv = health_srv;
if (!srv) {
BT_WARN("No Health Server available");
return;
}
model = srv->model;
} else {
srv = model->user_data;
}
if (time) {
if (srv->cb && srv->cb->attn_on) {
srv->cb->attn_on(model);
}
k_delayed_work_submit(&srv->attn_timer, time * 1000);
} else {
k_delayed_work_cancel(&srv->attn_timer);
if (srv->cb && srv->cb->attn_off) {
srv->cb->attn_off(model);
}
}
}
int health_srv_cb_register(struct bt_mesh_health_srv_cb *health_cb)
{
if(!health_cb || !health_srv){
return -EINVAL;
}
health_srv->cb = health_cb;
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/health_srv.c | C | apache-2.0 | 10,883 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <ble_os.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#ifdef CONFIG_BT_MESH_LOW_POWER
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_LOW_POWER)
#include "common/log.h"
#include "crypto.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "ble_transport.h"
#include "access.h"
#include "beacon.h"
#include "foundation.h"
#include "lpn.h"
#include "bt_errno.h"
#if defined(CONFIG_BT_MESH_LPN_AUTO)
#define LPN_AUTO_TIMEOUT K_SECONDS(CONFIG_BT_MESH_LPN_AUTO_TIMEOUT)
#else
#define LPN_AUTO_TIMEOUT 0
#endif
#define LPN_RECV_DELAY CONFIG_BT_MESH_LPN_RECV_DELAY
#define SCAN_LATENCY MIN(CONFIG_BT_MESH_LPN_SCAN_LATENCY, \
LPN_RECV_DELAY)
#define FRIEND_REQ_RETRY_TIMEOUT K_SECONDS(CONFIG_BT_MESH_LPN_RETRY_TIMEOUT)
#define FRIEND_REQ_WAIT K_MSEC(100)
#define FRIEND_REQ_SCAN K_SECONDS(1)
#define FRIEND_REQ_TIMEOUT (FRIEND_REQ_WAIT + FRIEND_REQ_SCAN)
#define POLL_RETRY_TIMEOUT K_MSEC(100)
#define REQ_RETRY_DURATION(lpn) (4 * (LPN_RECV_DELAY + (lpn)->adv_duration + \
(lpn)->recv_win + POLL_RETRY_TIMEOUT))
#define POLL_TIMEOUT_INIT (CONFIG_BT_MESH_LPN_INIT_POLL_TIMEOUT * 100)
#define POLL_TIMEOUT_MAX(lpn) ((CONFIG_BT_MESH_LPN_POLL_TIMEOUT * 100) - \
REQ_RETRY_DURATION(lpn))
#ifndef CONFIG_BT_BQB
#define REQ_ATTEMPTS(lpn) (POLL_TIMEOUT_MAX(lpn) < K_SECONDS(3) ? 2 : 4)
#else
#define REQ_ATTEMPTS(lpn) (POLL_TIMEOUT_MAX(lpn) < K_SECONDS(3) ? 2 : 16)
#endif
#define CLEAR_ATTEMPTS 2
#define LPN_CRITERIA ((CONFIG_BT_MESH_LPN_MIN_QUEUE_SIZE) | \
(CONFIG_BT_MESH_LPN_RSSI_FACTOR << 3) | \
(CONFIG_BT_MESH_LPN_RECV_WIN_FACTOR << 5))
#define POLL_TO(to) { (u8_t)((to) >> 16), (u8_t)((to) >> 8), (u8_t)(to) }
#define LPN_POLL_TO POLL_TO(CONFIG_BT_MESH_LPN_POLL_TIMEOUT)
/* 2 transmissions, 20ms interval */
#define POLL_XMIT BT_MESH_TRANSMIT(1, 20)
static void (*lpn_cb)(u16_t friend_addr, bool established);
extern void lpn_hb_send();
#if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER)
static const char *state2str(int state)
{
switch (state) {
case BT_MESH_LPN_DISABLED:
return "disabled";
case BT_MESH_LPN_CLEAR:
return "clear";
case BT_MESH_LPN_TIMER:
return "timer";
case BT_MESH_LPN_ENABLED:
return "enabled";
case BT_MESH_LPN_REQ_WAIT:
return "req wait";
case BT_MESH_LPN_WAIT_OFFER:
return "wait offer";
case BT_MESH_LPN_ESTABLISHED:
return "established";
case BT_MESH_LPN_RECV_DELAY:
return "recv delay";
case BT_MESH_LPN_WAIT_UPDATE:
return "wait update";
default:
return "(unknown)";
}
}
#endif /* CONFIG_BT_MESH_DEBUG_LOW_POWER */
static inline void lpn_set_state(int state)
{
#if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER)
BT_DBG("%s -> %s", state2str(bt_mesh.lpn.state), state2str(state));
#endif
bt_mesh.lpn.state = state;
}
static inline void group_zero(atomic_t *target)
{
#if CONFIG_BT_MESH_LPN_GROUPS > 32
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) {
atomic_set(&target[i], 0);
}
#else
atomic_set(target, 0);
#endif
}
static inline void group_set(atomic_t *target, atomic_t *source)
{
#if CONFIG_BT_MESH_LPN_GROUPS > 32
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) {
atomic_or(&target[i], atomic_get(&source[i]));
}
#else
atomic_or(target, atomic_get(source));
#endif
}
static inline void group_clear(atomic_t *target, atomic_t *source)
{
#if CONFIG_BT_MESH_LPN_GROUPS > 32
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) {
atomic_and(&target[i], ~atomic_get(&source[i]));
}
#else
atomic_and(target, ~atomic_get(source));
#endif
}
static void clear_friendship(bool force, bool disable);
static void friend_clear_sent(int err, void *user_data)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
/* We're switching away from Low Power behavior, so permanently
* enable scanning.
*/
bt_mesh_scan_enable();
lpn->req_attempts++;
if (err) {
BT_ERR("Sending Friend Request failed (err %d)", err);
lpn_set_state(BT_MESH_LPN_ENABLED);
clear_friendship(false, lpn->disable);
return;
}
lpn_set_state(BT_MESH_LPN_CLEAR);
k_delayed_work_submit(&lpn->timer, FRIEND_REQ_TIMEOUT);
}
static const struct bt_mesh_send_cb clear_sent_cb = {
.end = friend_clear_sent,
};
static int send_friend_clear(void)
{
struct bt_mesh_msg_ctx ctx = {
.net_idx = bt_mesh.sub[0].net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = bt_mesh.lpn.frnd,
.send_ttl = 0,
};
struct bt_mesh_net_tx tx = {
.sub = &bt_mesh.sub[0],
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
.xmit = bt_mesh_net_transmit_get(),
};
struct bt_mesh_ctl_friend_clear req = {
.lpn_addr = sys_cpu_to_be16(tx.src),
.lpn_counter = sys_cpu_to_be16(bt_mesh.lpn.counter),
};
BT_DBG("");
return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_CLEAR, &req,
sizeof(req), NULL, &clear_sent_cb, NULL);
}
static void clear_friendship(bool force, bool disable)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
BT_DBG("force %u disable %u", force, disable);
if (!force && lpn->established && !lpn->clear_success &&
lpn->req_attempts < CLEAR_ATTEMPTS) {
send_friend_clear();
lpn->disable = disable;
return;
}
bt_mesh_rx_reset();
k_delayed_work_cancel(&lpn->timer);
friend_cred_del(bt_mesh.sub[0].net_idx, lpn->frnd);
if (lpn->clear_success) {
lpn->old_friend = BT_MESH_ADDR_UNASSIGNED;
} else {
lpn->old_friend = lpn->frnd;
}
if (lpn_cb && lpn->frnd != BT_MESH_ADDR_UNASSIGNED) {
lpn_cb(lpn->frnd, false);
}
lpn->frnd = BT_MESH_ADDR_UNASSIGNED;
lpn->fsn = 0;
lpn->req_attempts = 0;
lpn->recv_win = 0;
lpn->queue_size = 0;
lpn->disable = 0;
lpn->sent_req = 0;
lpn->established = 0;
lpn->clear_success = 0;
group_zero(lpn->added);
group_zero(lpn->pending);
group_zero(lpn->to_remove);
/* Set this to 1 to force group subscription when the next
* Friendship is created, in case lpn->groups doesn't get
* modified meanwhile.
*/
lpn->groups_changed = 1;
if (disable) {
lpn_set_state(BT_MESH_LPN_DISABLED);
lpn_hb_send();
return;
}
lpn_set_state(BT_MESH_LPN_ENABLED);
lpn_hb_send();
k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT);
}
static void friend_req_sent(u16_t duration, int err, void *user_data)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
if (err) {
BT_ERR("Sending Friend Request failed (err %d)", err);
return;
}
lpn->adv_duration = duration;
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
k_delayed_work_submit(&lpn->timer, FRIEND_REQ_WAIT);
lpn_set_state(BT_MESH_LPN_REQ_WAIT);
} else {
k_delayed_work_submit(&lpn->timer,
duration + FRIEND_REQ_TIMEOUT);
lpn_set_state(BT_MESH_LPN_WAIT_OFFER);
}
}
static const struct bt_mesh_send_cb friend_req_sent_cb = {
.start = friend_req_sent,
};
static int send_friend_req(struct bt_mesh_lpn *lpn)
{
const struct bt_mesh_comp *comp = bt_mesh_comp_get();
struct bt_mesh_msg_ctx ctx = {
.net_idx = bt_mesh.sub[0].net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = BT_MESH_ADDR_FRIENDS,
.send_ttl = 0,
};
struct bt_mesh_net_tx tx = {
.sub = &bt_mesh.sub[0],
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
.xmit = POLL_XMIT,
};
struct bt_mesh_ctl_friend_req req = {
.criteria = LPN_CRITERIA,
.recv_delay = LPN_RECV_DELAY,
.poll_to = LPN_POLL_TO,
.prev_addr = sys_cpu_to_be16(lpn->old_friend),
.num_elem = comp->elem_count,
.lpn_counter = sys_cpu_to_be16(lpn->counter),
};
BT_DBG("");
return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_REQ, &req,
sizeof(req), NULL, &friend_req_sent_cb, NULL);
}
static void req_sent(u16_t duration, int err, void *user_data)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
#if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER)
BT_DBG("req 0x%02x duration %u err %d state %s",
lpn->sent_req, duration, err, state2str(lpn->state));
#endif
if (err) {
BT_ERR("Sending request failed (err %d)", err);
lpn->sent_req = 0;
group_zero(lpn->pending);
return;
}
lpn->req_attempts++;
lpn->adv_duration = duration;
if (lpn->established || IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
lpn_set_state(BT_MESH_LPN_RECV_DELAY);
/* We start scanning a bit early to elimitate risk of missing
* response data due to HCI and other latencies.
*/
k_delayed_work_submit(&lpn->timer,
LPN_RECV_DELAY - SCAN_LATENCY);
} else {
k_delayed_work_submit(&lpn->timer,
LPN_RECV_DELAY + duration +
lpn->recv_win);
}
}
static const struct bt_mesh_send_cb req_sent_cb = {
.start = req_sent,
};
static int send_friend_poll(void)
{
struct bt_mesh_msg_ctx ctx = {
.net_idx = bt_mesh.sub[0].net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = bt_mesh.lpn.frnd,
.send_ttl = 0,
};
struct bt_mesh_net_tx tx = {
.sub = &bt_mesh.sub[0],
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
.xmit = POLL_XMIT,
.friend_cred = true,
};
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
u8_t fsn = lpn->fsn;
int err;
BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req);
if (lpn->sent_req) {
if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) {
lpn->pending_poll = 1;
}
return 0;
}
err = bt_mesh_ctl_send(&tx, TRANS_CTL_OP_FRIEND_POLL, &fsn, 1,
NULL, &req_sent_cb, NULL);
if (err == 0) {
lpn->pending_poll = 0;
lpn->sent_req = TRANS_CTL_OP_FRIEND_POLL;
}
return err;
}
void bt_mesh_lpn_disable(bool force)
{
if (bt_mesh.lpn.state == BT_MESH_LPN_DISABLED) {
return;
}
clear_friendship(force, true);
}
int bt_mesh_lpn_set(bool enable)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
if (enable) {
if (lpn->state != BT_MESH_LPN_DISABLED) {
return 0;
}
} else {
if (lpn->state == BT_MESH_LPN_DISABLED) {
return 0;
}
}
if (!bt_mesh_is_provisioned()) {
if (enable) {
lpn_set_state(BT_MESH_LPN_ENABLED);
} else {
lpn_set_state(BT_MESH_LPN_DISABLED);
}
return 0;
}
if (enable) {
lpn_set_state(BT_MESH_LPN_ENABLED);
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
bt_mesh_scan_disable();
}
send_friend_req(lpn);
} else {
if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO) &&
lpn->state == BT_MESH_LPN_TIMER) {
k_delayed_work_cancel(&lpn->timer);
lpn_set_state(BT_MESH_LPN_DISABLED);
} else {
bt_mesh_lpn_disable(false);
}
}
return 0;
}
static void friend_response_received(struct bt_mesh_lpn *lpn)
{
BT_DBG("lpn->sent_req 0x%02x", lpn->sent_req);
if (lpn->sent_req == TRANS_CTL_OP_FRIEND_POLL) {
lpn->fsn++;
}
k_delayed_work_cancel(&lpn->timer);
bt_mesh_scan_disable();
lpn_set_state(BT_MESH_LPN_ESTABLISHED);
lpn->req_attempts = 0;
lpn->sent_req = 0;
}
void bt_mesh_lpn_msg_received(struct bt_mesh_net_rx *rx)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
if (lpn->state == BT_MESH_LPN_TIMER) {
BT_DBG("Restarting establishment timer");
k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT);
return;
}
if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) {
BT_WARN("Unexpected message withouth a preceding Poll");
return;
}
friend_response_received(lpn);
BT_DBG("Requesting more messages from Friend");
send_friend_poll();
}
int bt_mesh_lpn_friend_offer(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_offer *msg = (void *)buf->data;
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
struct bt_mesh_subnet *sub = rx->sub;
struct friend_cred *cred;
u16_t frnd_counter;
int err;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Offer");
return -EINVAL;
}
if (lpn->state != BT_MESH_LPN_WAIT_OFFER) {
BT_WARN("Ignoring unexpected Friend Offer");
return 0;
}
if (!msg->recv_win) {
BT_WARN("Prohibited ReceiveWindow value");
return -EINVAL;
}
frnd_counter = sys_be16_to_cpu(msg->frnd_counter);
BT_DBG("recv_win %u queue_size %u sub_list_size %u rssi %d counter %u",
msg->recv_win, msg->queue_size, msg->sub_list_size, msg->rssi,
frnd_counter);
lpn->frnd = rx->ctx.addr;
cred = friend_cred_create(sub, lpn->frnd, lpn->counter, frnd_counter);
if (!cred) {
lpn->frnd = BT_MESH_ADDR_UNASSIGNED;
return -ENOMEM;
}
/* TODO: Add offer acceptance criteria check */
k_delayed_work_cancel(&lpn->timer);
lpn->recv_win = msg->recv_win;
lpn->queue_size = msg->queue_size;
err = send_friend_poll();
if (err) {
friend_cred_clear(cred);
lpn->frnd = BT_MESH_ADDR_UNASSIGNED;
lpn->recv_win = 0;
lpn->queue_size = 0;
return err;
}
lpn->counter++;
return 0;
}
int bt_mesh_lpn_friend_clear_cfm(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_clear_confirm *msg = (void *)buf->data;
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
u16_t addr, counter;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Clear Confirm");
return -EINVAL;
}
if (lpn->state != BT_MESH_LPN_CLEAR) {
BT_WARN("Ignoring unexpected Friend Clear Confirm");
return 0;
}
addr = sys_be16_to_cpu(msg->lpn_addr);
counter = sys_be16_to_cpu(msg->lpn_counter);
BT_DBG("LPNAddress 0x%04x LPNCounter 0x%04x", addr, counter);
if (addr != bt_mesh_primary_addr() || counter != lpn->counter) {
BT_WARN("Invalid parameters in Friend Clear Confirm");
return 0;
}
lpn->clear_success = 1;
clear_friendship(false, lpn->disable);
return 0;
}
static void lpn_group_add(u16_t group)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
u16_t *free_slot = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) {
if (lpn->groups[i] == group) {
atomic_clear_bit(lpn->to_remove, i);
return;
}
if (!free_slot && lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) {
free_slot = &lpn->groups[i];
}
}
if (!free_slot) {
BT_WARN("Friend Subscription List exceeded!");
return;
}
*free_slot = group;
lpn->groups_changed = 1;
}
static void lpn_group_del(u16_t group)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
int i;
for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) {
if (lpn->groups[i] == group) {
if (atomic_test_bit(lpn->added, i) ||
atomic_test_bit(lpn->pending, i)) {
atomic_set_bit(lpn->to_remove, i);
lpn->groups_changed = 1;
} else {
lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED;
}
}
}
}
static inline int group_popcount(atomic_t *target)
{
#if CONFIG_BT_MESH_LPN_GROUPS > 32
int i, count = 0;
for (i = 0; i < ARRAY_SIZE(bt_mesh.lpn.added); i++) {
count += popcount(atomic_get(&target[i]));
}
#else
return popcount(atomic_get(target));
#endif
}
static bool sub_update(u8_t op)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
int added_count = group_popcount(lpn->added);
struct bt_mesh_msg_ctx ctx = {
.net_idx = bt_mesh.sub[0].net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = lpn->frnd,
.send_ttl = 0,
};
struct bt_mesh_net_tx tx = {
.sub = &bt_mesh.sub[0],
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
.xmit = POLL_XMIT,
.friend_cred = true,
};
struct bt_mesh_ctl_friend_sub req;
size_t i, g;
BT_DBG("op 0x%02x sent_req 0x%02x", op, lpn->sent_req);
if (lpn->sent_req) {
return false;
}
for (i = 0, g = 0; i < ARRAY_SIZE(lpn->groups); i++) {
if (lpn->groups[i] == BT_MESH_ADDR_UNASSIGNED) {
continue;
}
if (op == TRANS_CTL_OP_FRIEND_SUB_ADD) {
if (atomic_test_bit(lpn->added, i)) {
continue;
}
} else {
if (!atomic_test_bit(lpn->to_remove, i)) {
continue;
}
}
if (added_count + g >= lpn->queue_size) {
BT_WARN("Friend Queue Size exceeded");
break;
}
req.addr_list[g++] = sys_cpu_to_be16(lpn->groups[i]);
atomic_set_bit(lpn->pending, i);
if (g == ARRAY_SIZE(req.addr_list)) {
break;
}
}
if (g == 0) {
group_zero(lpn->pending);
return false;
}
req.xact = lpn->xact_next++;
if (bt_mesh_ctl_send(&tx, op, &req, 1 + g * 2, NULL,
&req_sent_cb, NULL) < 0) {
group_zero(lpn->pending);
return false;
}
lpn->xact_pending = req.xact;
lpn->sent_req = op;
return true;
}
static void update_timeout(struct bt_mesh_lpn *lpn)
{
if (lpn->established) {
BT_WARN("No response from Friend during ReceiveWindow");
bt_mesh_scan_disable();
lpn_set_state(BT_MESH_LPN_ESTABLISHED);
k_delayed_work_submit(&lpn->timer, POLL_RETRY_TIMEOUT);
} else {
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
bt_mesh_scan_disable();
}
if (lpn->req_attempts < 6) {
BT_WARN("Retrying first Friend Poll");
lpn->sent_req = 0;
if (send_friend_poll() == 0) {
return;
}
}
BT_ERR("Timed out waiting for first Friend Update");
clear_friendship(false, false);
}
}
static void lpn_timeout(struct k_work *work)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
#if defined(CONFIG_BT_MESH_DEBUG_LOW_POWER)
BT_DBG("state: %s", state2str(lpn->state));
#endif
switch (lpn->state) {
case BT_MESH_LPN_DISABLED:
break;
case BT_MESH_LPN_CLEAR:
clear_friendship(false, bt_mesh.lpn.disable);
break;
case BT_MESH_LPN_TIMER:
BT_DBG("Starting to look for Friend nodes");
lpn_set_state(BT_MESH_LPN_ENABLED);
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
bt_mesh_scan_disable();
}
/* fall through */
case BT_MESH_LPN_ENABLED:
send_friend_req(lpn);
break;
case BT_MESH_LPN_REQ_WAIT:
bt_mesh_scan_enable();
k_delayed_work_submit(&lpn->timer,
lpn->adv_duration + FRIEND_REQ_SCAN);
lpn_set_state(BT_MESH_LPN_WAIT_OFFER);
break;
case BT_MESH_LPN_WAIT_OFFER:
BT_WARN("No acceptable Friend Offers received");
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
bt_mesh_scan_disable();
}
lpn->counter++;
lpn_set_state(BT_MESH_LPN_ENABLED);
k_delayed_work_submit(&lpn->timer, FRIEND_REQ_RETRY_TIMEOUT);
break;
case BT_MESH_LPN_ESTABLISHED:
if (lpn->req_attempts < REQ_ATTEMPTS(lpn)) {
u8_t req = lpn->sent_req;
lpn->sent_req = 0;
if (!req || req == TRANS_CTL_OP_FRIEND_POLL) {
send_friend_poll();
} else {
sub_update(req);
}
break;
}
BT_ERR("No response from Friend after %u retries",
lpn->req_attempts);
lpn->req_attempts = 0;
clear_friendship(false, false);
break;
case BT_MESH_LPN_RECV_DELAY:
k_delayed_work_submit(&lpn->timer,
lpn->adv_duration + SCAN_LATENCY +
lpn->recv_win);
bt_mesh_scan_enable();
lpn_set_state(BT_MESH_LPN_WAIT_UPDATE);
break;
case BT_MESH_LPN_WAIT_UPDATE:
update_timeout(lpn);
break;
default:
__ASSERT(0, "Unhandled LPN state");
break;
}
}
void bt_mesh_lpn_group_add(u16_t group)
{
BT_DBG("group 0x%04x", group);
lpn_group_add(group);
if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) {
return;
}
sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD);
}
void bt_mesh_lpn_group_del(u16_t *groups, size_t group_count)
{
int i;
for (i = 0; i < group_count; i++) {
if (groups[i] != BT_MESH_ADDR_UNASSIGNED) {
BT_DBG("group 0x%04x", groups[i]);
lpn_group_del(groups[i]);
}
}
if (!bt_mesh_lpn_established() || bt_mesh.lpn.sent_req) {
return;
}
sub_update(TRANS_CTL_OP_FRIEND_SUB_REM);
}
static bt_s32_t poll_timeout(struct bt_mesh_lpn *lpn)
{
/* If we're waiting for segment acks keep polling at high freq */
if (bt_mesh_tx_in_progress()) {
return MIN(POLL_TIMEOUT_MAX(lpn), K_SECONDS(1));
}
if (lpn->poll_timeout < POLL_TIMEOUT_MAX(lpn)) {
lpn->poll_timeout *= 2;
lpn->poll_timeout = MIN(lpn->poll_timeout,
POLL_TIMEOUT_MAX(lpn));
}
BT_DBG("Poll Timeout is %ums", lpn->poll_timeout);
return lpn->poll_timeout;
}
int bt_mesh_lpn_friend_sub_cfm(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_sub_confirm *msg = (void *)buf->data;
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Subscription Confirm");
return -EINVAL;
}
BT_DBG("xact 0x%02x", msg->xact);
if (!lpn->sent_req) {
BT_WARN("No pending subscription list message");
return 0;
}
if (msg->xact != lpn->xact_pending) {
BT_WARN("Transaction mismatch (0x%02x != 0x%02x)",
msg->xact, lpn->xact_pending);
return 0;
}
if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_ADD) {
group_set(lpn->added, lpn->pending);
group_zero(lpn->pending);
} else if (lpn->sent_req == TRANS_CTL_OP_FRIEND_SUB_REM) {
int i;
group_clear(lpn->added, lpn->pending);
for (i = 0; i < ARRAY_SIZE(lpn->groups); i++) {
if (atomic_test_and_clear_bit(lpn->pending, i) &&
atomic_test_and_clear_bit(lpn->to_remove, i)) {
lpn->groups[i] = BT_MESH_ADDR_UNASSIGNED;
}
}
} else {
BT_WARN("Unexpected Friend Subscription Confirm");
return 0;
}
friend_response_received(lpn);
if (lpn->groups_changed) {
sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD);
sub_update(TRANS_CTL_OP_FRIEND_SUB_REM);
if (!lpn->sent_req) {
lpn->groups_changed = 0;
}
}
if (lpn->pending_poll) {
send_friend_poll();
}
if (!lpn->sent_req) {
k_delayed_work_submit(&lpn->timer, poll_timeout(lpn));
}
return 0;
}
int bt_mesh_lpn_friend_update(struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_ctl_friend_update *msg = (void *)buf->data;
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
struct bt_mesh_subnet *sub = rx->sub;
bt_u32_t iv_index;
if (buf->len < sizeof(*msg)) {
BT_WARN("Too short Friend Update");
return -EINVAL;
}
if (lpn->sent_req != TRANS_CTL_OP_FRIEND_POLL) {
BT_WARN("Unexpected friend update");
return 0;
}
if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !rx->new_key) {
BT_WARN("Ignoring Phase 2 KR Update secured using old key");
return 0;
}
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) &&
(atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ==
BT_MESH_IV_UPDATE(msg->flags))) {
bt_mesh_beacon_ivu_initiator(false);
}
if (!lpn->established) {
/* This is normally checked on the transport layer, however
* in this state we're also still accepting master
* credentials so we need to ensure the right ones (Friend
* Credentials) were used for this message.
*/
if (!rx->friend_cred) {
BT_WARN("Friend Update with wrong credentials");
return -EINVAL;
}
lpn->established = 1;
BT_INFO("Friendship established with 0x%04x", lpn->frnd);
if (lpn_cb) {
lpn_cb(lpn->frnd, true);
}
lpn_hb_send();
/* Set initial poll timeout */
lpn->poll_timeout = MIN(POLL_TIMEOUT_MAX(lpn),
POLL_TIMEOUT_INIT);
}
friend_response_received(lpn);
iv_index = sys_be32_to_cpu(msg->iv_index);
BT_DBG("flags 0x%02x iv_index 0x%08x md %u", msg->flags, iv_index,
msg->md);
if (bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(msg->flags),
rx->new_key)) {
bt_mesh_net_beacon_update(sub);
}
bt_mesh_net_iv_update(iv_index, BT_MESH_IV_UPDATE(msg->flags));
if (lpn->groups_changed) {
sub_update(TRANS_CTL_OP_FRIEND_SUB_ADD);
sub_update(TRANS_CTL_OP_FRIEND_SUB_REM);
if (!lpn->sent_req) {
lpn->groups_changed = 0;
}
}
if (msg->md) {
BT_DBG("Requesting for more messages");
send_friend_poll();
}
if (!lpn->sent_req) {
k_delayed_work_submit(&lpn->timer, poll_timeout(lpn));
}
return 0;
}
int bt_mesh_lpn_poll(void)
{
if (!bt_mesh.lpn.established) {
return -EAGAIN;
}
BT_DBG("Requesting more messages");
return send_friend_poll();
}
void bt_mesh_lpn_set_cb(void (*cb)(u16_t friend_addr, bool established))
{
lpn_cb = cb;
}
int bt_mesh_lpn_init(void)
{
struct bt_mesh_lpn *lpn = &bt_mesh.lpn;
BT_DBG("");
k_delayed_work_init(&lpn->timer, lpn_timeout);
if (lpn->state == BT_MESH_LPN_ENABLED) {
if (IS_ENABLED(CONFIG_BT_MESH_LPN_ESTABLISHMENT)) {
bt_mesh_scan_disable();
} else {
bt_mesh_scan_enable();
}
send_friend_req(lpn);
} else {
bt_mesh_scan_enable();
if (IS_ENABLED(CONFIG_BT_MESH_LPN_AUTO)) {
BT_DBG("Waiting %u ms for messages", LPN_AUTO_TIMEOUT);
lpn_set_state(BT_MESH_LPN_TIMER);
k_delayed_work_submit(&lpn->timer, LPN_AUTO_TIMEOUT);
}
}
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/lpn.c | C | apache-2.0 | 23,909 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <stdbool.h>
#include <bt_errno.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/uuid.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG)
#include "common/log.h"
#include "test.h"
#include "adv.h"
#include "prov.h"
#include "net.h"
#include "beacon.h"
#include "lpn.h"
#include "friend.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#include "proxy.h"
#include "settings.h"
#include "mesh.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "provisioner_proxy.h"
static volatile bool provisioner_en;
#endif
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
static uint8_t mesh_init = 0;
int bt_mesh_provision(const u8_t net_key[16], u16_t net_idx, u8_t flags, bt_u32_t iv_index, u16_t addr,
const u8_t dev_key[16])
{
bool pb_gatt_enabled;
int err;
BT_INFO("Primary Element: 0x%04x", addr);
BT_DBG("net_idx 0x%04x flags 0x%02x iv_index 0x%04x", net_idx, flags, iv_index);
if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_VALID)) {
return -EALREADY;
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) {
if (bt_mesh_proxy_prov_disable(false) == 0) {
pb_gatt_enabled = true;
} else {
pb_gatt_enabled = false;
}
} else {
pb_gatt_enabled = false;
}
err = bt_mesh_net_create(net_idx, flags, net_key, iv_index);
if (err) {
atomic_clear_bit(bt_mesh.flags, BT_MESH_VALID);
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && pb_gatt_enabled) {
bt_mesh_proxy_prov_enable();
}
return err;
}
#ifdef CONFIG_GENIE_MESH_ENABLE
// if(bt_mesh_elem_count() == 1)
// {
// bt_mesh.seq = 0U;
// }
// else
// {
atomic_set_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING);
// }
// printf("bt_mesh_provision seq:0x%x\n", bt_mesh.seq);
#else
bt_mesh.seq = 0U;
#endif
bt_mesh_comp_provision(addr);
memcpy(bt_mesh.dev_key, dev_key, 16);
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
BT_WARN("Storing network information persistently");
bt_mesh_store_net();
bt_mesh_store_subnet(&bt_mesh.sub[0], 0);
bt_mesh_store_iv(false);
}
bt_mesh_net_start();
return 0;
}
void bt_mesh_reset(void)
{
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
return;
}
bt_mesh.iv_index = 0U;
memset(bt_mesh.flags, 0, sizeof(bt_mesh.flags));
#ifdef CONFIG_GENIE_MESH_ENABLE
// if(bt_mesh_elem_count() == 1)
// {
// bt_mesh.seq = 0U;
// }
// else
// {
atomic_set_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING);
// }
// printf("bt_mesh_reset seq:0x%x\n", bt_mesh.seq);
#else
bt_mesh.seq = 0U;
#endif
k_delayed_work_cancel(&bt_mesh.ivu_timer);
bt_mesh_cfg_reset();
bt_mesh_rx_reset();
bt_mesh_tx_reset();
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_disable(true);
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
bt_mesh_friend_clear_net_idx(BT_MESH_KEY_ANY);
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
bt_mesh_proxy_gatt_disable();
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_net();
}
memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key));
bt_mesh_scan_disable();
bt_mesh_beacon_disable();
bt_mesh_comp_unprovision();
if (IS_ENABLED(CONFIG_BT_MESH_PROV)) {
bt_mesh_prov_reset();
}
#ifdef CONFIG_BT_MESH_PROVISIONER
provisioner_upper_reset_all_nodes();
#endif
}
bool bt_mesh_is_provisioned(void)
{
return atomic_test_bit(bt_mesh.flags, BT_MESH_VALID);
}
int bt_mesh_prov_enable(bt_mesh_prov_bearer_t bearers)
{
if (!mesh_init) {
return -EINVAL;
}
if (bearers >= (BT_MESH_PROV_GATT << 1) || bearers == 0) {
return -EINVAL;
}
if (bt_mesh_is_provisioned()) {
return -EALREADY;
}
if (IS_ENABLED(CONFIG_BT_DEBUG)) {
const struct bt_mesh_prov *prov = bt_mesh_prov_get();
struct bt_uuid_128 uuid = { .uuid.type = BT_UUID_TYPE_128 };
memcpy(uuid.val, prov->uuid, 16);
BT_INFO("Device UUID: %s", bt_uuid_str(&uuid.uuid));
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && (bearers & BT_MESH_PROV_ADV)) {
/* Make sure we're scanning for provisioning inviations */
bt_mesh_scan_enable();
/* Enable unprovisioned beacon sending */
bt_mesh_beacon_enable();
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT)) {
bt_mesh_proxy_prov_enable();
bt_mesh_adv_update();
}
return 0;
}
int bt_mesh_prov_disable(bt_mesh_prov_bearer_t bearers)
{
if (!mesh_init) {
return -EINVAL;
}
if (bearers >= (BT_MESH_PROV_GATT << 1) || bearers == 0) {
return -EINVAL;
}
if (bt_mesh_is_provisioned()) {
return -EALREADY;
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && (bearers & BT_MESH_PROV_ADV)) {
bt_mesh_beacon_disable();
bt_mesh_scan_disable();
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT)) {
bt_mesh_proxy_prov_disable(true);
}
return 0;
}
static void model_suspend(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
if (mod->pub && mod->pub->update) {
mod->pub->count = 0U;
k_delayed_work_cancel(&mod->pub->timer);
}
}
int bt_mesh_suspend(bool force)
{
int err;
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
return -EINVAL;
}
if (atomic_test_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) {
return -EALREADY;
}
#ifdef CONFIG_GENIE_MESH_ENABLE
extern bool bt_mesh_net_is_rx(void);
extern bool genie_transport_tx_in_progress(void);
if (force == false) {
if (!bt_mesh_is_provisioned()) {
BT_INFO("unprov stat no suspend");
return -1;
}
if (bt_mesh_net_is_rx()) {
BT_INFO("rx stat no suspend");
return -2;
}
if (genie_transport_tx_in_progress()) {
BT_INFO("tx stat no suspend");
return -3;
}
}
#endif
err = bt_mesh_scan_disable();
if (err) {
BT_WARN("Disabling scanning failed (err %d)", err);
return err;
}
bt_mesh_hb_pub_disable();
if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) {
bt_mesh_beacon_disable();
}
bt_mesh_model_foreach(model_suspend, NULL);
atomic_set_bit(bt_mesh.flags, BT_MESH_SUSPENDED);
return 0;
}
static void model_resume(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
if (mod->pub && mod->pub->update) {
bt_s32_t period_ms = bt_mesh_model_pub_period_get(mod);
if (period_ms) {
k_delayed_work_submit(&mod->pub->timer, period_ms);
}
}
}
int bt_mesh_resume(void)
{
int err;
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
return -EINVAL;
}
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_SUSPENDED)) {
return -EALREADY;
}
err = bt_mesh_scan_enable();
if (err) {
BT_WARN("Re-enabling scanning failed (err %d)", err);
return err;
}
if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) {
bt_mesh_beacon_enable();
}
bt_mesh_model_foreach(model_resume, NULL);
atomic_clear_bit(bt_mesh.flags, BT_MESH_SUSPENDED);
return err;
}
#ifdef CONFIG_BT_MESH_PROVISIONER
bool bt_mesh_is_provisioner_en(void)
{
return provisioner_en;
}
int bt_mesh_provisioner_enable(bt_mesh_prov_bearer_t bearers)
{
int err;
if (bearers >= (BT_MESH_PROV_GATT << 1) || bearers == 0) {
return -EINVAL;
}
if (bt_mesh_is_provisioner_en()) {
BT_ERR("Provisioner already enabled");
return -EALREADY;
}
err = provisioner_upper_init();
if (err) {
BT_ERR("%s: provisioner_upper_init fail", __func__);
return err;
}
if ((IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && (bearers & BT_MESH_PROV_ADV)) ||
(IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT))) {
bt_mesh_scan_enable();
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT)) {
provisioner_pb_gatt_enable();
}
provisioner_en = true;
return 0;
}
int bt_mesh_provisioner_disable(bt_mesh_prov_bearer_t bearers)
{
if (bearers >= (BT_MESH_PROV_GATT << 1) || bearers == 0) {
return -EINVAL;
}
if (!bt_mesh_is_provisioner_en()) {
BT_ERR("Provisioner already disabled");
return -EALREADY;
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT)) {
provisioner_pb_gatt_disable();
}
if ((IS_ENABLED(CONFIG_BT_MESH_PB_ADV) && (bearers & BT_MESH_PROV_ADV)) &&
(IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && (bearers & BT_MESH_PROV_GATT))) {
bt_mesh_scan_disable();
}
provisioner_en = false;
return 0;
}
#endif /* CONFIG_BT_MESH_PROVISIONER */
int bt_mesh_is_init()
{
return mesh_init;
}
int bt_mesh_vnd_adv_set_cb(void (*cb)(const struct adv_addr_t *addr, s8_t rssi, u8_t adv_type, void *user_data,
uint16_t len))
{
return bt_mesh_adv_vnd_scan_register((vendor_beacon_cb)cb);
}
int bt_mesh_init(const struct bt_mesh_prov *prov, const struct bt_mesh_comp *comp,
const struct bt_mesh_provisioner *provisioner)
{
int err;
BT_WARN(" ble_mesh log is enable \r\n");
if (mesh_init) {
return -EALREADY;
}
if (prov == NULL || comp == NULL) {
return -EINVAL;
}
if (prov->uuid == NULL) {
return -EINVAL;
}
if (prov->oob_info >= (BT_MESH_PROV_OOB_ON_DEV << 1)) {
return -EINVAL;
}
if (prov->output_actions >= (BT_MESH_DISPLAY_STRING << 1)) {
return -EINVAL;
}
if (prov->input_actions >= (BT_MESH_ENTER_STRING << 1)) {
return -EINVAL;
}
// bt_enable is aleady called before
// printf("before bt_enable in %s\n", __func__);
// err = bt_enable(NULL);
// if (err && err != -EALREADY) {
// return err;
// }
printf("before bt_mesh_test in %s\n", __func__);
err = bt_mesh_test();
if (err) {
return err;
}
printf("before bt_mesh_comp_register in %s\n", __func__);
err = bt_mesh_comp_register(comp);
if (err) {
return err;
}
printf("before bt_mesh_prov_init in %s\n", __func__);
if (IS_ENABLED(CONFIG_BT_MESH_PROV)) {
err = bt_mesh_prov_init(prov);
if (err) {
printf(" bt_mesh_prov_init err:%d\n", err);
return err;
}
}
#ifdef CONFIG_BT_MESH_PROVISIONER
printf("before provisioner_prov_init in %s\n", __func__);
err = provisioner_prov_init(provisioner);
if (err) {
return err;
}
#endif
bt_mesh_net_init();
bt_mesh_trans_init();
bt_mesh_beacon_init();
bt_mesh_adv_init();
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
#ifdef CONFIG_BT_MESH_PROVISIONER
provisioner_proxy_init();
#endif
bt_mesh_proxy_init();
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_settings_init();
extern int settings_load();
settings_load();
}
mesh_init = 1;
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/main.c | C | apache-2.0 | 11,676 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <string.h>
#include <bt_errno.h>
#include <stdbool.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_NET)
#include "common/log.h"
#include "crypto.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "lpn.h"
#include "friend.h"
#include "proxy.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#include "beacon.h"
#include "settings.h"
#include "prov.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "provisioner_proxy.h"
#endif
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
/* Minimum valid Mesh Network PDU length. The Network headers
* themselves take up 9 bytes. After that there is a minumum of 1 byte
* payload for both CTL=1 and CTL=0 PDUs (smallest OpCode is 1 byte). CTL=1
* PDUs must use a 64-bit (8 byte) NetMIC, whereas CTL=0 PDUs have at least
* a 32-bit (4 byte) NetMIC and AppMIC giving again a total of 8 bytes.
*/
#define BT_MESH_NET_MIN_PDU_LEN (BT_MESH_NET_HDR_LEN + 1 + 8)
/* Seq limit after IV Update is triggered */
#ifndef CONFIG_IV_UPDATE_SEQ_LIMIT
#define CONFIG_IV_UPDATE_SEQ_LIMIT 8000000
#endif
#define IVI(pdu) ((pdu)[0] >> 7)
#define NID(pdu) ((pdu)[0] & 0x7f)
#define CTL(pdu) ((pdu)[1] >> 7)
#define TTL(pdu) ((pdu)[1] & 0x7f)
#define SEQ(pdu) (((bt_u32_t)(pdu)[2] << 16) | ((bt_u32_t)(pdu)[3] << 8) | (bt_u32_t)(pdu)[4]);
#define SRC(pdu) (sys_get_be16(&(pdu)[5]))
#define DST(pdu) (sys_get_be16(&(pdu)[7]))
/* Determine how many friendship credentials we need */
#if defined(CONFIG_BT_MESH_FRIEND)
#define FRIEND_CRED_COUNT CONFIG_BT_MESH_FRIEND_LPN_COUNT
#elif defined(CONFIG_BT_MESH_LOW_POWER)
#define FRIEND_CRED_COUNT CONFIG_BT_MESH_SUBNET_COUNT
#else
#define FRIEND_CRED_COUNT 0
#endif
#if FRIEND_CRED_COUNT > 0
static struct friend_cred friend_cred[FRIEND_CRED_COUNT];
#endif
static u64_t msg_cache[CONFIG_BT_MESH_MSG_CACHE_SIZE];
static u16_t msg_cache_next;
u16_t g_sub_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT];
#if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
struct net_buf_trace_t net_buf_trace = { 0 };
#endif
/* Singleton network context (the implementation only supports one) */
struct bt_mesh_net bt_mesh = {
.local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue),
.sub = {
[0 ... (CONFIG_BT_MESH_SUBNET_COUNT - 1)] = {
.net_idx = BT_MESH_KEY_UNUSED,
}
},
.app_keys = {
[0 ... (CONFIG_BT_MESH_APP_KEY_COUNT - 1)] = {
.net_idx = BT_MESH_KEY_UNUSED,
}
},
// #ifdef CONFIG_BT_MESH_PROVISIONER
// .p_app_keys = {
// [0 ... (CONFIG_BT_MESH_PROVISIONER_APP_KEY_COUNT - 1)] = {
// .net_idx = BT_MESH_KEY_UNUSED,
// }
// },
// .p_sub = {
// [0 ... (CONFIG_BT_MESH_PROVISIONER_SUBNET_COUNT - 1)] = {
// .net_idx = BT_MESH_KEY_UNUSED,
// }
// },
// #endif
};
static bt_u32_t dup_cache[4];
static int dup_cache_next;
static bool check_dup(struct net_buf_simple *data)
{
const u8_t *tail = net_buf_simple_tail(data);
bt_u32_t val;
int i;
val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8);
for (i = 0; i < ARRAY_SIZE(dup_cache); i++) {
if (dup_cache[i] == val) {
return true;
}
}
dup_cache[dup_cache_next++] = val;
dup_cache_next %= ARRAY_SIZE(dup_cache);
return false;
}
static u64_t msg_hash(struct bt_mesh_net_rx *rx, struct net_buf_simple *pdu)
{
bt_u32_t hash1, hash2;
/* Three least significant bytes of IVI + first byte of SEQ */
hash1 = (BT_MESH_NET_IVI_RX(rx) << 8) | pdu->data[2];
/* Two last bytes of SEQ + SRC */
memcpy(&hash2, &pdu->data[3], 4);
return (u64_t)hash1 << 32 | (u64_t)hash2;
}
static bool msg_cache_match(struct bt_mesh_net_rx *rx, struct net_buf_simple *pdu)
{
u64_t hash = msg_hash(rx, pdu);
u16_t i;
for (i = 0; i < ARRAY_SIZE(msg_cache); i++) {
if (msg_cache[i] == hash) {
return true;
}
}
/* Add to the cache */
msg_cache[msg_cache_next++] = hash;
msg_cache_next %= ARRAY_SIZE(msg_cache);
return false;
}
struct bt_mesh_subnet *bt_mesh_subnet_get(u16_t net_idx)
{
int i;
if (net_idx == BT_MESH_KEY_ANY) {
return &bt_mesh.sub[0];
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx == net_idx) {
return &bt_mesh.sub[i];
}
}
return NULL;
}
int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys, const u8_t key[16])
{
u8_t p[] = { 0 };
u8_t nid;
int err;
err = bt_mesh_k2(key, p, sizeof(p), &nid, keys->enc, keys->privacy);
if (err) {
BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
return err;
}
memcpy(keys->net, key, 16);
keys->nid = nid;
BT_DBG("NID 0x%02x EncKey %s", keys->nid, bt_hex(keys->enc, 16));
BT_DBG("PrivacyKey %s", bt_hex(keys->privacy, 16));
err = bt_mesh_k3(key, keys->net_id);
if (err) {
BT_ERR("Unable to generate Net ID");
return err;
}
BT_DBG("NetID %s", bt_hex(keys->net_id, 8));
#if defined(CONFIG_BT_MESH_GATT_PROXY)
err = bt_mesh_identity_key(key, keys->identity);
if (err) {
BT_ERR("Unable to generate IdentityKey");
return err;
}
BT_DBG("IdentityKey %s", bt_hex(keys->identity, 16));
#endif /* GATT_PROXY */
err = bt_mesh_beacon_key(key, keys->beacon);
if (err) {
BT_ERR("Unable to generate beacon key");
return err;
}
BT_DBG("BeaconKey %s", bt_hex(keys->beacon, 16));
return 0;
}
#if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
int friend_cred_set(struct friend_cred *cred, u8_t idx, const u8_t net_key[16])
{
u16_t lpn_addr, frnd_addr;
int err;
u8_t p[9];
#if defined(CONFIG_BT_MESH_LOW_POWER)
if (cred->addr == bt_mesh.lpn.frnd) {
lpn_addr = bt_mesh_primary_addr();
frnd_addr = cred->addr;
} else {
lpn_addr = cred->addr;
frnd_addr = bt_mesh_primary_addr();
}
#else
lpn_addr = cred->addr;
frnd_addr = bt_mesh_primary_addr();
#endif
BT_DBG("LPNAddress 0x%04x FriendAddress 0x%04x", lpn_addr, frnd_addr);
BT_DBG("LPNCounter 0x%04x FriendCounter 0x%04x", cred->lpn_counter, cred->frnd_counter);
p[0] = 0x01;
sys_put_be16(lpn_addr, p + 1);
sys_put_be16(frnd_addr, p + 3);
sys_put_be16(cred->lpn_counter, p + 5);
sys_put_be16(cred->frnd_counter, p + 7);
err = bt_mesh_k2(net_key, p, sizeof(p), &cred->cred[idx].nid, cred->cred[idx].enc, cred->cred[idx].privacy);
if (err) {
BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
return err;
}
BT_DBG("Friend NID 0x%02x EncKey %s", cred->cred[idx].nid, bt_hex(cred->cred[idx].enc, 16));
BT_DBG("Friend PrivacyKey %s", bt_hex(cred->cred[idx].privacy, 16));
return 0;
}
void friend_cred_refresh(u16_t net_idx)
{
int i;
for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
struct friend_cred *cred = &friend_cred[i];
if (cred->addr != BT_MESH_ADDR_UNASSIGNED && cred->net_idx == net_idx) {
memcpy(&cred->cred[0], &cred->cred[1], sizeof(cred->cred[0]));
}
}
}
int friend_cred_update(struct bt_mesh_subnet *sub)
{
int err, i;
BT_DBG("net_idx 0x%04x", sub->net_idx);
for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
struct friend_cred *cred = &friend_cred[i];
if (cred->addr == BT_MESH_ADDR_UNASSIGNED || cred->net_idx != sub->net_idx) {
continue;
}
err = friend_cred_set(cred, 1, sub->keys[1].net);
if (err) {
return err;
}
}
return 0;
}
struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, u16_t addr, u16_t lpn_counter, u16_t frnd_counter)
{
struct friend_cred *cred;
int i, err;
BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
for (cred = NULL, i = 0; i < ARRAY_SIZE(friend_cred); i++) {
if ((friend_cred[i].addr == BT_MESH_ADDR_UNASSIGNED) ||
(friend_cred[i].addr == addr && friend_cred[i].net_idx == sub->net_idx)) {
cred = &friend_cred[i];
break;
}
}
if (!cred) {
BT_WARN("No free friend credential slots");
return NULL;
}
cred->net_idx = sub->net_idx;
cred->addr = addr;
cred->lpn_counter = lpn_counter;
cred->frnd_counter = frnd_counter;
err = friend_cred_set(cred, 0, sub->keys[0].net);
if (err) {
friend_cred_clear(cred);
return NULL;
}
if (sub->kr_flag) {
err = friend_cred_set(cred, 1, sub->keys[1].net);
if (err) {
friend_cred_clear(cred);
return NULL;
}
}
return cred;
}
void friend_cred_clear(struct friend_cred *cred)
{
cred->net_idx = BT_MESH_KEY_UNUSED;
cred->addr = BT_MESH_ADDR_UNASSIGNED;
cred->lpn_counter = 0;
cred->frnd_counter = 0;
memset(cred->cred, 0, sizeof(cred->cred));
}
int friend_cred_del(u16_t net_idx, u16_t addr)
{
int i;
for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
struct friend_cred *cred = &friend_cred[i];
if (cred->addr == addr && cred->net_idx == net_idx) {
friend_cred_clear(cred);
return 0;
}
}
return -ENOENT;
}
int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, const u8_t **enc, const u8_t **priv)
{
int i;
BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
struct friend_cred *cred = &friend_cred[i];
if (cred->net_idx != sub->net_idx) {
continue;
}
if (addr != BT_MESH_ADDR_UNASSIGNED && cred->addr != addr) {
continue;
}
if (nid) {
*nid = cred->cred[sub->kr_flag].nid;
}
if (enc) {
*enc = cred->cred[sub->kr_flag].enc;
}
if (priv) {
*priv = cred->cred[sub->kr_flag].privacy;
}
return 0;
}
return -ENOENT;
}
#else
int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, const u8_t **enc, const u8_t **priv)
{
return -ENOENT;
}
#endif /* FRIEND || LOW_POWER */
u8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub)
{
u8_t flags = 0x00;
if (sub && sub->kr_flag) {
flags |= BT_MESH_NET_FLAG_KR;
}
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
flags |= BT_MESH_NET_FLAG_IVU;
}
return flags;
}
int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub)
{
u8_t flags = bt_mesh_net_flags(sub);
struct bt_mesh_subnet_keys *keys;
if (sub->kr_flag) {
BT_DBG("NetIndex %u Using new key", sub->net_idx);
keys = &sub->keys[1];
} else {
BT_DBG("NetIndex %u Using current key", sub->net_idx);
keys = &sub->keys[0];
}
BT_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index);
return bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, bt_mesh.iv_index, sub->auth);
}
int bt_mesh_net_create(u16_t idx, u8_t flags, const u8_t key[16], bt_u32_t iv_index)
{
struct bt_mesh_subnet *sub;
int err;
BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index);
BT_DBG("NetKey %s", bt_hex(key, 16));
(void)memset(msg_cache, 0, sizeof(msg_cache));
msg_cache_next = 0U;
sub = &bt_mesh.sub[0];
sub->kr_flag = BT_MESH_KEY_REFRESH(flags);
if (sub->kr_flag) {
err = bt_mesh_net_keys_create(&sub->keys[1], key);
if (err) {
return -EIO;
}
sub->kr_phase = BT_MESH_KR_PHASE_2;
} else {
err = bt_mesh_net_keys_create(&sub->keys[0], key);
if (err) {
return -EIO;
}
}
sub->net_idx = idx;
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
} else {
sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
}
bt_mesh.iv_index = iv_index;
atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, BT_MESH_IV_UPDATE(flags));
/* Set minimum required hours, since the 96-hour minimum requirement
* doesn't apply straight after provisioning (since we can't know how
* long has actually passed since the network changed its state).
*/
bt_mesh.ivu_duration = BT_MESH_IVU_MIN_HOURS;
/* Make sure we have valid beacon data to be sent */
bt_mesh_net_beacon_update(sub);
sub->subnet_active = true;
return 0;
}
void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub)
{
int i;
BT_DBG("idx 0x%04x", sub->net_idx);
memcpy(&sub->keys[0], &sub->keys[1], sizeof(sub->keys[0]));
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx != sub->net_idx || !key->updated) {
continue;
}
memcpy(&key->keys[0], &key->keys[1], sizeof(key->keys[0]));
key->updated = false;
}
}
bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, u8_t new_kr, bool new_key)
{
if (new_kr != sub->kr_flag && sub->kr_phase == BT_MESH_KR_NORMAL) {
BT_WARN("KR change in normal operation. Are we blacklisted?");
return false;
}
sub->kr_flag = new_kr;
if (sub->kr_flag) {
if (sub->kr_phase == BT_MESH_KR_PHASE_1) {
BT_DBG("Phase 1 -> Phase 2");
sub->kr_phase = BT_MESH_KR_PHASE_2;
return true;
}
} else {
switch (sub->kr_phase) {
case BT_MESH_KR_PHASE_1:
if (!new_key) {
/* Ignore */
break;
}
/* Upon receiving a Secure Network beacon with the KR flag set
* to 0 using the new NetKey in Phase 1, the node shall
* immediately transition to Phase 3, which effectively skips
* Phase 2.
*
* Intentional fall-through.
*/
case BT_MESH_KR_PHASE_2:
BT_DBG("KR Phase 0x%02x -> Normal", sub->kr_phase);
bt_mesh_net_revoke_keys(sub);
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
friend_cred_refresh(sub->net_idx);
}
sub->kr_phase = BT_MESH_KR_NORMAL;
return true;
}
}
return false;
}
void bt_mesh_rpl_reset(void)
{
int i;
/* Discard "old old" IV Index entries from RPL and flag
* any other ones (which are valid) as old.
*/
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
if (rpl->src) {
if (rpl->old_iv) {
memset(rpl, 0, sizeof(*rpl));
} else {
rpl->old_iv = true;
}
}
}
}
#if defined(CONFIG_BT_MESH_IV_UPDATE_TEST)
void bt_mesh_iv_update_test(bool enable)
{
atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_TEST, enable);
/* Reset the duration variable - needed for some PTS tests */
bt_mesh.ivu_duration = 0;
}
bool bt_mesh_iv_update(void)
{
if (!bt_mesh_is_provisioned()) {
BT_ERR("Not yet provisioned");
return false;
}
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
bt_mesh_net_iv_update(bt_mesh.iv_index, false);
} else {
bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
}
bt_mesh_net_sec_update(NULL);
return atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
}
#endif /* CONFIG_BT_MESH_IV_UPDATE_TEST */
/* Used for sending immediate beacons to Friend queues and GATT clients */
void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub)
{
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
bt_mesh_friend_sec_update(sub ? sub->net_idx : BT_MESH_KEY_ANY);
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
bt_mesh_proxy_beacon_send(sub);
}
}
bool bt_mesh_net_iv_update(bt_u32_t iv_index, bool iv_update)
{
int i;
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
/* We're currently in IV Update mode */
if (iv_index != bt_mesh.iv_index) {
BT_WARN("IV Index mismatch: 0x%08x != 0x%08x", iv_index, bt_mesh.iv_index);
return false;
}
if (iv_update) {
/* Nothing to do */
BT_DBG("Already in IV Update in Progress state");
return false;
}
} else {
/* We're currently in Normal mode */
if (iv_index == bt_mesh.iv_index) {
BT_DBG("Same IV Index in normal mode");
return false;
}
if (iv_index < bt_mesh.iv_index || iv_index > bt_mesh.iv_index + 42) {
BT_ERR("IV Index out of sync: 0x%08x != 0x%08x", iv_index, bt_mesh.iv_index);
return false;
}
if (iv_index > bt_mesh.iv_index + 1) {
BT_WARN("Performing IV Index Recovery");
memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
bt_mesh.iv_index = iv_index;
bt_mesh.seq = 0;
goto do_update;
}
if (iv_index == bt_mesh.iv_index + 1 && !iv_update) {
BT_WARN("Ignoring new index in normal mode");
return false;
}
if (!iv_update) {
/* Nothing to do */
BT_DBG("Already in Normal state");
return false;
}
}
if (!(IS_ENABLED(CONFIG_BT_MESH_IV_UPDATE_TEST) && atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_TEST))) {
if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
BT_WARN("IV Update before minimum duration");
return false;
}
}
/* Defer change to Normal Operation if there are pending acks */
if (!iv_update && bt_mesh_tx_in_progress()) {
BT_WARN("IV Update deferred because of pending transfer");
atomic_set_bit(bt_mesh.flags, BT_MESH_IVU_PENDING);
return false;
}
do_update:
atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv_update);
bt_mesh.ivu_duration = 0U;
if (iv_update) {
bt_mesh.iv_index = iv_index;
BT_DBG("IV Update state entered. New index 0x%08x", bt_mesh.iv_index);
bt_mesh_rpl_reset();
} else {
BT_DBG("Normal mode entered");
bt_mesh.seq = 0;
}
k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) {
bt_mesh_net_beacon_update(&bt_mesh.sub[i]);
}
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_iv(false);
}
return true;
}
bt_u32_t bt_mesh_next_seq(void)
{
bt_u32_t seq = bt_mesh.seq++;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_seq();
}
return seq;
}
int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf, bool new_key, const struct bt_mesh_send_cb *cb,
void *cb_data)
{
const u8_t *enc, *priv;
bt_u32_t seq;
int err;
BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key, buf->len);
if (!sub || !buf || !buf->data) {
return -EINVAL;
}
enc = sub->keys[new_key].enc;
priv = sub->keys[new_key].privacy;
err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
if (err) {
BT_WARN("deobfuscate failed (err %d)", err);
return err;
}
err = bt_mesh_net_decrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false);
if (err) {
BT_WARN("decrypt failed (err %d)", err);
return err;
}
/* Update with a new sequence number */
seq = bt_mesh_next_seq();
buf->data[2] = seq >> 16;
buf->data[3] = seq >> 8;
buf->data[4] = seq;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, NULL);
}
#endif
err = bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false);
if (err) {
BT_WARN("encrypt failed (err %d)", err);
return err;
}
err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
if (err) {
BT_WARN("obfuscate failed (err %d)", err);
return err;
}
bt_mesh_adv_send(buf, cb, cb_data);
if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) && bt_mesh.seq > CONFIG_IV_UPDATE_SEQ_LIMIT) {
bt_mesh_beacon_ivu_initiator(true);
bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
bt_mesh_net_sec_update(NULL);
}
return 0;
}
static void bt_mesh_net_local(struct k_work *work)
{
struct net_buf *buf;
while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
bt_mesh_net_recv(&buf->b, 0, BT_MESH_NET_IF_LOCAL);
net_buf_unref(buf);
}
}
int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf, bool proxy)
{
const bool ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED);
bt_u32_t seq_val;
u8_t nid;
const u8_t *enc, *priv;
u8_t *seq;
int err;
if (ctl && net_buf_simple_tailroom(buf) < 8) {
BT_ERR("Insufficient MIC space for CTL PDU");
return -EINVAL;
} else if (net_buf_simple_tailroom(buf) < 4) {
BT_ERR("Insufficient MIC space for PDU");
return -EINVAL;
}
BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x", tx->src, tx->ctx->addr, ctl, bt_mesh.seq);
net_buf_simple_push_be16(buf, tx->ctx->addr);
net_buf_simple_push_be16(buf, tx->src);
seq = net_buf_simple_push(buf, 3);
seq_val = bt_mesh_next_seq();
seq[0] = seq_val >> 16;
seq[1] = seq_val >> 8;
seq[2] = seq_val;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, NULL);
}
#endif
if (ctl) {
net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80);
} else {
net_buf_simple_push_u8(buf, tx->ctx->send_ttl);
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && tx->friend_cred) {
if (friend_cred_get(tx->sub, BT_MESH_ADDR_UNASSIGNED, &nid, &enc, &priv)) {
BT_WARN("Falling back to master credentials");
tx->friend_cred = 0;
nid = tx->sub->keys[tx->sub->kr_flag].nid;
enc = tx->sub->keys[tx->sub->kr_flag].enc;
priv = tx->sub->keys[tx->sub->kr_flag].privacy;
}
} else {
tx->friend_cred = 0;
nid = tx->sub->keys[tx->sub->kr_flag].nid;
enc = tx->sub->keys[tx->sub->kr_flag].enc;
priv = tx->sub->keys[tx->sub->kr_flag].privacy;
}
net_buf_simple_push_u8(buf, (nid | (BT_MESH_NET_IVI_TX & 1) << 7));
err = bt_mesh_net_encrypt(enc, buf, BT_MESH_NET_IVI_TX, proxy);
if (err) {
return err;
}
return bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
}
int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf, const struct bt_mesh_send_cb *cb, void *cb_data)
{
int err;
BT_DBG("src 0x%04x dst 0x%04x len %u headroom %zu tailroom %zu", tx->src, tx->ctx->addr, buf->len,
net_buf_headroom(buf), net_buf_tailroom(buf));
BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len));
BT_DBG("Seq 0x%06x", bt_mesh.seq);
if (tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) {
tx->ctx->send_ttl = bt_mesh_default_ttl_get();
}
err = bt_mesh_net_encode(tx, &buf->b, false);
if (err) {
goto done;
}
/* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2:
* "The output filter of the interface connected to advertising or
* GATT bearers shall drop all messages with TTL value set to 1."
*/
#ifdef CONFIG_BT_MESH_PROVISIONER
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_is_provisioner_en()) {
if (0 == provisioner_proxy_pdu_send(&buf->b)) {
goto done;
}
}
#endif
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && tx->ctx->send_ttl != 1) {
if (bt_mesh_proxy_relay(&buf->b, tx->ctx->addr) && BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
/* Notify completion if this only went
* through the Mesh Proxy.
*/
if (cb) {
if (cb->start) {
cb->start(0, 0, cb_data);
}
if (cb->end) {
cb->end(0, cb_data);
}
}
err = 0;
goto done;
}
}
/* Deliver to local network interface if necessary */
if (bt_mesh_fixed_group_match(tx->ctx->addr) || bt_mesh_elem_find(tx->ctx->addr)) {
if (cb && cb->start) {
cb->start(0, 0, cb_data);
}
net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf));
if (cb && cb->end) {
cb->end(0, cb_data);
}
k_work_submit(&bt_mesh.local_work);
} else if (tx->ctx->send_ttl != 1) {
/* Deliver to to the advertising network interface. Mesh spec
* 3.4.5.2: "The output filter of the interface connected to
* advertising or GATT bearers shall drop all messages with
* TTL value set to 1."
*/
bt_mesh_adv_send(buf, cb, cb_data);
}
done:
net_buf_unref(buf);
return err;
}
static bool auth_match(struct bt_mesh_subnet_keys *keys, const u8_t net_id[8], u8_t flags, bt_u32_t iv_index,
const u8_t auth[8])
{
u8_t net_auth[8] = { 0 };
if (memcmp(net_id, keys->net_id, 8)) {
return false;
}
bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index, net_auth);
if (memcmp(auth, net_auth, 8)) {
BT_WARN("Authentication Value %s != %s", bt_hex(auth, 8), bt_hex(net_auth, 8));
return false;
}
return true;
}
struct bt_mesh_subnet *bt_mesh_subnet_find(const u8_t net_id[8], u8_t flags, bt_u32_t iv_index, const u8_t auth[8],
bool *new_key)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) {
*new_key = false;
return sub;
}
if (sub->kr_phase == BT_MESH_KR_NORMAL) {
continue;
}
if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) {
*new_key = true;
return sub;
}
}
return NULL;
}
static int net_decrypt(struct bt_mesh_subnet *sub, const u8_t *enc, const u8_t *priv, const u8_t *data, size_t data_len,
struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index);
rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01));
net_buf_simple_reset(buf);
memcpy(net_buf_simple_add(buf, data_len), data, data_len);
if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) {
return -ENOENT;
}
if (rx->net_if == BT_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) {
BT_DBG("Duplicate found in Network Message Cache");
return -EALREADY;
}
rx->ctx.addr = SRC(buf->data);
if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) {
BT_WARN("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr);
return -EINVAL;
}
BT_DBG("src 0x%04x", rx->ctx.addr);
if (IS_ENABLED(CONFIG_BT_MESH_PROXY) && rx->net_if == BT_MESH_NET_IF_PROXY_CFG) {
return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), true);
}
return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), false);
}
#if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
static int friend_decrypt(struct bt_mesh_subnet *sub, const u8_t *data, size_t data_len, struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
int i;
BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
struct friend_cred *cred = &friend_cred[i];
if (cred->net_idx != sub->net_idx) {
continue;
}
if (NID(data) == cred->cred[0].nid &&
!net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy, data, data_len, rx, buf)) {
return 0;
}
if (sub->kr_phase == BT_MESH_KR_NORMAL) {
continue;
}
if (NID(data) == cred->cred[1].nid &&
!net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy, data, data_len, rx, buf)) {
rx->new_key = 1;
return 0;
}
}
return -ENOENT;
}
#endif
static bool net_find_and_decrypt(const u8_t *data, size_t data_len, struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_subnet *sub;
int i;
bt_u32_t array_size = 0;
BT_DBG("");
array_size = ARRAY_SIZE(bt_mesh.sub);
for (i = 0; i < array_size; i++) {
sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
#if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
if (!friend_decrypt(sub, data, data_len, rx, buf)) {
rx->friend_cred = 1;
rx->ctx.net_idx = sub->net_idx;
rx->sub = sub;
return true;
}
#endif
if (NID(data) == sub->keys[0].nid &&
!net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy, data, data_len, rx, buf)) {
rx->ctx.net_idx = sub->net_idx;
rx->sub = sub;
return true;
}
if (sub->kr_phase == BT_MESH_KR_NORMAL) {
continue;
}
if (NID(data) == sub->keys[1].nid &&
!net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy, data, data_len, rx, buf)) {
rx->new_key = 1;
rx->ctx.net_idx = sub->net_idx;
rx->sub = sub;
return true;
}
}
return false;
}
/* Relaying from advertising to the advertising bearer should only happen
* if the Relay state is set to enabled. Locally originated packets always
* get sent to the advertising bearer. If the packet came in through GATT,
* then we should only relay it if the GATT Proxy state is enabled.
*/
static bool relay_to_adv(enum bt_mesh_net_if net_if)
{
switch (net_if) {
case BT_MESH_NET_IF_LOCAL:
return true;
case BT_MESH_NET_IF_ADV:
return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED);
case BT_MESH_NET_IF_PROXY:
return (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED);
default:
return false;
}
}
static void bt_mesh_net_relay(struct net_buf_simple *sbuf, struct bt_mesh_net_rx *rx)
{
const u8_t *enc, *priv;
struct net_buf *buf;
u8_t nid, transmit;
if (rx->net_if == BT_MESH_NET_IF_LOCAL) {
/* Locally originated PDUs with TTL=1 will only be delivered
* to local elements as per Mesh Profile 1.0 section 3.4.5.2:
* "The output filter of the interface connected to
* advertising or GATT bearers shall drop all messages with
* TTL value set to 1."
*/
if (rx->ctx.recv_ttl == 1) {
return;
}
} else {
if (rx->ctx.recv_ttl <= 1) {
return;
}
}
if (rx->net_if == BT_MESH_NET_IF_ADV && bt_mesh_relay_get() != BT_MESH_RELAY_ENABLED &&
bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_ENABLED) {
return;
}
#if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
if (BT_MESH_NET_IF_ADV == rx->net_if) {
if (net_buf_trace.buf == sbuf) {
BT_INFO("TTL %u CTL %u dst 0x%04x recv from 0x%04x (%02X:%02X:%02X:%02X:%02X:%02X (%d)) packet ",
rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst, rx->ctx.addr, net_buf_trace.addr[5],
net_buf_trace.addr[4], net_buf_trace.addr[3], net_buf_trace.addr[2], net_buf_trace.addr[1],
net_buf_trace.addr[0], net_buf_trace.addr[6]);
}
} else {
BT_DBG("TTL %u CTL %u dst 0x%04x packet ", rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst);
}
#else
BT_DBG("TTL %u CTL %u dst 0x%04x packet ", rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst);
#endif
/* The Relay Retransmit state is only applied to adv-adv relaying.
* Anything else (like GATT to adv, or locally originated packets)
* use the Network Transmit state.
*/
if (rx->net_if == BT_MESH_NET_IF_ADV) {
transmit = bt_mesh_relay_retransmit_get();
} else {
transmit = bt_mesh_net_transmit_get();
}
buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, transmit, K_NO_WAIT);
if (!buf) {
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
BT_ERR("[%u]Out of relay buffers, Payload: %s", k_uptime_get_32(), bt_hex(sbuf->data, sbuf->len));
#ifdef CONFIG_BT_MESH_CTRL_RELAY
ctrl_relay_set_flood_flg();
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
return;
}
/* Only decrement TTL for non-locally originated packets */
if (rx->net_if != BT_MESH_NET_IF_LOCAL) {
/* Leave CTL bit intact */
sbuf->data[1] &= 0x80;
sbuf->data[1] |= rx->ctx.recv_ttl - 1;
}
net_buf_add_mem(buf, sbuf->data, sbuf->len);
enc = rx->sub->keys[rx->sub->kr_flag].enc;
priv = rx->sub->keys[rx->sub->kr_flag].privacy;
nid = rx->sub->keys[rx->sub->kr_flag].nid;
BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data));
/* Update NID if RX or RX was with friend credentials */
if (rx->friend_cred) {
buf->data[0] &= 0x80; /* Clear everything except IVI */
buf->data[0] |= nid;
}
/* We re-encrypt and obfuscate using the received IVI rather than
* the normal TX IVI (which may be different) since the transport
* layer nonce includes the IVI.
*/
if (bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_RX(rx), false)) {
BT_ERR("Re-encrypting failed");
goto done;
}
if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) {
BT_ERR("Re-obfuscating failed");
goto done;
}
/* Sending to the GATT bearer should only happen if GATT Proxy
* is enabled or the message originates from the local node.
*/
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
(bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED || rx->net_if == BT_MESH_NET_IF_LOCAL)) {
if (bt_mesh_proxy_relay(&buf->b, rx->ctx.recv_dst) && BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) {
goto done;
}
}
if (relay_to_adv(rx->net_if)) {
bt_mesh_adv_send(buf, NULL, NULL);
}
done:
net_buf_unref(buf);
}
int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if, struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
if (data->len < BT_MESH_NET_MIN_PDU_LEN) {
BT_WARN("Dropping too short mesh packet (len %u)", data->len);
BT_WARN("%s", bt_hex(data->data, data->len));
return -EINVAL;
}
if (net_if == BT_MESH_NET_IF_ADV && check_dup(data)) {
return -EINVAL;
}
BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len));
rx->net_if = net_if;
if (!net_find_and_decrypt(data->data, data->len, rx, buf)) {
BT_DBG("Unable to find matching net for packet");
return -ENOENT;
}
/* Initialize AppIdx to a sane value */
rx->ctx.app_idx = BT_MESH_KEY_UNUSED;
rx->ctx.recv_ttl = TTL(buf->data);
/* Default to responding with TTL 0 for non-routed messages */
if (rx->ctx.recv_ttl == 0) {
rx->ctx.send_ttl = 0;
} else {
rx->ctx.send_ttl = BT_MESH_TTL_DEFAULT;
}
rx->ctl = CTL(buf->data);
rx->seq = SEQ(buf->data);
rx->ctx.recv_dst = DST(buf->data);
BT_DBG("Decryption successful. Payload len %u", buf->len);
if (net_if != BT_MESH_NET_IF_PROXY_CFG && rx->ctx.recv_dst == BT_MESH_ADDR_UNASSIGNED) {
BT_ERR("Destination address is unassigned; dropping packet");
return -EBADMSG;
}
if (BT_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) {
BT_ERR("Destination address is RFU; dropping packet");
return -EBADMSG;
}
if (net_if != BT_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) {
BT_DBG("Dropping locally originated packet");
return -EBADMSG;
}
BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst, rx->ctx.recv_ttl);
BT_DBG("PDU: %s", bt_hex(buf->data, buf->len));
return 0;
}
#ifdef CONFIG_GENIE_MESH_ENABLE
static bool bt_mesh_net_rx_stat = false;
bool bt_mesh_net_is_rx(void)
{
return bt_mesh_net_rx_stat;
}
#endif
void bt_mesh_net_recv(struct net_buf_simple *data, s8_t rssi, enum bt_mesh_net_if net_if)
{
struct bt_mesh_net_rx rx = { .rssi = rssi };
struct net_buf_simple_state state;
BT_DBG("rssi %d net_if %u, len %d", rssi, net_if, data->len);
if (data->len > BT_MESH_NET_MAX_PDU_LEN) {
BT_ERR("Net PDU is too long %d(%d)", data->len, BT_MESH_NET_MAX_PDU_LEN);
return;
}
NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
#if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
if (BT_MESH_NET_IF_ADV == net_if) {
net_buf_trace.buf = &buf;
}
#endif
if (!bt_mesh_is_provisioned()) {
return;
}
#ifdef CONFIG_GENIE_MESH_ENABLE
bt_mesh_net_rx_stat = true;
#endif
if (bt_mesh_net_decode(data, net_if, &rx, &buf)) {
#ifdef CONFIG_GENIE_MESH_ENABLE
bt_mesh_net_rx_stat = false;
#endif
return;
}
/* Save the state so the buffer can later be relayed */
net_buf_simple_save(&buf, &state);
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && net_if == BT_MESH_NET_IF_PROXY) {
bt_mesh_proxy_addr_add(data, rx.ctx.addr);
}
rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) || bt_mesh_elem_find(rx.ctx.recv_dst));
bt_mesh_trans_recv(&buf, &rx);
/* Relay if this was a group/virtual address, or if the destination
* was neither a local element nor an LPN we're Friends for.
*/
if (!BT_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) || (!rx.local_match && !rx.friend_match)) {
net_buf_simple_restore(&buf, &state);
bt_mesh_net_relay(&buf, &rx);
}
#ifdef CONFIG_GENIE_MESH_ENABLE
bt_mesh_net_rx_stat = false;
#endif
}
static void ivu_refresh(struct k_work *work)
{
bt_mesh.ivu_duration += BT_MESH_IVU_HOURS;
BT_DBG("%s for %u hour%s",
atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ? "IVU in Progress" : "IVU Normal mode",
bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s");
if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_iv(true);
}
k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
return;
}
if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
bt_mesh_beacon_ivu_initiator(true);
bt_mesh_net_iv_update(bt_mesh.iv_index, false);
} else if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_iv(true);
}
}
void bt_mesh_net_start(void)
{
if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) {
bt_mesh_beacon_enable();
} else {
bt_mesh_beacon_disable();
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_NOT_SUPPORTED) {
bt_mesh_proxy_gatt_enable();
bt_mesh_adv_update();
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
bt_mesh_lpn_init();
} else {
bt_mesh_scan_enable();
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
bt_mesh_friend_init();
}
if (IS_ENABLED(CONFIG_BT_MESH_PROV)) {
u16_t net_idx = bt_mesh.sub[0].net_idx;
u16_t addr = bt_mesh_primary_addr();
bt_mesh_prov_complete(net_idx, addr);
}
}
void bt_mesh_net_init(void)
{
BT_INFO("enter %s\n", __func__);
k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh);
k_work_init(&bt_mesh.local_work, bt_mesh_net_local);
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/net.c | C | apache-2.0 | 40,614 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#include <api/mesh/proxy.h>
#include <bluetooth/uuid.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROV)
#include "common/log.h"
#include "host/ecc.h"
#include "host/testing.h"
#include "crypto.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "access.h"
#include "foundation.h"
#include "proxy.h"
#include "prov.h"
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
#ifdef CONFIG_GENIE_MESH_ENABLE
#include "genie_crypto.h"
#endif
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#endif
#ifdef MESH_DEBUG_PROV
#ifdef CONFIG_GENIE_MESH_ENABLE
#define PROV_TAG "\t[ALI_PROV]"
#else
#define PROV_TAG "\t[SIG_PROV]"
#endif
#define PROV_D(f, ...) LOGI(PROV_TAG, "\033[0;33m %s " f "\033[0m\n", __func__, ##__VA_ARGS__)
#else
#define PROV_D(f, ...)
#endif
/* 3 transmissions, 20ms interval */
#define PROV_XMIT BT_MESH_TRANSMIT(2, 20)
#define AUTH_METHOD_NO_OOB 0x00
#define AUTH_METHOD_STATIC 0x01
#define AUTH_METHOD_OUTPUT 0x02
#define AUTH_METHOD_INPUT 0x03
#define OUTPUT_OOB_BLINK 0x00
#define OUTPUT_OOB_BEEP 0x01
#define OUTPUT_OOB_VIBRATE 0x02
#define OUTPUT_OOB_NUMBER 0x03
#define OUTPUT_OOB_STRING 0x04
#define INPUT_OOB_PUSH 0x00
#define INPUT_OOB_TWIST 0x01
#define INPUT_OOB_NUMBER 0x02
#define INPUT_OOB_STRING 0x03
#define PROV_ERR_NONE 0x00
#define PROV_ERR_NVAL_PDU 0x01
#define PROV_ERR_NVAL_FMT 0x02
#define PROV_ERR_UNEXP_PDU 0x03
#define PROV_ERR_CFM_FAILED 0x04
#define PROV_ERR_RESOURCES 0x05
#define PROV_ERR_DECRYPT 0x06
#define PROV_ERR_UNEXP_ERR 0x07
#define PROV_ERR_ADDR 0x08
#define PROV_INVITE 0x00
#define PROV_CAPABILITIES 0x01
#define PROV_START 0x02
#define PROV_PUB_KEY 0x03
#define PROV_INPUT_COMPLETE 0x04
#define PROV_CONFIRM 0x05
#define PROV_RANDOM 0x06
#define PROV_DATA 0x07
#define PROV_COMPLETE 0x08
#define PROV_FAILED 0x09
#define PROV_ALG_P256 0x00
#define GPCF(gpc) (gpc & 0x03)
#define GPC_START(last_seg) (((last_seg) << 2) | 0x00)
#define GPC_ACK 0x01
#define GPC_CONT(seg_id) (((seg_id) << 2) | 0x02)
#define GPC_CTL(op) (((op) << 2) | 0x03)
#define START_PAYLOAD_MAX 20
#define CONT_PAYLOAD_MAX 23
#define START_LAST_SEG(gpc) (gpc >> 2)
#define CONT_SEG_INDEX(gpc) (gpc >> 2)
#define BEARER_CTL(gpc) (gpc >> 2)
#define LINK_OPEN 0x00
#define LINK_ACK 0x01
#define LINK_CLOSE 0x02
#define CLOSE_REASON_SUCCESS 0x00
#define CLOSE_REASON_TIMEOUT 0x01
#define CLOSE_REASON_FAILED 0x02
#define XACT_SEG_DATA(_seg) (&plink.rx.buf->data[20 + ((_seg - 1) * 23)])
#define XACT_SEG_RECV(_seg) (plink.rx.seg &= ~(1 << (_seg)))
#define XACT_NVAL 0xFF
enum {
REMOTE_PUB_KEY, /* Remote key has been received */
LOCAL_PUB_KEY, /* Local public key is available */
LINK_ACTIVE, /* Link has been opened */
HAVE_DHKEY, /* DHKey has been calcualted */
SEND_CONFIRM, /* Waiting to send Confirm value */
WAIT_NUMBER, /* Waiting for number input from user */
WAIT_STRING, /* Waiting for string input from user */
NUM_FLAGS,
};
struct prov_link {
ATOMIC_DEFINE(flags, NUM_FLAGS);
#if defined(CONFIG_BT_MESH_PB_GATT)
struct bt_conn *conn; /* GATT connection */
#endif
u8_t dhkey[32]; /* Calculated DHKey */
u8_t expect; /* Next expected PDU */
u8_t oob_method;
u8_t oob_action;
u8_t oob_size;
u8_t conf[16]; /* Remote Confirmation */
u8_t rand[16]; /* Local Random */
u8_t auth[16]; /* Authentication Value */
u8_t conf_salt[16]; /* ConfirmationSalt */
u8_t conf_key[16]; /* ConfirmationKey */
u8_t conf_inputs[145]; /* ConfirmationInputs */
u8_t prov_salt[16]; /* Provisioning Salt */
#ifdef CONFIG_BT_MESH_PROVISIONER
u8_t remote_dev_key[16];
u16_t unicast_addr;
#endif
#if defined(CONFIG_BT_MESH_PB_ADV)
bt_u32_t id; /* Link ID */
struct {
u8_t id; /* Transaction ID */
u8_t prev_id; /* Previous Transaction ID */
u8_t seg; /* Bit-field of unreceived segments */
u8_t last_seg; /* Last segment (to check length) */
u8_t fcs; /* Expected FCS value */
struct net_buf_simple *buf;
} rx;
struct {
/* Start timestamp of the transaction */
s64_t start;
/* Transaction id*/
u8_t id;
/* Pending outgoing buffer(s) */
struct net_buf *buf[3];
/* Retransmit timer */
struct k_delayed_work retransmit;
} tx;
#endif
};
struct prov_rx {
bt_u32_t link_id;
u8_t xact_id;
u8_t gpc;
};
#define RETRANSMIT_TIMEOUT K_MSEC(500)
#define BUF_TIMEOUT K_MSEC(400)
#define TRANSACTION_TIMEOUT K_SECONDS(30)
#define PROV_TIMEOUT K_SECONDS(60)
#if defined(CONFIG_BT_MESH_PB_GATT)
#define PROV_BUF_HEADROOM 5
#else
#define PROV_BUF_HEADROOM 0
NET_BUF_SIMPLE_DEFINE_STATIC(rx_buf, 65);
#endif
#define PROV_BUF(name, len) NET_BUF_SIMPLE_DEFINE(name, PROV_BUF_HEADROOM + len)
static struct prov_link plink;
static const struct bt_mesh_prov *prov;
static u8_t prov_method = 0;
#ifndef CONFIG_BT_MESH_PROV_TIMEOUT
#define CONFIG_BT_MESH_PROV_TIMEOUT 1
#endif
#if CONFIG_BT_MESH_PROV_TIMEOUT
static k_timer_t g_prov_timeout;
#endif
static void close_link(u8_t err, u8_t reason);
#ifdef CONFIG_MESH_GENIE_APP
__attribute__((weak)) int genie_set_static_auth(uint8_t *link_auth, uint8_t *random)
{
(void)link_auth;
(void)random;
return 0;
}
#endif
#ifdef CONFIG_BT_BQB
static void reset_state_without_linkclose()
{
/* Disable Attention Timer if it was set */
if (plink.conf_inputs[0]) {
bt_mesh_attention(NULL, 0);
}
#if defined(CONFIG_BT_MESH_PB_ADV)
/* Clear everything except the retransmit delayed work config */
struct bt_conn *conn = plink.conn;
(void)memset(&plink, 0, offsetof(struct prov_link, tx.retransmit));
plink.rx.prev_id = XACT_NVAL;
plink.conn = conn;
#if defined(CONFIG_BT_MESH_PB_GATT)
plink.rx.buf = bt_mesh_proxy_get_buf();
#else
net_buf_simple_reset(&rx_buf);
plink.rx.buf = &rx_buf;
#endif /* PB_GATT */
#else
struct bt_conn *conn = plink.conn;
(void)memset(&plink, 0, sizeof(plink));
plink.conn = conn;
#endif /* PB_ADV */
}
#endif
extern int32_t csi_kernel_delay_ms(uint32_t ms);
static void reset_state(void)
{
prov_method = 0;
#ifdef CONFIG_BT_BQB
int err;
/* wait dhkey gen complete */
csi_kernel_delay_ms(5000);
extern int bt_pub_key_regen();
err = bt_pub_key_regen();
if (err) {
BT_ERR("Failed to generate public key (%d)", err);
return;
}
#endif
/* Disable Attention Timer if it was set */
if (plink.conf_inputs[0]) {
bt_mesh_attention(NULL, 0);
}
#if defined(CONFIG_BT_MESH_PB_GATT)
if (plink.conn) {
bt_conn_unref(plink.conn);
}
#endif
#if defined(CONFIG_BT_MESH_PB_ADV)
/* Clear everything except the retransmit delayed work config */
(void)memset(&plink, 0, offsetof(struct prov_link, tx.retransmit));
plink.rx.prev_id = XACT_NVAL;
#if defined(CONFIG_BT_MESH_PB_GATT)
plink.rx.buf = bt_mesh_proxy_get_buf();
#else
net_buf_simple_reset(&rx_buf);
plink.rx.buf = &rx_buf;
#endif /* PB_GATT */
#else
(void)memset(&plink, 0, sizeof(plink));
#endif /* PB_ADV */
}
#if defined(CONFIG_BT_MESH_PB_ADV)
static void buf_sent(int err, void *user_data)
{
if (!plink.tx.buf[0]) {
return;
}
k_delayed_work_submit(&plink.tx.retransmit, RETRANSMIT_TIMEOUT);
}
static struct bt_mesh_send_cb buf_sent_cb = {
.end = buf_sent,
};
static void free_segments(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(plink.tx.buf); i++) {
struct net_buf *buf = plink.tx.buf[i];
if (!buf) {
break;
}
plink.tx.buf[i] = NULL;
/* Mark as canceled */
BT_MESH_ADV(buf)->busy = 0;
net_buf_unref(buf);
}
}
static void prov_clear_tx(void)
{
BT_DBG("");
k_delayed_work_cancel(&plink.tx.retransmit);
free_segments();
}
void reset_link(void)
{
prov_clear_tx();
if (prov->link_close) {
prov->link_close(BT_MESH_PROV_ADV);
}
reset_state();
}
static struct net_buf *adv_buf_create(void)
{
struct net_buf *buf;
buf = bt_mesh_adv_create(BT_MESH_ADV_PROV, PROV_XMIT, BUF_TIMEOUT);
if (!buf) {
BT_ERR("Out of provisioning buffers");
return NULL;
}
return buf;
}
static atomic_t pending_ack = 0x00;
static void ack_complete(int err, void *user_data)
{
struct net_buf *buf = (struct net_buf *)user_data;
uint32_t link_id = net_buf_pull_be32(buf);
uint8_t ack_index = net_buf_pull_u8(buf);
atomic_clear_bit(&pending_ack, ack_index);
BT_DBG("linkid: %d xact index %u send complete", link_id, ack_index);
net_buf_unref(buf);
(void)link_id;
}
static void gen_prov_ack_send(u8_t xact_id)
{
static const struct bt_mesh_send_cb cb = {
.end = ack_complete,
};
const struct bt_mesh_send_cb *complete = &cb;
struct net_buf *buf;
BT_DBG("xact_id %u %02x", xact_id, pending_ack);
if (atomic_test_and_set_bit(&pending_ack, xact_id)) {
BT_DBG("The xact_id aready exit int adv pool");
return;
}
buf = adv_buf_create();
if (!buf) {
return;
}
net_buf_add_be32(buf, plink.id);
net_buf_add_u8(buf, xact_id);
net_buf_add_u8(buf, GPC_ACK);
bt_mesh_adv_send(buf, complete, buf);
}
static void send_reliable(void)
{
int i;
plink.tx.start = k_uptime_get();
for (i = 0; i < ARRAY_SIZE(plink.tx.buf); i++) {
struct net_buf *buf = plink.tx.buf[i];
if (!buf) {
break;
}
if (i + 1 < ARRAY_SIZE(plink.tx.buf) && plink.tx.buf[i + 1]) {
bt_mesh_adv_send(buf, NULL, NULL);
} else {
bt_mesh_adv_send(buf, &buf_sent_cb, NULL);
}
}
}
static int bearer_ctl_send(u8_t op, void *data, u8_t data_len)
{
struct net_buf *buf;
BT_DBG("op 0x%02x data_len %u", op, data_len);
prov_clear_tx();
buf = adv_buf_create();
if (!buf) {
return -ENOBUFS;
}
net_buf_add_be32(buf, plink.id);
/* Transaction ID, always 0 for Bearer messages */
net_buf_add_u8(buf, 0x00);
net_buf_add_u8(buf, GPC_CTL(op));
net_buf_add_mem(buf, data, data_len);
plink.tx.buf[0] = buf;
send_reliable();
return 0;
}
static u8_t last_seg(u8_t len)
{
if (len <= START_PAYLOAD_MAX) {
return 0;
}
len -= START_PAYLOAD_MAX;
return 1 + (len / CONT_PAYLOAD_MAX);
}
static inline u8_t next_transaction_id(void)
{
if (plink.tx.id != 0 && plink.tx.id != 0xFF) {
return ++plink.tx.id;
}
plink.tx.id = 0x80;
return plink.tx.id;
}
static int prov_send_adv(struct net_buf_simple *msg)
{
struct net_buf *start, *buf;
u8_t seg_len, seg_id;
u8_t xact_id;
BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
// PROV_D("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
PROV_D("len %u", msg->len);
prov_clear_tx();
start = adv_buf_create();
if (!start) {
return -ENOBUFS;
}
xact_id = next_transaction_id();
net_buf_add_be32(start, plink.id);
net_buf_add_u8(start, xact_id);
net_buf_add_u8(start, GPC_START(last_seg(msg->len)));
net_buf_add_be16(start, msg->len);
net_buf_add_u8(start, bt_mesh_fcs_calc(msg->data, msg->len));
plink.tx.buf[0] = start;
seg_len = MIN(msg->len, START_PAYLOAD_MAX);
BT_DBG("seg 0 len %u: %s", seg_len, bt_hex(msg->data, seg_len));
net_buf_add_mem(start, msg->data, seg_len);
net_buf_simple_pull(msg, seg_len);
buf = start;
for (seg_id = 1; msg->len > 0; seg_id++) {
if (seg_id >= ARRAY_SIZE(plink.tx.buf)) {
BT_ERR("Too big message");
free_segments();
return -E2BIG;
}
buf = adv_buf_create();
if (!buf) {
free_segments();
return -ENOBUFS;
}
plink.tx.buf[seg_id] = buf;
seg_len = MIN(msg->len, CONT_PAYLOAD_MAX);
BT_DBG("seg_id %u len %u: %s", seg_id, seg_len, bt_hex(msg->data, seg_len));
net_buf_add_be32(buf, plink.id);
net_buf_add_u8(buf, xact_id);
net_buf_add_u8(buf, GPC_CONT(seg_id));
net_buf_add_mem(buf, msg->data, seg_len);
net_buf_simple_pull(msg, seg_len);
}
send_reliable();
return 0;
}
#endif /* CONFIG_BT_MESH_PB_ADV */
#if defined(CONFIG_BT_MESH_PB_GATT)
static int prov_send_gatt(struct net_buf_simple *msg)
{
if (!plink.conn) {
return -ENOTCONN;
}
return bt_mesh_proxy_send(plink.conn, BT_MESH_PROXY_PROV, msg);
}
#endif /* CONFIG_BT_MESH_PB_GATT */
static inline int prov_send(struct net_buf_simple *buf)
{
#if defined(CONFIG_BT_MESH_PB_GATT)
if (plink.conn) {
return prov_send_gatt(buf);
}
#endif
#if defined(CONFIG_BT_MESH_PB_ADV)
return prov_send_adv(buf);
#else
return 0;
#endif
}
static void prov_buf_init(struct net_buf_simple *buf, u8_t type)
{
net_buf_simple_reserve(buf, PROV_BUF_HEADROOM);
net_buf_simple_add_u8(buf, type);
}
static void prov_send_fail_msg(u8_t err)
{
PROV_BUF(buf, 2);
prov_buf_init(&buf, PROV_FAILED);
net_buf_simple_add_u8(&buf, err);
prov_send(&buf);
#ifdef CONFIG_BT_BQB
reset_state_without_linkclose();
#endif
}
static void prov_invite(const u8_t *data)
{
PROV_BUF(buf, 12);
BT_DBG("Attention Duration: %u seconds", data[0]);
PROV_D(", 1--->2");
if (data[0]) {
bt_mesh_attention(NULL, data[0]);
}
plink.conf_inputs[0] = data[0];
prov_buf_init(&buf, PROV_CAPABILITIES);
/* Number of Elements supported */
net_buf_simple_add_u8(&buf, bt_mesh_elem_count());
/* Supported algorithms - FIPS P-256 Eliptic Curve */
net_buf_simple_add_be16(&buf, BIT(PROV_ALG_P256));
/* Public Key Type */
net_buf_simple_add_u8(&buf, 0x00);
/* Static OOB Type */
net_buf_simple_add_u8(&buf, prov->static_val && prov->static_val_len ? BIT(0) : 0x00);
/* Output OOB Size */
net_buf_simple_add_u8(&buf, prov->output_size);
/* Output OOB Action */
net_buf_simple_add_be16(&buf, prov->output_actions);
/* Input OOB Size */
net_buf_simple_add_u8(&buf, prov->input_size);
/* Input OOB Action */
net_buf_simple_add_be16(&buf, prov->input_actions);
memcpy(&plink.conf_inputs[1], &buf.data[1], 11);
if (prov_send(&buf)) {
BT_ERR("Failed to send capabilities");
close_link(PROV_ERR_RESOURCES, CLOSE_REASON_FAILED);
return;
}
plink.expect = PROV_START;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#if defined(CONFIG_BT_MESH_PB_GATT)
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (plink.conn && event_cb) {
event_cb(BT_MESH_MODEL_EVT_PROV_START, NULL);
}
#endif
#endif
}
static void prov_capabilities(const u8_t *data)
{
BT_DBG("Elements: %u", data[0]);
BT_DBG("Algorithms: %u", sys_get_be16(&data[1]));
BT_DBG("Public Key Type: 0x%02x", data[3]);
BT_DBG("Static OOB Type: 0x%02x", data[4]);
BT_DBG("Output OOB Size: %u", data[5]);
BT_DBG("Output OOB Action: 0x%04x", sys_get_be16(&data[6]));
BT_DBG("Input OOB Size: %u", data[8]);
BT_DBG("Input OOB Action: 0x%04x", sys_get_be16(&data[9]));
}
static bt_mesh_output_action_t output_action(u8_t action)
{
switch (action) {
case OUTPUT_OOB_BLINK:
return BT_MESH_BLINK;
case OUTPUT_OOB_BEEP:
return BT_MESH_BEEP;
case OUTPUT_OOB_VIBRATE:
return BT_MESH_VIBRATE;
case OUTPUT_OOB_NUMBER:
return BT_MESH_DISPLAY_NUMBER;
case OUTPUT_OOB_STRING:
return BT_MESH_DISPLAY_STRING;
default:
return BT_MESH_NO_OUTPUT;
}
}
static bt_mesh_input_action_t input_action(u8_t action)
{
switch (action) {
case INPUT_OOB_PUSH:
return BT_MESH_PUSH;
case INPUT_OOB_TWIST:
return BT_MESH_TWIST;
case INPUT_OOB_NUMBER:
return BT_MESH_ENTER_NUMBER;
case INPUT_OOB_STRING:
return BT_MESH_ENTER_STRING;
default:
return BT_MESH_NO_INPUT;
}
}
static int prov_auth(u8_t method, u8_t action, u8_t size)
{
bt_mesh_output_action_t output;
bt_mesh_input_action_t input;
prov_method = method;
switch (method) {
case AUTH_METHOD_NO_OOB:
if (action || size) {
return -EINVAL;
}
memset(plink.auth, 0, sizeof(plink.auth));
return 0;
case AUTH_METHOD_STATIC:
if (action || size) {
return -EINVAL;
}
memcpy(plink.auth + 16 - prov->static_val_len, prov->static_val, prov->static_val_len);
(void)memset(plink.auth, 0, sizeof(plink.auth) - prov->static_val_len);
return 0;
case AUTH_METHOD_OUTPUT:
output = output_action(action);
if (!output) {
return -EINVAL;
}
if (!(prov->output_actions & output)) {
return -EINVAL;
}
if (size > prov->output_size) {
return -EINVAL;
}
if (output == BT_MESH_DISPLAY_STRING) {
unsigned char str[9];
u8_t i;
bt_rand(str, size);
/* Normalize to '0' .. '9' & 'A' .. 'Z' */
for (i = 0; i < size; i++) {
str[i] %= 36;
if (str[i] < 10) {
str[i] += '0';
} else {
str[i] += 'A' - 10;
}
}
str[size] = '\0';
memcpy(plink.auth, str, size);
(void)memset(plink.auth + size, 0, sizeof(plink.auth) - size);
return prov->output_string((char *)str);
} else {
bt_u32_t div[8] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
bt_u32_t num;
bt_rand(&num, sizeof(num));
num %= div[size - 1];
sys_put_be32(num, &plink.auth[12]);
memset(plink.auth, 0, 12);
return prov->output_number(output, num);
}
case AUTH_METHOD_INPUT:
input = input_action(action);
if (!input) {
return -EINVAL;
}
if (!(prov->input_actions & input)) {
return -EINVAL;
}
if (size > prov->input_size) {
return -EINVAL;
}
if (input == BT_MESH_ENTER_STRING) {
atomic_set_bit(plink.flags, WAIT_STRING);
} else {
atomic_set_bit(plink.flags, WAIT_NUMBER);
}
return prov->input(input, size);
default:
return -EINVAL;
}
}
static void prov_start(const u8_t *data)
{
BT_DBG("Algorithm: 0x%02x", data[0]);
BT_DBG("Public Key: 0x%02x", data[1]);
BT_DBG("Auth Method: 0x%02x", data[2]);
BT_DBG("Auth Action: 0x%02x", data[3]);
BT_DBG("Auth Size: 0x%02x", data[4]);
PROV_D(", 2--->3");
if (data[0] != PROV_ALG_P256) {
BT_ERR("Unknown algorithm 0x%02x", data[0]);
prov_send_fail_msg(PROV_ERR_NVAL_FMT);
return;
}
#ifdef CONFIG_BT_BQB
/* not support public key oob */
if (data[1] != 0x00) {
BT_ERR("Invalid public key value: 0x%02x", data[1]);
prov_send_fail_msg(PROV_ERR_NVAL_FMT);
return;
}
#else
if (data[1] > 0x01) {
BT_ERR("Invalid public key value: 0x%02x", data[1]);
prov_send_fail_msg(PROV_ERR_NVAL_FMT);
return;
}
#endif
memcpy(&plink.conf_inputs[12], data, 5);
plink.expect = PROV_PUB_KEY;
if (prov_auth(data[2], data[3], data[4]) < 0) {
BT_ERR("Invalid authentication method: 0x%02x; "
"action: 0x%02x; size: 0x%02x",
data[2], data[3], data[4]);
prov_send_fail_msg(PROV_ERR_NVAL_FMT);
}
}
static void send_confirm(void)
{
PROV_BUF(cfm, 17);
BT_DBG("ConfInputs[0] %s", bt_hex(plink.conf_inputs, 64));
BT_DBG("ConfInputs[64] %s", bt_hex(&plink.conf_inputs[64], 64));
BT_DBG("ConfInputs[128] %s", bt_hex(&plink.conf_inputs[128], 17));
if (bt_mesh_prov_conf_salt(plink.conf_inputs, plink.conf_salt)) {
BT_ERR("Unable to generate confirmation salt");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("ConfirmationSalt: %s", bt_hex(plink.conf_salt, 16));
if (bt_mesh_prov_conf_key(plink.dhkey, plink.conf_salt, plink.conf_key)) {
BT_ERR("Unable to generate confirmation key");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("ConfirmationKey: %s", bt_hex(plink.conf_key, 16));
if (bt_rand(plink.rand, 16)) {
BT_ERR("Unable to generate random number");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("LocalRandom: %s", bt_hex(plink.rand, 16));
prov_buf_init(&cfm, PROV_CONFIRM);
#ifdef CONFIG_GENIE_MESH_ENABLE
if (prov_method == AUTH_METHOD_STATIC) {
memcpy(plink.auth, genie_crypto_get_auth(plink.rand), STATIC_OOB_LENGTH);
}
#endif
if (bt_mesh_prov_conf(plink.conf_key, plink.rand, plink.auth, net_buf_simple_add(&cfm, 16))) {
BT_ERR("Unable to generate confirmation value");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
if (prov_send(&cfm)) {
BT_ERR("Failed to send Provisioning Confirm");
close_link(PROV_ERR_RESOURCES, CLOSE_REASON_FAILED);
return;
}
plink.expect = PROV_RANDOM;
}
static void send_input_complete(void)
{
PROV_BUF(buf, 1);
prov_buf_init(&buf, PROV_INPUT_COMPLETE);
prov_send(&buf);
}
int bt_mesh_input_number(bt_u32_t num)
{
BT_DBG("%u", num);
if (!atomic_test_and_clear_bit(plink.flags, WAIT_NUMBER)) {
return -EINVAL;
}
sys_put_be32(num, &plink.auth[12]);
send_input_complete();
if (!atomic_test_bit(plink.flags, HAVE_DHKEY)) {
return 0;
}
if (atomic_test_and_clear_bit(plink.flags, SEND_CONFIRM)) {
send_confirm();
}
return 0;
}
int bt_mesh_input_string(const char *str)
{
if (!str) {
return -EINVAL;
}
BT_DBG("%s", str);
if (!atomic_test_and_clear_bit(plink.flags, WAIT_STRING)) {
return -EINVAL;
}
strncpy((char *)plink.auth, str, prov->input_size);
send_input_complete();
if (!atomic_test_bit(plink.flags, HAVE_DHKEY)) {
return 0;
}
if (atomic_test_and_clear_bit(plink.flags, SEND_CONFIRM)) {
send_confirm();
}
return 0;
}
static void prov_dh_key_cb(const u8_t key[32])
{
BT_DBG("%p", key);
if (!key) {
BT_ERR("DHKey generation failed");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
sys_memcpy_swap(plink.dhkey, key, 32);
BT_DBG("DHkey: %s", bt_hex(plink.dhkey, 32));
atomic_set_bit(plink.flags, HAVE_DHKEY);
if (atomic_test_bit(plink.flags, WAIT_NUMBER) || atomic_test_bit(plink.flags, WAIT_STRING)) {
return;
}
if (atomic_test_and_clear_bit(plink.flags, SEND_CONFIRM)) {
send_confirm();
}
}
static void send_pub_key(void)
{
PROV_BUF(buf, 65);
const u8_t *key;
key = bt_pub_key_get();
if (!key) {
BT_ERR("No public key available");
close_link(PROV_ERR_RESOURCES, CLOSE_REASON_FAILED);
return;
}
BT_DBG("Local Public Key: %s", bt_hex(key, 64));
prov_buf_init(&buf, PROV_PUB_KEY);
/* Swap X and Y halves independently to big-endian */
sys_memcpy_swap(net_buf_simple_add(&buf, 32), key, 32);
sys_memcpy_swap(net_buf_simple_add(&buf, 32), &key[32], 32);
memcpy(&plink.conf_inputs[81], &buf.data[1], 64);
prov_send(&buf);
/* Copy remote key in little-endian for bt_dh_key_gen().
* X and Y halves are swapped independently.
*/
net_buf_simple_reset(&buf);
sys_memcpy_swap(buf.data, &plink.conf_inputs[17], 32);
sys_memcpy_swap(&buf.data[32], &plink.conf_inputs[49], 32);
if (bt_dh_key_gen(buf.data, prov_dh_key_cb)) {
BT_ERR("Failed to generate DHKey");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
plink.expect = PROV_CONFIRM;
}
static void prov_pub_key(const u8_t *data)
{
BT_DBG("Remote Public Key: %s", bt_hex(data, 64));
PROV_D(", 3--->4");
memcpy(&plink.conf_inputs[17], data, 64);
if (!bt_pub_key_get()) {
/* Clear retransmit timer */
#if defined(CONFIG_BT_MESH_PB_ADV)
prov_clear_tx();
#endif
atomic_set_bit(plink.flags, REMOTE_PUB_KEY);
BT_WARN("Waiting for local public key");
return;
}
send_pub_key();
}
static void pub_key_ready(const u8_t *pkey)
{
if (!pkey) {
BT_WARN("Public key not available");
return;
}
BT_DBG("Local public key ready");
if (atomic_test_and_clear_bit(plink.flags, REMOTE_PUB_KEY)) {
send_pub_key();
}
}
static void prov_input_complete(const u8_t *data)
{
BT_DBG("");
}
static void prov_confirm(const u8_t *data)
{
BT_DBG("Remote Confirm: %s", bt_hex(data, 16));
PROV_D(", 4--->5");
memcpy(plink.conf, data, 16);
if (!atomic_test_bit(plink.flags, HAVE_DHKEY)) {
#if defined(CONFIG_BT_MESH_PB_ADV)
prov_clear_tx();
#endif
atomic_set_bit(plink.flags, SEND_CONFIRM);
} else {
send_confirm();
}
}
static void prov_random(const u8_t *data)
{
PROV_BUF(rnd, 16);
u8_t conf_verify[16];
PROV_D(", 5--->6");
BT_DBG("Remote Random: %s", bt_hex(data, 16));
#ifdef CONFIG_GENIE_MESH_ENABLE
if (prov_method == AUTH_METHOD_STATIC) {
memcpy(plink.auth, genie_crypto_get_auth(data), STATIC_OOB_LENGTH);
}
#endif
if (bt_mesh_prov_conf(plink.conf_key, data, plink.auth, conf_verify)) {
BT_ERR("Unable to calculate confirmation verification");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
if (memcmp(conf_verify, plink.conf, 16)) {
BT_ERR("Invalid confirmation value");
BT_DBG("Received: %s", bt_hex(plink.conf, 16));
BT_DBG("Calculated: %s", bt_hex(conf_verify, 16));
close_link(PROV_ERR_CFM_FAILED, CLOSE_REASON_FAILED);
return;
}
prov_buf_init(&rnd, PROV_RANDOM);
net_buf_simple_add_mem(&rnd, plink.rand, 16);
if (prov_send(&rnd)) {
BT_ERR("Failed to send Provisioning Random");
close_link(PROV_ERR_RESOURCES, CLOSE_REASON_FAILED);
return;
}
if (bt_mesh_prov_salt(plink.conf_salt, data, plink.rand, plink.prov_salt)) {
BT_ERR("Failed to generate provisioning salt");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("ProvisioningSalt: %s", bt_hex(plink.prov_salt, 16));
plink.expect = PROV_DATA;
}
static inline bool is_pb_gatt(void)
{
#if defined(CONFIG_BT_MESH_PB_GATT)
return !!plink.conn;
#else
return false;
#endif
}
static void prov_data(const u8_t *data)
{
PROV_BUF(msg, 1);
u8_t session_key[16];
u8_t nonce[13];
u8_t dev_key[16];
u8_t pdu[25];
u8_t flags;
bt_u32_t iv_index;
u16_t addr;
u16_t net_idx;
int err;
bool identity_enable;
BT_DBG("");
PROV_D(", 6--->7");
err = bt_mesh_session_key(plink.dhkey, plink.prov_salt, session_key);
if (err) {
BT_ERR("Unable to generate session key");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("SessionKey: %s", bt_hex(session_key, 16));
err = bt_mesh_prov_nonce(plink.dhkey, plink.prov_salt, nonce);
if (err) {
BT_ERR("Unable to generate session nonce");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("Nonce: %s", bt_hex(nonce, 13));
err = bt_mesh_prov_decrypt(session_key, nonce, data, pdu);
if (err) {
BT_ERR("Unable to decrypt provisioning data");
close_link(PROV_ERR_DECRYPT, CLOSE_REASON_FAILED);
return;
}
err = bt_mesh_dev_key(plink.dhkey, plink.prov_salt, dev_key);
if (err) {
BT_ERR("Unable to generate device key");
close_link(PROV_ERR_UNEXP_ERR, CLOSE_REASON_FAILED);
return;
}
BT_DBG("DevKey: %s", bt_hex(dev_key, 16));
net_idx = sys_get_be16(&pdu[16]);
flags = pdu[18];
iv_index = sys_get_be32(&pdu[19]);
addr = sys_get_be16(&pdu[23]);
BT_DBG("net_idx %u iv_index 0x%08x, addr 0x%04x", net_idx, iv_index, addr);
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_PROV_DATA, &addr);
}
#endif
prov_buf_init(&msg, PROV_COMPLETE);
prov_send(&msg);
/* Ignore any further PDUs on this plink */
plink.expect = 0;
/* Store info, since bt_mesh_provision() will end up clearing it */
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
identity_enable = is_pb_gatt();
} else {
identity_enable = false;
}
err = bt_mesh_provision(pdu, net_idx, flags, iv_index, addr, dev_key);
if (err) {
BT_ERR("Failed to provision (err %d)", err);
return;
}
#ifdef CONFIG_BT_MESH_PROVISIONER
bt_mesh.p_net_idx_next = net_idx;
struct node_info node_info;
struct bt_le_oob oob;
bt_le_oob_get_local(0, &oob);
memcpy(&node_info.addr, &oob.addr, sizeof(bt_addr_le_t));
memcpy(node_info.uuid, prov->uuid, 16);
node_info.oob_info = prov->oob_info;
node_info.element_num = bt_mesh_elem_count();
node_info.unicast_addr = addr;
node_info.net_idx = net_idx;
node_info.flags = flags;
node_info.iv_index = iv_index;
bt_mesh_provisioner_add_node(&node_info, dev_key);
#endif
/* After PB-GATT provisioning we should start advertising
* using Node Identity.
*/
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && identity_enable) {
bt_mesh_proxy_identity_enable();
}
}
static void prov_complete(const u8_t *data)
{
BT_DBG("");
PROV_D(", 9--->10");
}
static void prov_failed(const u8_t *data)
{
BT_WARN("Error: 0x%02x", data[0]);
}
static const struct {
void (*func)(const u8_t *data);
u16_t len;
} prov_handlers[] = {
{ prov_invite, 1 },
{ prov_capabilities, 11 },
{
prov_start,
5,
},
{ prov_pub_key, 64 },
{ prov_input_complete, 0 },
{ prov_confirm, 16 },
{ prov_random, 16 },
{ prov_data, 33 },
{ prov_complete, 0 },
{ prov_failed, 1 },
};
static void close_link(u8_t err, u8_t reason)
{
#if defined(CONFIG_BT_MESH_PB_GATT)
if (plink.conn) {
if (err) {
prov_send_fail_msg(err);
}
#ifndef CONFIG_BT_BQB
bt_mesh_pb_gatt_close(plink.conn);
#endif
return;
}
#endif
#if defined(CONFIG_BT_MESH_PB_ADV)
if (err) {
prov_send_fail_msg(err);
}
plink.rx.seg = 0;
bearer_ctl_send(LINK_CLOSE, &reason, sizeof(reason));
#endif
reset_state();
}
#if defined(CONFIG_BT_MESH_PB_ADV)
static void prov_retransmit(struct k_work *work)
{
int i;
BT_DBG("");
if (!atomic_test_bit(plink.flags, LINK_ACTIVE)) {
BT_WARN("Link not active");
return;
}
if (k_uptime_get() - plink.tx.start > TRANSACTION_TIMEOUT) {
BT_WARN("Giving up transaction");
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_stop(&g_prov_timeout);
#endif
reset_link();
return;
}
for (i = 0; i < ARRAY_SIZE(plink.tx.buf); i++) {
struct net_buf *buf = plink.tx.buf[i];
if (!buf) {
break;
}
if (BT_MESH_ADV(buf)->busy) {
continue;
}
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (i + 1 < ARRAY_SIZE(plink.tx.buf) && plink.tx.buf[i + 1]) {
bt_mesh_adv_send(buf, NULL, NULL);
} else {
bt_mesh_adv_send(buf, &buf_sent_cb, NULL);
}
}
}
static void link_open(struct prov_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("len %u", buf->len);
if (buf->len < 16) {
BT_ERR("Too short bearer open message (len %u)", buf->len);
return;
}
if (atomic_test_bit(plink.flags, LINK_ACTIVE)) {
/* Send another plink ack if the provisioner missed the last */
if (plink.id == rx->link_id && plink.expect == PROV_INVITE) {
BT_DBG("Resending link ack");
bearer_ctl_send(LINK_ACK, NULL, 0);
} else {
BT_WARN("Ignoring bearer open: plink already active");
}
return;
}
if (memcmp(buf->data, prov->uuid, 16)) {
BT_DBG("Bearer open message not for us");
return;
}
if (prov->link_open) {
prov->link_open(BT_MESH_PROV_ADV);
}
plink.id = rx->link_id;
atomic_set_bit(plink.flags, LINK_ACTIVE);
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_start(&g_prov_timeout, PROV_TIMEOUT);
#endif
net_buf_simple_reset(plink.rx.buf);
bearer_ctl_send(LINK_ACK, NULL, 0);
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_PROV_START, &plink.id);
}
#endif
plink.expect = PROV_INVITE;
}
static void link_ack(struct prov_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("len %u", buf->len);
}
static void link_close(struct prov_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("len %u", buf->len);
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_stop(&g_prov_timeout);
#endif
reset_link();
}
static void gen_prov_ctl(struct prov_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("op 0x%02x len %u", BEARER_CTL(rx->gpc), buf->len);
switch (BEARER_CTL(rx->gpc)) {
case LINK_OPEN:
link_open(rx, buf);
break;
case LINK_ACK:
if (!atomic_test_bit(plink.flags, LINK_ACTIVE)) {
return;
}
link_ack(rx, buf);
break;
case LINK_CLOSE:
if (!atomic_test_bit(plink.flags, LINK_ACTIVE)) {
return;
}
link_close(rx, buf);
break;
default:
BT_ERR("Unknown bearer opcode: 0x%02x", BEARER_CTL(rx->gpc));
if (IS_ENABLED(CONFIG_BT_TESTING)) {
bt_test_mesh_prov_invalid_bearer(BEARER_CTL(rx->gpc));
}
return;
}
}
static void prov_msg_recv(void)
{
u8_t type = plink.rx.buf->data[0];
BT_DBG("type 0x%02x len %u", type, plink.rx.buf->len);
if (!bt_mesh_fcs_check(plink.rx.buf, plink.rx.fcs)) {
BT_ERR("Incorrect FCS");
return;
}
gen_prov_ack_send(plink.rx.id);
plink.rx.prev_id = plink.rx.id;
plink.rx.id = 0;
if (type != PROV_FAILED && type != plink.expect) {
BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, plink.expect);
prov_send_fail_msg(PROV_ERR_UNEXP_PDU);
return;
}
if (type >= ARRAY_SIZE(prov_handlers)) {
BT_ERR("Unknown provisioning PDU type 0x%02x", type);
close_link(PROV_ERR_NVAL_PDU, CLOSE_REASON_FAILED);
return;
}
if (1 + prov_handlers[type].len != plink.rx.buf->len) {
BT_ERR("Invalid length %u for type 0x%02x", plink.rx.buf->len, type);
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
}
prov_handlers[type].func(&plink.rx.buf->data[1]);
}
static void gen_prov_cont(struct prov_rx *rx, struct net_buf_simple *buf)
{
u8_t seg = CONT_SEG_INDEX(rx->gpc);
BT_DBG("len %u, seg_index %u", buf->len, seg);
if (!plink.rx.seg && plink.rx.prev_id == rx->xact_id) {
BT_DBG("Resending ack");
gen_prov_ack_send(rx->xact_id);
return;
}
if (rx->xact_id != plink.rx.id) {
BT_WARN("Data for unknown transaction (%u != %u)", rx->xact_id, plink.rx.id);
return;
}
if (seg > plink.rx.last_seg) {
BT_ERR("Invalid segment index %u", seg);
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
} else if (seg == plink.rx.last_seg) {
u8_t expect_len;
expect_len = (plink.rx.buf->len - 20U - ((plink.rx.last_seg - 1) * 23U));
if (expect_len != buf->len) {
BT_ERR("Incorrect last seg len: %u != %u", expect_len, buf->len);
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
}
}
if (!(plink.rx.seg & BIT(seg))) {
BT_DBG("Ignoring already received segment");
return;
}
memcpy(XACT_SEG_DATA(seg), buf->data, buf->len);
XACT_SEG_RECV(seg);
if (!plink.rx.seg) {
prov_msg_recv();
}
}
static void gen_prov_ack(struct prov_rx *rx, struct net_buf_simple *buf)
{
BT_DBG("len %u", buf->len);
if (!plink.tx.buf[0]) {
return;
}
if (rx->xact_id == plink.tx.id) {
prov_clear_tx();
}
}
static void gen_prov_start(struct prov_rx *rx, struct net_buf_simple *buf)
{
if (plink.rx.seg) {
BT_WARN("Got Start while there are unreceived segments");
return;
}
if (plink.rx.prev_id == rx->xact_id) {
BT_DBG("Resending ack");
gen_prov_ack_send(rx->xact_id);
return;
}
plink.rx.buf->len = net_buf_simple_pull_be16(buf);
plink.rx.id = rx->xact_id;
plink.rx.fcs = net_buf_simple_pull_u8(buf);
BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len, START_LAST_SEG(rx->gpc), plink.rx.buf->len,
plink.rx.fcs);
if (plink.rx.buf->len < 1) {
BT_ERR("Ignoring zero-length provisioning PDU");
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
}
if (plink.rx.buf->len > plink.rx.buf->size) {
BT_ERR("Too large provisioning PDU (%u bytes)", plink.rx.buf->len);
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
}
if (START_LAST_SEG(rx->gpc) > 0 && plink.rx.buf->len <= 20) {
BT_ERR("Too small total length for multi-segment PDU");
close_link(PROV_ERR_NVAL_FMT, CLOSE_REASON_FAILED);
return;
}
plink.rx.seg = (1 << (START_LAST_SEG(rx->gpc) + 1)) - 1;
plink.rx.last_seg = START_LAST_SEG(rx->gpc);
memcpy(plink.rx.buf->data, buf->data, buf->len);
XACT_SEG_RECV(0);
if (!plink.rx.seg) {
prov_msg_recv();
}
}
static const struct {
void (*func)(struct prov_rx *rx, struct net_buf_simple *buf);
bool require_link;
u8_t min_len;
} gen_prov[] = {
{ gen_prov_start, true, 3 },
{ gen_prov_ack, true, 0 },
{ gen_prov_cont, true, 0 },
{ gen_prov_ctl, false, 0 },
};
static void gen_prov_recv(struct prov_rx *rx, struct net_buf_simple *buf)
{
if (buf->len < gen_prov[GPCF(rx->gpc)].min_len) {
BT_ERR("Too short GPC message type %u", GPCF(rx->gpc));
return;
}
if (!atomic_test_bit(plink.flags, LINK_ACTIVE) && gen_prov[GPCF(rx->gpc)].require_link) {
BT_DBG("Ignoring message that requires active plink");
return;
}
gen_prov[GPCF(rx->gpc)].func(rx, buf);
}
void bt_mesh_pb_adv_recv(struct net_buf_simple *buf)
{
struct prov_rx rx;
if (!bt_prov_active() && bt_mesh_is_provisioned()) {
BT_DBG("Ignoring provisioning PDU - already provisioned");
return;
}
if (buf->len < 6) {
BT_WARN("Too short provisioning packet (len %u)", buf->len);
return;
}
rx.link_id = net_buf_simple_pull_be32(buf);
rx.xact_id = net_buf_simple_pull_u8(buf);
rx.gpc = net_buf_simple_pull_u8(buf);
BT_DBG("link_id 0x%08x xact_id %u", rx.link_id, rx.xact_id);
if (atomic_test_bit(plink.flags, LINK_ACTIVE) && plink.id != rx.link_id) {
BT_DBG("Ignoring mesh beacon for unknown plink");
return;
}
gen_prov_recv(&rx, buf);
}
#endif /* CONFIG_BT_MESH_PB_ADV */
#if defined(CONFIG_BT_MESH_PB_GATT)
int bt_mesh_pb_gatt_recv(struct bt_conn *conn, struct net_buf_simple *buf)
{
u8_t type;
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (plink.conn != conn) {
BT_WARN("Data for unexpected connection");
return -ENOTCONN;
}
if (buf->len < 1) {
BT_WARN("Too short provisioning packet (len %u)", buf->len);
return -EINVAL;
}
type = net_buf_simple_pull_u8(buf);
if (type != PROV_FAILED && type != plink.expect) {
BT_WARN("Unexpected msg 0x%02x != 0x%02x", type, plink.expect);
prov_send_fail_msg(PROV_ERR_UNEXP_PDU);
plink.expect = 0xFF;
return -EINVAL;
}
if (type >= ARRAY_SIZE(prov_handlers)) {
BT_ERR("Unknown provisioning PDU type 0x%02x", type);
return -EINVAL;
}
if (prov_handlers[type].len != buf->len) {
BT_ERR("Invalid length %u for type 0x%02x", buf->len, type);
return -EINVAL;
}
prov_handlers[type].func(buf->data);
return 0;
}
int bt_mesh_pb_gatt_open(struct bt_conn *conn)
{
BT_DBG("conn %p", conn);
if (atomic_test_and_set_bit(plink.flags, LINK_ACTIVE)) {
return -EBUSY;
}
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_start(&g_prov_timeout, PROV_TIMEOUT);
#endif
plink.conn = bt_conn_ref(conn);
plink.expect = PROV_INVITE;
if (prov->link_open) {
prov->link_open(BT_MESH_PROV_GATT);
}
return 0;
}
int bt_mesh_pb_gatt_close(struct bt_conn *conn)
{
BT_DBG("conn %p", conn);
if (plink.conn != conn) {
BT_ERR("Not connected");
return -ENOTCONN;
}
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_stop(&g_prov_timeout);
#endif
if (prov->link_close) {
prov->link_close(BT_MESH_PROV_GATT);
}
reset_state();
return 0;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
const struct bt_mesh_prov *bt_mesh_prov_get(void)
{
return prov;
}
bool bt_prov_active(void)
{
return atomic_test_bit(plink.flags, LINK_ACTIVE);
}
#if CONFIG_BT_MESH_PROV_TIMEOUT
static void prov_timeout(void *timer, void *arg)
{
reset_link();
}
#endif
int bt_mesh_prov_init(const struct bt_mesh_prov *prov_info)
{
static struct bt_pub_key_cb pub_key_cb = {
.func = pub_key_ready,
};
int err;
if (!prov_info) {
BT_ERR("No provisioning context provided");
return -EINVAL;
}
err = bt_pub_key_gen(&pub_key_cb);
if (err) {
BT_ERR("Failed to generate public key (%d)", err);
return err;
}
prov = prov_info;
#if defined(CONFIG_BT_MESH_PB_ADV)
k_delayed_work_init(&plink.tx.retransmit, prov_retransmit);
#endif
#if CONFIG_BT_MESH_PROV_TIMEOUT
k_timer_init(&g_prov_timeout, prov_timeout, NULL);
#endif
reset_state();
return 0;
}
void bt_mesh_prov_complete(u16_t net_idx, u16_t addr)
{
if (prov->complete) {
prov->complete(net_idx, addr);
}
}
void bt_mesh_prov_reset(void)
{
if (prov->reset) {
prov->reset();
}
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/prov.c | C | apache-2.0 | 42,968 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// #include <bt_errno.h>
// #include <string.h>
#include <ble_os.h>
#include <api/mesh.h>
#ifdef CONFIG_BT_MESH_PROVISIONER
#include <bt_errno.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/conn.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_BEACON)
#include "common/log.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "prov.h"
//#include "crypto.h"
#include "beacon.h"
#include "foundation.h"
#include "provisioner_prov.h"
//#include "bt_mesh_custom_log.h"
static void provisioner_secure_beacon_recv(struct net_buf_simple *buf)
{
// TODO: Provisioner receive and handle Secure Beacon
}
void provisioner_beacon_recv(struct net_buf_simple *buf)
{
u8_t type;
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (buf->len < 1) {
BT_ERR("Too short beacon");
return;
}
type = net_buf_simple_pull_u8(buf);
switch (type) {
case BEACON_TYPE_UNPROVISIONED:
BT_DBG("Unprovisioned device beacon received");
provisioner_unprov_beacon_recv(buf);
break;
case BEACON_TYPE_SECURE:
provisioner_secure_beacon_recv(buf);
break;
default:
BT_WARN("Unknown beacon type 0x%02x", type);
break;
}
}
#endif /* CONFIG_BT_MESH_PROVISIONER */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/provisioner_beacon.c | C | apache-2.0 | 1,970 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ble_os.h>
#include <bt_errno.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <api/mesh.h>
#include <bluetooth/conn.h>
#include <aos/ble.h>
#ifdef CONFIG_BT_MESH_PROVISIONER
#ifndef CONFIG_BT_CENTRAL
#error "Provisioner need BT Central"
#endif
#include "mesh.h"
#include "api/mesh/main.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROV)
#include "common/log.h"
#include "crypto.h"
#include "adv.h"
#include "net.h"
#include "access.h"
#include "provisioner_prov.h"
#include "provisioner_proxy.h"
#include "provisioner_main.h"
#include <settings.h>
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
#define NODE_COMP_DATA_MIN_LEN 14
#define BEACON_STATE BIT(0)
#define DEFAULT_TTL_STATE BIT(1)
#define GATT_PROXY_STATE BIT(2)
#define RELAY_STATE BIT(3)
#define NODE_IDENTITY_STATE BIT(4)
#define FRIEND_STATE BIT(5)
#define NET_TRANSMIT_STATE BIT(6)
#define HEARTBEAT_PUB_STATE BIT(7)
#define HEARTBEAT_SUB_STATE BIT(8)
static const struct bt_mesh_prov *prov;
static const struct bt_mesh_provisioner *provisioner;
static const struct bt_mesh_comp *comp;
static struct bt_mesh_node_t mesh_nodes[CONFIG_BT_MESH_MAX_STORED_NODES];
static bt_u32_t mesh_node_count;
static bool prov_upper_init = false;
extern struct net_buf_pool provisioner_buf_pool;
static inline u8_t get_u8(const u8_t **src)
{
return (u8_t) * ((*src)++);
}
static inline u16_t get_le16(const u8_t **src)
{
u16_t val = sys_get_le16(*src);
*src += 2;
return val;
}
static int provisioner_index_check(int node_index)
{
struct bt_mesh_node_t *node = NULL;
BT_DBG("%s", __func__);
if (node_index < 0) {
BT_ERR("%s: node_index < 0", __func__);
return -EINVAL;
}
if (node_index >= ARRAY_SIZE(mesh_nodes)) {
BT_ERR("%s: Too big node_index", __func__);
return -EINVAL;
}
node = &mesh_nodes[node_index];
if (node->node_active != true) {
BT_ERR("%s: node not found", __func__);
return -EINVAL;
}
return 0;
}
bool provisioner_is_node_provisioned(const u8_t *dev_addr)
{
int i;
struct bt_mesh_node_t *node = NULL;
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (!node->node_active || !BT_MESH_ADDR_IS_UNICAST(node->unicast_addr)) {
continue;
}
if (!memcmp(dev_addr, node->addr_val, 6)) {
return true;
}
}
return false;
}
int provisioner_node_provision(int node_index, const u8_t uuid[16], u16_t oob_info, u16_t unicast_addr,
u8_t element_num, u16_t net_idx, u8_t flags, bt_u32_t iv_index, const u8_t dev_key[16],
u8_t *dev_addr)
{
struct bt_mesh_node_t *node = NULL;
BT_DBG("%s", __func__);
if (mesh_node_count >= ARRAY_SIZE(mesh_nodes)) {
BT_ERR("Provisioner mesh node queue is full");
return -ENOMEM;
}
if (node_index >= ARRAY_SIZE(mesh_nodes) || !uuid || !dev_key) {
BT_ERR("Argument is invalid");
return -EINVAL;
}
#if 0
node = osi_calloc(sizeof(struct bt_mesh_node_t));
if (!node) {
BT_ERR("Provisioner allocate memory for node fail");
return -ENOMEM;
}
#endif
node = &mesh_nodes[node_index];
BT_DBG("node_index: 0x%x, unicast_addr: 0x%x, element_num: 0x%x, net_idx: 0x%x", node_index, unicast_addr,
element_num, net_idx);
BT_DBG("dev_uuid: %s", bt_hex(uuid, 16));
BT_DBG("dev_key: %s", bt_hex(dev_key, 16));
memcpy(node->dev_uuid, uuid, 16);
node->oob_info = oob_info;
node->unicast_addr = unicast_addr;
node->element_num = element_num;
node->net_idx = net_idx;
node->flags = flags;
node->iv_index = iv_index;
memcpy(node->dev_key, dev_key, 16);
memcpy(node->addr_val, dev_addr, 6);
node->node_active = true;
mesh_node_count++;
return 0;
}
int provisioner_node_reset(int node_index)
{
struct bt_mesh_node_t *node = NULL;
BT_DBG("%s: reset node %d", __func__, node_index);
if (!mesh_node_count) {
BT_ERR("%s: mesh_nodes is empty", __func__);
return -ENODEV;
}
if (provisioner_index_check(node_index)) {
BT_ERR("%s: check node_index fail", __func__);
return -EINVAL;
}
node = &mesh_nodes[node_index];
/* Reset corresponding rpl when reset the node */
extern void bt_mesh_rpl_clear_node(uint16_t unicast_addr, uint8_t elem_num);
bt_mesh_rpl_clear_node(node->unicast_addr, node->element_num);
#if 0
osi_free(mesh_nodes[node_index]);
mesh_nodes[node_index] = NULL;
#endif
node->node_active = false;
mesh_node_count--;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
bt_mesh_model_evt_t evt_data;
evt_data.source_addr = mesh_nodes[node_index].unicast_addr;
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_NODE_RESET_STATUS, &evt_data);
}
#endif
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_mesh_node(node_index);
}
return 0;
}
int provisioner_upper_reset_all_nodes(void)
{
int i, err;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
err = provisioner_node_reset(i);
if (err == -ENODEV) {
return 0;
}
}
return 0;
}
/** For Provisioner, we use the same data structure
* (like, struct bt_mesh_subnet, etc.) for netkey
* & appkey because if not we need to change a lot
* of APIs.
*/
int provisioner_upper_init(void)
{
struct bt_mesh_subnet *sub = NULL;
u8_t p_key[16] = { 0 };
BT_DBG("%s", __func__);
if (prov_upper_init) {
return 0;
}
comp = bt_mesh_comp_get();
if (!comp) {
BT_ERR("%s: Provisioner comp is NULL", __func__);
return -EINVAL;
}
provisioner = provisioner_get_prov_info();
if (!provisioner) {
BT_ERR("%s: Provisioner context is NULL", __func__);
return -EINVAL;
}
/* If the device only acts as a Provisioner, need to initialize
each element's address. */
//bt_mesh_comp_provision(provisioner->prov_unicast_addr);
/* Generate the primary netkey */
if (bt_rand(p_key, 16)) {
BT_ERR("%s: create primary netkey fail", __func__);
return -EIO;
}
#if 0
sub = osi_calloc(sizeof(struct bt_mesh_subnet));
if (!sub) {
BT_ERR("%s: allocate memory fail", __func__);
return -ENOMEM;
}
#endif
sub = &(bt_mesh.sub[0]);
if (sub->subnet_active == false) {
sub->kr_flag = BT_MESH_KEY_REFRESH(provisioner->flags);
if (sub->kr_flag) {
if (bt_mesh_net_keys_create(&sub->keys[1], p_key)) {
BT_ERR("%s: create net_keys fail", __func__);
//osi_free(sub);
sub->subnet_active = false;
return -EIO;
}
sub->kr_phase = BT_MESH_KR_PHASE_2;
} else {
/* Currently provisioner only use keys[0] */
if (bt_mesh_net_keys_create(&sub->keys[0], p_key)) {
BT_ERR("%s: create net_keys fail", __func__);
//osi_free(sub);
sub->subnet_active = false;
return -EIO;
}
sub->kr_phase = BT_MESH_KR_NORMAL;
}
sub->net_idx = BT_MESH_KEY_PRIMARY;
sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
sub->subnet_active = true;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_subnet(sub, 0);
}
}
/* Dynamically added appkey & netkey will use these key_idx */
bt_mesh.p_app_idx_next = 0x0000;
bt_mesh.p_net_idx_next = 0x0001;
/* In this function, we use the values of struct bt_mesh_prov
which has been initialized in the application layer */
bt_mesh.iv_index = provisioner->iv_index;
bt_mesh.iv_update = BT_MESH_IV_UPDATE(provisioner->flags);
/* Set initial IV Update procedure state time-stamp */
bt_mesh.last_update = k_uptime_get();
prov_upper_init = true;
BT_DBG("kr_flag: %d, kr_phase: %d, net_idx: 0x%02x, node_id %d", sub->kr_flag, sub->kr_phase, sub->net_idx,
sub->node_id);
BT_DBG("netkey: %s, nid: 0x%x", bt_hex(sub->keys[0].net, 16), sub->keys[0].nid);
BT_DBG("enckey: %s", bt_hex(sub->keys[0].enc, 16));
BT_DBG("network id: %s", bt_hex(sub->keys[0].net_id, 8));
#if defined(CONFIG_BT_MESH_GATT_PROXY)
BT_DBG("identity: %s", bt_hex(sub->keys[0].identity, 16));
#endif
BT_DBG("privacy: %s", bt_hex(sub->keys[0].privacy, 16));
BT_DBG("beacon: %s", bt_hex(sub->keys[0].beacon, 16));
return 0;
}
/* The following APIs are for provisioner upper layers internal use */
const u8_t *provisioner_net_key_get(u16_t net_idx)
{
struct bt_mesh_subnet *sub = NULL;
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (!sub->subnet_active || (sub->net_idx != net_idx)) {
BT_DBG("CONTINUE: %u, %u, %u", sub->subnet_active, sub->net_idx, net_idx);
continue;
}
if (sub->kr_flag) {
BT_DBG("return kr_flag: %u", sub->kr_flag);
return sub->keys[1].net;
}
BT_DBG("return netkey: %02x, %02x, %02x, %02x", sub->keys[0].net[0], sub->keys[0].net[1], sub->keys[0].net[2],
sub->keys[0].net[3]);
return sub->keys[0].net;
}
BT_DBG("return netkey NULL");
return NULL;
}
bool provisioner_check_msg_dst_addr(u16_t dst_addr)
{
struct bt_mesh_node_t *node = NULL;
int i;
BT_DBG("%s", __func__);
if (!BT_MESH_ADDR_IS_UNICAST(dst_addr)) {
return true;
}
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (node->node_active && dst_addr >= node->unicast_addr && dst_addr < node->unicast_addr + node->element_num) {
return true;
}
}
return false;
}
const u8_t *provisioner_get_device_key(u16_t dst_addr)
{
/* Device key is only used to encrypt configuration messages.
* Configuration model shall only be supported by the primary
* element which uses the primary unicast address.
*/
struct bt_mesh_node_t *node = NULL;
int i;
BT_DBG("%s", __func__);
if (!BT_MESH_ADDR_IS_UNICAST(dst_addr)) {
BT_ERR("%s: dst_addr is not unicast", __func__);
return NULL;
}
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (node->node_active && node->unicast_addr == dst_addr) {
return node->dev_key;
}
}
return NULL;
}
struct bt_mesh_app_key *provisioner_app_key_find(u16_t app_idx)
{
struct bt_mesh_app_key *key = NULL;
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (!key->appkey_active) {
continue;
}
if (key->net_idx != BT_MESH_KEY_UNUSED && key->app_idx == app_idx) {
return key;
}
}
return NULL;
}
bt_u32_t provisioner_get_prov_node_count(void)
{
return mesh_node_count;
}
/* The following APIs are for provisioner application use */
#if 0
static int bt_mesh_provisioner_set_kr_flag(u16_t net_idx, bool kr_flag)
{
struct bt_mesh_subnet *sub = NULL;
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
sub = bt_mesh.p_sub[i];
if (!sub || (sub->net_idx != net_idx)) {
continue;
}
sub->kr_flag = kr_flag;
break;
}
if (i == ARRAY_SIZE(bt_mesh.p_sub)) {
return -ENODEV;
}
/* TODO: When kr_flag is changed, provisioner may need
* to change the netkey of the subnet and update
* corresponding appkey.
*/
return 0;
}
static void bt_mesh_provisioner_set_iv_index(bt_u32_t iv_index)
{
bt_mesh.iv_index = iv_index;
/* TODO: When iv_index is changed, provisioner may need to
* start iv update procedure. And the ivu_initiator
* & iv_update flags may also need to be set.
*/
}
#endif
int bt_mesh_provisioner_store_node_info(struct bt_mesh_node_t *node_info)
{
struct bt_mesh_node_t *node = NULL;
int i;
if (!node_info) {
BT_ERR("%s: node_info is NULL", __func__);
return -EINVAL;
}
/* Check if the device uuid already exists */
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (node->node_active && !memcmp(node->dev_uuid, node_info->dev_uuid, 16)) {
BT_WARN("%s: node_info already exists", __func__);
return -EEXIST;
}
}
/* 0 ~ (CONFIG_BT_MESH_MAX_PROV_NODES-1) are left for self-provisioned nodes */
for (i = CONFIG_BT_MESH_MAX_PROV_NODES; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (!node->node_active) {
#if 0
node = osi_calloc(sizeof(struct bt_mesh_node_t));
if (!node) {
BT_ERR("%s: allocate memory fail", __func__);
return -ENOMEM;
}
#endif
memcpy(node, node_info, sizeof(struct bt_mesh_node_t));
#if 0
mesh_nodes[i] = node;
#endif
node->node_active = true;
mesh_node_count++;
return 0;
}
}
BT_ERR("%s: node_info is full", __func__);
return -ENOMEM;
}
int bt_mesh_provisioner_get_all_node_unicast_addr(struct net_buf_simple *buf)
{
struct bt_mesh_node_t *node = NULL;
int i;
if (!buf) {
BT_ERR("%s: buf is NULL", __func__);
return -EINVAL;
}
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (!node->node_active || !BT_MESH_ADDR_IS_UNICAST(node->unicast_addr)) {
continue;
}
net_buf_simple_add_le16(buf, node->unicast_addr);
}
return 0;
}
int bt_mesh_provisioner_set_node_name(int node_index, const char *name)
{
size_t length, name_len;
int i;
BT_DBG("%s", __func__);
if (!name) {
BT_ERR("%s: input name is NULL", __func__);
return -EINVAL;
}
if (provisioner_index_check(node_index)) {
BT_ERR("%s: check node_index fail", __func__);
return -EINVAL;
}
BT_DBG("name len is %d, name is %s", strlen(name), name);
length = (strlen(name) <= MESH_NAME_SIZE) ? strlen(name) : MESH_NAME_SIZE;
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
if (!mesh_nodes[i].node_active) {
continue;
}
name_len = strlen(mesh_nodes[i].node_name);
if (length != name_len) {
continue;
}
if (!strncmp(mesh_nodes[i].node_name, name, length)) {
BT_WARN("%s: name already exists", __func__);
return -EEXIST;
}
}
strncpy(mesh_nodes[node_index].node_name, name, length);
return 0;
}
const char *bt_mesh_provisioner_get_node_name(int node_index)
{
BT_DBG("%s", __func__);
if (provisioner_index_check(node_index)) {
BT_ERR("%s: check node_index fail", __func__);
return NULL;
}
return mesh_nodes[node_index].node_name;
}
int bt_mesh_provisioner_get_node_index(const char *name)
{
size_t length, name_len;
int i;
BT_DBG("%s", __func__);
if (!name) {
return -EINVAL;
}
length = (strlen(name) <= MESH_NAME_SIZE) ? strlen(name) : MESH_NAME_SIZE;
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
if (!mesh_nodes[i].node_active) {
continue;
}
name_len = strlen(mesh_nodes[i].node_name);
if (length != name_len) {
continue;
}
if (!strncmp(mesh_nodes[i].node_name, name, length)) {
return i;
}
}
return -ENODEV;
}
struct bt_mesh_node_t *bt_mesh_provisioner_get_node_info_by_id(int node_index)
{
if (provisioner_index_check(node_index)) {
BT_ERR("%s: check node_index fail", __func__);
return NULL;
}
return &mesh_nodes[node_index];
}
struct bt_mesh_node_t *bt_mesh_provisioner_get_node_info(u16_t unicast_addr)
{
struct bt_mesh_node_t *node = NULL;
int i;
BT_DBG("%s", __func__);
if (!BT_MESH_ADDR_IS_UNICAST(unicast_addr)) {
BT_ERR("%s: not a unicast address", __func__);
return NULL;
}
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
node = &mesh_nodes[i];
if (!node->node_active) {
continue;
}
if (unicast_addr >= node->unicast_addr && unicast_addr < (node->unicast_addr + node->element_num)) {
return node;
}
}
return NULL;
}
bt_u32_t bt_mesh_provisioner_get_net_key_count(void)
{
return ARRAY_SIZE(bt_mesh.sub);
}
bt_u32_t bt_mesh_provisioner_get_app_key_count(void)
{
return ARRAY_SIZE(bt_mesh.app_keys);
}
static int provisioner_check_app_key(const u8_t app_key[16], u16_t *app_idx)
{
struct bt_mesh_app_key *key = NULL;
int i;
if (!app_key) {
return 0;
}
/* Check if app_key is already existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && (!memcmp(key->keys[0].val, app_key, 16) || !memcmp(key->keys[1].val, app_key, 16))) {
*app_idx = key->app_idx;
return -EEXIST;
}
}
return 0;
}
static int provisioner_check_app_idx(u16_t app_idx, bool exist)
{
struct bt_mesh_app_key *key = NULL;
int i;
if (exist) {
/* Check if app_idx is already existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && (key->app_idx == app_idx)) {
return -EEXIST;
}
}
return 0;
}
/* Check if app_idx is not existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && (key->app_idx == app_idx)) {
return 0;
}
}
return -ENODEV;
}
static int provisioner_check_app_key_full(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
if (!bt_mesh.app_keys[i].appkey_active) {
return i;
}
}
return -ENOMEM;
}
static int provisioner_check_net_key(const u8_t net_key[16], u16_t *net_idx)
{
struct bt_mesh_subnet *sub = NULL;
int i;
if (!net_key) {
return 0;
}
/* Check if net_key is already existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && (!memcmp(sub->keys[0].net, net_key, 16) || !memcmp(sub->keys[1].net, net_key, 16))) {
*net_idx = sub->net_idx;
return -EEXIST;
}
}
return 0;
}
static int provisioner_check_net_idx(u16_t net_idx, bool exist)
{
struct bt_mesh_subnet *sub = NULL;
int i;
if (exist) {
/* Check if net_idx is already existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && (sub->net_idx == net_idx)) {
return -EEXIST;
}
}
return 0;
}
/* Check if net_idx is not existed */
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && (sub->net_idx == net_idx)) {
return 0;
}
}
return -ENODEV;
}
static int provisioner_check_net_key_full(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (!bt_mesh.sub[i].subnet_active) {
return i;
}
}
return -ENOMEM;
}
struct bt_mesh_app_key *bt_mesh_provisioner_p_app_key_alloc()
{
struct bt_mesh_app_key *key = NULL;
int add = -1;
add = provisioner_check_app_key_full();
if (add < 0) {
BT_ERR("%s: app_key full", __func__);
return NULL;
}
key = &(bt_mesh.app_keys[add]);
return key;
}
int bt_mesh_provisioner_local_app_key_add(const u8_t app_key[16], u16_t net_idx, u16_t *app_idx)
{
struct bt_mesh_app_key *key = NULL;
struct bt_mesh_app_keys *keys = NULL;
u8_t p_key[16] = { 0 };
int add = -1;
if (bt_mesh.p_app_idx_next >= 0x1000) {
BT_ERR("%s: no app_idx available", __func__);
return -EIO;
}
if (!app_idx || (*app_idx != 0xFFFF && *app_idx >= 0x1000)) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
/* Check if the same application key already exists */
if (provisioner_check_app_key(app_key, app_idx)) {
BT_WARN("%s: app_key already exists, app_idx updated", __func__);
return 0;
}
/* Check if the net_idx exists */
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return -ENODEV;
}
/* Check if the same app_idx already exists */
if (provisioner_check_app_idx(*app_idx, true)) {
BT_ERR("%s: app_idx already exists", __func__);
return -EEXIST;
}
add = provisioner_check_app_key_full();
if (add < 0) {
BT_ERR("%s: app_key full", __func__);
return -ENOMEM;
}
if (!app_key) {
if (bt_rand(p_key, 16)) {
BT_ERR("%s: generate app_key fail", __func__);
return -EIO;
}
} else {
memcpy(p_key, app_key, 16);
}
key = &(bt_mesh.app_keys[add]);
keys = &key->keys[0];
if (bt_mesh_app_id(p_key, &keys->id)) {
BT_ERR("%s: generate aid fail", __func__);
key->appkey_active = false;
return -EIO;
}
memcpy(keys->val, p_key, 16);
key->net_idx = net_idx;
if (*app_idx != 0xFFFF) {
key->app_idx = *app_idx;
} else {
key->app_idx = bt_mesh.p_app_idx_next;
while (1) {
if (provisioner_check_app_idx(key->app_idx, true)) {
key->app_idx = (++bt_mesh.p_app_idx_next);
if (key->app_idx >= 0x1000) {
BT_ERR("%s: no app_idx available for key", __func__);
//osi_free(key);
key->appkey_active = false;
return -EIO;
}
} else {
break;
}
}
*app_idx = key->app_idx;
}
key->updated = false;
key->appkey_active = true;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
BT_DBG("Storing AppKey persistently");
bt_mesh_store_app_key(key, 0);
}
return 0;
}
const u8_t *bt_mesh_provisioner_local_app_key_get(u16_t net_idx, u16_t app_idx)
{
struct bt_mesh_app_key *key = NULL;
int i;
BT_DBG("%s", __func__);
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return NULL;
}
if (provisioner_check_app_idx(app_idx, false)) {
BT_ERR("%s: app_idx does not exist", __func__);
return NULL;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && key->net_idx == net_idx && key->app_idx == app_idx) {
if (key->updated) {
return key->keys[1].val;
}
return key->keys[0].val;
}
}
return NULL;
}
int bt_mesh_provisioner_local_app_key_delete(u16_t net_idx, u16_t app_idx)
{
struct bt_mesh_app_key *key = NULL;
int i;
BT_DBG("%s", __func__);
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return -ENODEV;
}
if (provisioner_check_app_idx(app_idx, false)) {
BT_ERR("%s: app_idx does not exist", __func__);
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && key->net_idx == net_idx && key->app_idx == app_idx) {
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_app_key(key, 0);
}
key->appkey_active = false;
return 0;
}
}
/* Shall never reach here */
return -ENODEV;
}
int bt_mesh_provisioner_local_net_key_add(const u8_t net_key[16], u16_t *net_idx)
{
struct bt_mesh_subnet *sub = NULL;
u8_t p_key[16] = { 0 };
int add = -1;
if (bt_mesh.p_net_idx_next >= 0x1000) {
BT_ERR("%s: no net_idx available", __func__);
return -EIO;
}
if (!net_idx || (*net_idx != 0xFFFF && *net_idx >= 0x1000)) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
/* Check if the same network key already exists */
if (provisioner_check_net_key(net_key, net_idx)) {
BT_WARN("%s: net_key already exists, net_idx updated", __func__);
return -EEXIST;
}
/* Check if the same net_idx already exists */
if (provisioner_check_net_idx(*net_idx, true)) {
BT_ERR("%s: net_idx already exists", __func__);
return -EEXIST;
}
add = provisioner_check_net_key_full();
if (add < 0) {
BT_ERR("%s: net_key full", __func__);
return -ENOMEM;
}
if (!net_key) {
if (bt_rand(p_key, 16)) {
BT_ERR("%s: generate net_key fail", __func__);
return -EIO;
}
} else {
memcpy(p_key, net_key, 16);
}
#if 0
sub = osi_calloc(sizeof(struct bt_mesh_subnet));
if (!sub) {
BT_ERR("%s: allocate memory for net_key fail", __func__);
return -ENOMEM;
}
#endif
sub = &bt_mesh.sub[add];
if (bt_mesh_net_keys_create(&sub->keys[0], p_key)) {
BT_ERR("%s: generate nid fail", __func__);
//osi_free(sub);
sub->subnet_active = false;
return -EIO;
}
if (*net_idx != 0xFFFF) {
sub->net_idx = *net_idx;
} else {
sub->net_idx = bt_mesh.p_net_idx_next;
while (1) {
if (provisioner_check_net_idx(sub->net_idx, true)) {
sub->net_idx = (++bt_mesh.p_net_idx_next);
if (sub->net_idx >= 0x1000) {
BT_ERR("%s: no net_idx available for sub", __func__);
//osi_free(sub);
sub->subnet_active = false;
return -EIO;
}
} else {
break;
}
}
*net_idx = sub->net_idx;
}
sub->kr_phase = BT_MESH_KR_NORMAL;
sub->kr_flag = false;
sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
sub->subnet_active = true;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_subnet(sub, 0);
}
return 0;
}
const u8_t *bt_mesh_provisioner_local_net_key_get(u16_t net_idx)
{
struct bt_mesh_subnet *sub = NULL;
int i;
BT_DBG("%s", __func__);
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return NULL;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && sub->net_idx == net_idx) {
if (sub->kr_flag) {
return sub->keys[1].net;
}
return sub->keys[0].net;
}
}
return NULL;
}
int bt_mesh_provisioner_local_net_key_delete(u16_t net_idx)
{
struct bt_mesh_subnet *sub = NULL;
int i;
BT_DBG("%s", __func__);
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && sub->net_idx == net_idx) {
sub->subnet_active = false;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_subnet(sub, 0);
}
return 0;
}
}
/* Shall never reach here */
return -ENODEV;
}
int bt_mesh_provisioner_get_own_unicast_addr(u16_t *addr, u8_t *elem_num)
{
if (!addr || !elem_num || !prov || !comp) {
BT_ERR("%s: parameter is NULL", __func__);
return -EINVAL;
}
*addr = provisioner->prov_unicast_addr;
*elem_num = comp->elem_count;
return 0;
}
int bt_mesh_provisioner_unbind_local_model_app_idx(u16_t elem_addr, u16_t mod_id, u16_t cid, u16_t app_idx)
{
struct bt_mesh_elem *elem = NULL;
struct bt_mesh_model *model = NULL;
int i;
if (!comp) {
BT_ERR("%s: comp is NULL", __func__);
return -EINVAL;
}
for (i = 0; i < comp->elem_count; i++) {
elem = &comp->elem[i];
if (elem->addr == elem_addr) {
break;
}
}
if (i == comp->elem_count) {
BT_ERR("%s: no element found", __func__);
return -ENODEV;
}
if (cid == 0xFFFF) {
model = bt_mesh_model_find(elem, mod_id);
} else {
model = bt_mesh_model_find_vnd(elem, cid, mod_id);
}
if (!model) {
BT_ERR("%s: no model found", __func__);
return -ENODEV;
}
if (provisioner_check_app_idx(app_idx, false)) {
BT_ERR("%s: app_idx does not exist", __func__);
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
if (model->keys[i] == app_idx) {
model->keys[i] = BT_MESH_KEY_UNUSED;
return 0;
}
}
BT_DBG("%s:the appkey has not been bound to model", __func__);
return 0;
}
int bt_mesh_provisioner_bind_local_model_app_idx(u16_t elem_addr, u16_t mod_id, u16_t cid, u16_t app_idx)
{
struct bt_mesh_elem *elem = NULL;
struct bt_mesh_model *model = NULL;
int i;
if (!comp) {
BT_ERR("%s: comp is NULL", __func__);
return -EINVAL;
}
for (i = 0; i < comp->elem_count; i++) {
elem = &comp->elem[i];
if (elem->addr == elem_addr) {
break;
}
}
if (i == comp->elem_count) {
BT_ERR("%s: no element found", __func__);
return -ENODEV;
}
if (cid == 0xFFFF) {
model = bt_mesh_model_find(elem, mod_id);
} else {
model = bt_mesh_model_find_vnd(elem, cid, mod_id);
}
if (!model) {
BT_ERR("%s: no model found", __func__);
return -ENODEV;
}
if (provisioner_check_app_idx(app_idx, false)) {
BT_ERR("%s: app_idx does not exist", __func__);
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
if (model->keys[i] == app_idx) {
BT_WARN("%s: app_idx already bind with model", __func__);
return 0;
}
}
for (i = 0; i < ARRAY_SIZE(model->keys); i++) {
if (model->keys[i] == BT_MESH_KEY_UNUSED) {
model->keys[i] = app_idx;
return 0;
}
}
BT_ERR("%s: model->keys is full", __func__);
return -ENOMEM;
}
int bt_mesh_provisioner_bind_local_app_net_idx(u16_t net_idx, u16_t app_idx)
{
struct bt_mesh_app_key *key = NULL;
int i;
BT_DBG("%s", __func__);
if (provisioner_check_net_idx(net_idx, false)) {
BT_ERR("%s: net_idx does not exist", __func__);
return -ENODEV;
}
if (provisioner_check_app_idx(app_idx, false)) {
BT_ERR("%s: app_idx does not exist", __func__);
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (!key->appkey_active || (key->app_idx != app_idx)) {
continue;
}
key->net_idx = net_idx;
return 0;
}
return -ENODEV;
}
int bt_mesh_provisioner_print_local_element_info(void)
{
struct bt_mesh_elem *elem = NULL;
struct bt_mesh_model *model = NULL;
int i, j;
if (!comp) {
BT_ERR("%s: comp is NULL", __func__);
return -EINVAL;
}
BT_WARN("************************************************");
BT_WARN("* cid: 0x%04x pid: 0x%04x vid: 0x%04x *", comp->cid, comp->pid, comp->vid);
BT_WARN("* Element Number: 0x%02x *", comp->elem_count);
for (i = 0; i < comp->elem_count; i++) {
elem = &comp->elem[i];
BT_WARN("* Element %d: 0x%04x *", i, elem->addr);
BT_WARN("* Loc: 0x%04x NumS: 0x%02x NumV: 0x%02x *", elem->loc, elem->model_count,
elem->vnd_model_count);
for (j = 0; j < elem->model_count; j++) {
model = &elem->models[j];
BT_WARN("* sig_model %d: id - 0x%04x *", j, model->id);
}
for (j = 0; j < elem->vnd_model_count; j++) {
model = &elem->vnd_models[j];
BT_WARN("* vnd_model %d: id - 0x%04x, cid - 0x%04x *", j, model->vnd.id, model->vnd.company);
}
}
BT_WARN("************************************************");
(void)model;
return 0;
}
int bt_mesh_provisioner_print_node_info(void)
{
int i;
BT_WARN("************************************************");
BT_WARN("* Provisioned Node info *");
for (i = 0; i < ARRAY_SIZE(mesh_nodes); i++) {
struct bt_mesh_node_t *node = &mesh_nodes[i];
if (!node->node_active || !BT_MESH_ADDR_IS_UNICAST(node->unicast_addr)) {
continue;
}
BT_WARN("* Node [%d]: %s", i, node->node_name);
BT_WARN("* UUID : %s", bt_hex(node->dev_uuid, 16));
BT_WARN("* Addr: %02X:%02X:%02X:%02X:%02X:%02X (%s)", node->addr_val[5], node->addr_val[4], node->addr_val[3],
node->addr_val[2], node->addr_val[1], node->addr_val[0], node->addr_type == 0 ? "Public" : "random");
BT_WARN("* Unicast Addr: %04x ELEM Nums: %02x Net ID %04x", node->unicast_addr, node->element_num,
node->net_idx);
BT_WARN("* Device key: %s", bt_hex(node->dev_key, 16));
}
BT_WARN("************************************************");
return 0;
}
/* The following APIs are for temporary provisioner use */
int bt_mesh_temp_prov_net_idx_set(const u8_t net_key[16], u16_t *net_idx, u8_t *status)
{
struct bt_mesh_subnet *sub = NULL;
struct bt_mesh_subnet_keys *key = NULL;
const u8_t *keys = NULL;
u8_t kr_flag = 0;
int i, err = 0;
if (!net_key || !net_idx || !status) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
/* Check if net_key already exists in the node subnet */
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->net_idx == *net_idx) {
kr_flag = BT_MESH_KEY_REFRESH(sub->kr_flag);
key = kr_flag ? &sub->keys[1] : &sub->keys[0];
*status = provisioner_temp_prov_set_net_idx(key->net, sub->net_idx);
return 0;
}
}
/* Check if different netkeys with the same net_idx */
while (1) {
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
sub = &bt_mesh.sub[i];
if (sub->subnet_active && sub->net_idx == *net_idx) {
*net_idx += 1;
*net_idx &= 0xFFF; /* net_idx is 12-bit */
break;
}
}
if (i == ARRAY_SIZE(bt_mesh.sub)) {
break;
}
}
bt_mesh.p_net_idx_next = *net_idx;
/* If not exist in node subnet, will be checked with provisioner p_sub
and added to p_sub if necessary */
err = bt_mesh_provisioner_local_net_key_add(net_key, net_idx);
if (err) {
*status = 0x01; /* status: fail */
return 0;
};
keys = bt_mesh_provisioner_local_net_key_get(*net_idx);
if (!keys) {
*status = 0x01; /* status: fail */
return 0;
}
*status = provisioner_temp_prov_set_net_idx(keys, *net_idx);
return 0;
}
int bt_mesh_temp_prov_app_idx_set(const u8_t app_key[16], u16_t net_idx, u16_t *app_idx, u8_t *status)
{
struct bt_mesh_app_key *key = NULL;
int i, err = 0;
if (!app_key || !app_idx || !status) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
/* Check if net_key already exists in the node subnet */
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->app_idx == *app_idx) {
*status = 0x0;
return 0;
}
}
/* Check if different netkeys with the same net_idx */
while (1) {
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
key = &bt_mesh.app_keys[i];
if (key->appkey_active && key->app_idx == *app_idx) {
*app_idx += 1;
*app_idx &= 0xFFF; /* app_idx is 12-bit */
break;
}
}
if (i == ARRAY_SIZE(bt_mesh.app_keys)) {
break;
}
}
bt_mesh.p_app_idx_next = *app_idx;
/* If not exist in node subnet, will be checked with provisioner p_app_keys
and added to p_app_keys if necessary */
err = bt_mesh_provisioner_local_app_key_add(app_key, net_idx, app_idx);
if (err) {
*status = 0x01; /* status: fail */
};
*status = 0x0;
return 0;
}
#endif /* CONFIG_BT_MESH_PROVISIONER */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/provisioner_main.c | C | apache-2.0 | 38,079 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ble_os.h>
#include <api/mesh.h>
#ifdef CONFIG_BT_MESH_PROVISIONER
#include <bt_errno.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROV)
#include "common/log.h"
//#include "mesh_def.h"
#include "mesh.h"
#include "net.h"
#include "crypto.h"
#include "adv.h"
#include "provisioner_prov.h"
#include "provisioner_proxy.h"
#include "provisioner_main.h"
#include "bluetooth/uuid.h"
#include "mesh_hal_ble.h"
#include "host/ecc.h"
#include "settings.h"
//#include "bt_mesh_custom_log.h"
#ifndef CONFIG_BT_MAX_CONN
#define CONFIG_BT_ACL_CONNECTIONS 20
#define CONFIG_BT_MAX_CONN CONFIG_BT_ACL_CONNECTIONS
#endif
/* Service data length has minus 1 type length & 2 uuid length*/
#define BT_MESH_PROV_SRV_DATA_LEN 0x12
#define BT_MESH_PROXY_SRV_DATA_LEN1 0x09
#define BT_MESH_PROXY_SRV_DATA_LEN2 0x11
/* 3 transmissions, 20ms interval */
#define PROV_XMIT_COUNT 2
#define PROV_XMIT_INT 20
#define AUTH_METHOD_NO_OOB 0x00
#define AUTH_METHOD_STATIC 0x01
#define AUTH_METHOD_OUTPUT 0x02
#define AUTH_METHOD_INPUT 0x03
#define OUTPUT_OOB_BLINK 0x00
#define OUTPUT_OOB_BEEP 0x01
#define OUTPUT_OOB_VIBRATE 0x02
#define OUTPUT_OOB_NUMBER 0x03
#define OUTPUT_OOB_STRING 0x04
#define INPUT_OOB_PUSH 0x00
#define INPUT_OOB_TWIST 0x01
#define INPUT_OOB_NUMBER 0x02
#define INPUT_OOB_STRING 0x03
#define PROV_ERR_NONE 0x00
#define PROV_ERR_NVAL_PDU 0x01
#define PROV_ERR_NVAL_FMT 0x02
#define PROV_ERR_UNEXP_PDU 0x03
#define PROV_ERR_CFM_FAILED 0x04
#define PROV_ERR_RESOURCES 0x05
#define PROV_ERR_DECRYPT 0x06
#define PROV_ERR_UNEXP_ERR 0x07
#define PROV_ERR_ADDR 0x08
#define PROV_INVITE 0x00
#define PROV_CAPABILITIES 0x01
#define PROV_START 0x02
#define PROV_PUB_KEY 0x03
#define PROV_INPUT_COMPLETE 0x04
#define PROV_CONFIRM 0x05
#define PROV_RANDOM 0x06
#define PROV_DATA 0x07
#define PROV_COMPLETE 0x08
#define PROV_FAILED 0x09
#define PROV_ALG_P256 0x00
#define GPCF(gpc) (gpc & 0x03)
#define GPC_START(last_seg) (((last_seg) << 2) | 0x00)
#define GPC_ACK 0x01
#define GPC_CONT(seg_id) (((seg_id) << 2) | 0x02)
#define GPC_CTL(op) (((op) << 2) | 0x03)
#define START_PAYLOAD_MAX 20
#define CONT_PAYLOAD_MAX 23
#define START_LAST_SEG(gpc) (gpc >> 2)
#define CONT_SEG_INDEX(gpc) (gpc >> 2)
#define BEARER_CTL(gpc) (gpc >> 2)
#define LINK_OPEN 0x00
#define LINK_ACK 0x01
#define LINK_CLOSE 0x02
#define CLOSE_REASON_SUCCESS 0x00
#define CLOSE_REASON_TIMEOUT 0x01
#define CLOSE_REASON_FAILED 0x02
#define PROV_AUTH_VAL_SIZE 0x10
#define PROV_CONF_SALT_SIZE 0x10
#define PROV_CONF_KEY_SIZE 0x10
#define PROV_DH_KEY_SIZE 0x20
#define PROV_CONFIRM_SIZE 0x10
#define PROV_PROV_SALT_SIZE 0x10
#define PROV_CONF_INPUTS_SIZE 0x91
#define CONFIG_BT_MESH_UNPROV_DEV_ADD 10
static inline int prov_get_pb_index(void);
static uint32_t g_restore_max_mac = 0;
int bt_mesh_prov_output_data(u8_t *num, u8_t size, bool num_flag);
int bt_mesh_prov_input_data(u8_t *num, u8_t size, bool num_flag);
#define XACT_SEG_DATA(_seg) (&link[prov_get_pb_index()].rx.buf->data[20 + ((_seg - 1) * 23)])
#define XACT_SEG_RECV(_seg) (link[prov_get_pb_index()].rx.seg &= ~(1 << (_seg)))
#define XACT_NVAL 0xff
enum {
REMOTE_PUB_KEY, /* Remote key has been received */
LOCAL_PUB_KEY, /* Local public key is available */
LINK_ACTIVE, /* Link has been opened */
HAVE_DHKEY, /* DHKey has been calcualted */
SEND_CONFIRM, /* Waiting to send Confirm value */
WAIT_NUMBER, /* Waiting for number input from user */
WAIT_STRING, /* Waiting for string input from user */
TIMEOUT_START, /* Provision timeout timer has started */
NUM_FLAGS,
};
/** Provisioner link structure allocation
* |--------------------------------------------------------|
* | Link(PB-ADV) | Link(PB-GATT) |
* |--------------------------------------------------------|
* |<----------------------Total Link---------------------->|
*/
struct prov_link {
ATOMIC_DEFINE(flags, NUM_FLAGS);
u8_t uuid[16]; /* check if device is being provisioned*/
u16_t oob_info; /* oob info of this device */
u8_t element_num; /* element num of device */
u8_t ki_flags; /* Key refresh flag and iv update flag */
bt_u32_t iv_index; /* IV Index */
u8_t auth_method; /* choosed authentication method */
u8_t auth_action; /* choosed authentication action */
u8_t auth_size; /* choosed authentication size */
u16_t unicast_addr; /* unicast address assigned for device */
bt_addr_le_t addr; /* Device address */
#if defined(CONFIG_BT_MESH_PB_GATT)
bool connecting; /* start connecting with device */
struct bt_conn *conn; /* GATT connection */
#endif
u8_t expect; /* Next expected PDU */
u8_t dhkey[32]; /* Calculated DHKey */
u8_t auth[16]; /* Authentication Value */
u8_t conf_salt[16]; /* ConfirmationSalt */
u8_t conf_key[16]; /* ConfirmationKey */
u8_t conf_inputs[145]; /* ConfirmationInputs */
u8_t rand[16]; /* Local Random */
u8_t conf[16]; /* Remote Confirmation */
u8_t prov_salt[16]; /* Provisioning Salt */
#if defined(CONFIG_BT_MESH_PB_ADV)
bool linking; /* Linking is being establishing */
u16_t link_close; /* Link close been sent flag */
bt_u32_t id; /* Link ID */
u8_t pending_ack; /* Decide which transaction id ack is pending */
u8_t expect_ack_for; /* Transaction ACK expected for provisioning pdu */
struct {
u8_t id; /* Transaction ID */
u8_t prev_id; /* Previous Transaction ID */
u8_t seg; /* Bit-field of unreceived segments */
u8_t last_seg; /* Last segment (to check length) */
u8_t fcs; /* Expected FCS value */
u8_t adv_buf_id; /* index of buf allocated in adv_buf_data */
struct net_buf_simple *buf;
} rx;
struct {
/* Start timestamp of the transaction */
s64_t start;
/* Transaction id*/
u8_t id;
/* Pending outgoing buffer(s) */
struct net_buf *buf[3];
/* Retransmit timer */
struct k_delayed_work retransmit;
} tx;
#endif
/** Provision timeout timer. Spec P259 says: The provisioning protocol
* shall have a minimum timeout of 60 seconds that is reset each time
* a provisioning protocol PDU is sent or received.
*/
struct k_delayed_work timeout;
};
struct prov_rx {
bt_u32_t link_id;
u8_t xact_id;
u8_t gpc;
};
#define BT_MESH_ALREADY_PROV_NUM (CONFIG_BT_MESH_MAX_PROV_NODES + 10)
struct prov_ctx_t {
/** Provisioner public key and random have been generated
* Bit0 for public key and Bit1 for random
*/
u8_t pub_key_rand_done;
/* Provisioner public key */
u8_t public_key[64];
/* Provisioner random */
u8_t random[16];
/* Number of provisioned devices */
u16_t node_count;
/* Current number of PB-ADV provisioned devices simultaneously */
u8_t pba_count;
/* Current number of PB-GATT provisioned devices simultaneously */
u8_t pbg_count;
/* Current index of device being provisioned using PB-GATT or PB-ADV */
int pb_index;
/* Current unicast address going to assigned */
u16_t current_addr;
/* Number of unprovisioned devices whose information has been added to queue */
u8_t unprov_dev_num;
/* Current net_idx going to be used in provisioning data */
u16_t curr_net_idx;
/* Current flags going to be used in provisioning data */
u16_t curr_flags;
/* Current iv_index going to be used in provisioning data */
u16_t curr_iv_index;
/* Offset of the device uuid to be matched, based on zero */
u8_t match_offset;
/* Length of the device uuid to be matched (start from the match_offset) */
u8_t match_length;
/* Value of the device uuid to be matched */
u8_t match_value[16];
/* Indicate when received uuid_match adv_pkts, can provision it at once */
bool prov_after_match;
/** This structure is used to store the information of the device which
* provisioner has successfully sent provisioning data to. In this
* structure, we don't care if the device is currently in the mesh
* network, or has been removed, or failed to send provisioning
* complete pdu after receiving the provisioning data pdu.
*/
struct already_prov_info {
u8_t uuid[16]; /* device uuid */
u8_t element_num; /* element number of the deleted node */
u16_t unicast_addr; /* Primary unicast address of the deleted node */
} already_prov[BT_MESH_ALREADY_PROV_NUM];
};
struct unprov_dev_queue {
bt_addr_le_t addr;
u8_t uuid[16];
u16_t oob_info;
u8_t bearer;
u8_t flags;
uint8_t auto_add_appkey;
uint8_t prov_count;
} __packed unprov_dev[CONFIG_BT_MESH_UNPROV_DEV_ADD] = {
[0 ...(CONFIG_BT_MESH_UNPROV_DEV_ADD - 1)] = {
.addr.type = 0xff,
.bearer = 0,
.flags = false,
.prov_count = 0,
.auto_add_appkey = 0,
},
};
static prov_adv_pkt_cb adv_pkt_notify;
#define PROV_ADV BIT(0)
#define PROV_GATT BIT(1)
#define RETRANSMIT_TIMEOUT K_MSEC(500)
#define BUF_TIMEOUT K_MSEC(400)
#define TRANSACTION_TIMEOUT K_SECONDS(30)
#define PROVISION_TIMEOUT K_SECONDS(60)
#if defined(CONFIG_BT_MESH_PB_GATT)
#define PROV_BUF_HEADROOM 5
#else
#define PROV_BUF_HEADROOM 0
#endif
#define PROV_BUF(len) NET_BUF_SIMPLE(PROV_BUF_HEADROOM + len)
/* Number of devices can be provisioned at the same time using PB-GATT + PB-ADV */
#define BT_MESH_PROV_SAME_TIME (CONFIG_BT_MESH_PBA_SAME_TIME + CONFIG_BT_MESH_PBG_SAME_TIME)
static struct prov_link link[BT_MESH_PROV_SAME_TIME];
//static const struct bt_mesh_prov *prov;
static const struct bt_mesh_provisioner *provisioner;
static struct prov_ctx_t prov_ctx;
static struct node_info node[CONFIG_BT_MESH_MAX_PROV_NODES];
struct k_sem prov_input_sem;
u8_t prov_input[8];
u8_t prov_input_size;
static void send_link_open(void);
static void send_pub_key(u8_t oob);
static void close_link(int i, u8_t reason);
#if defined(CONFIG_BT_MESH_PB_ADV)
#define ADV_BUF_SIZE 65
static struct adv_buf_t {
struct net_buf_simple buf;
u8_t adv_buf_data[ADV_BUF_SIZE];
} adv_buf[CONFIG_BT_MESH_PBA_SAME_TIME];
#endif
#if 0
#define PROV_FREE_MEM(id, member) \
{ \
if (link[id].member) { \
osi_free(link[id].member); \
} \
}
#endif
/* Temporary provisioner uses this structure for provisioning data */
struct bt_mesh_temp_prov {
u16_t net_idx;
const u8_t *net_key;
u8_t flags;
bt_u32_t iv_index;
u16_t unicast_addr_min;
u16_t unicast_addr_max;
};
static struct bt_mesh_temp_prov temp_prov;
static bool temp_prov_flag;
#define TEMP_PROV_FLAG_GET() temp_prov_flag
static inline int prov_get_pb_index(void)
{
return prov_ctx.pb_index;
}
static void prov_set_pb_index(int i)
{
prov_ctx.pb_index = i;
}
void provisioner_pbg_count_dec(void)
{
if (prov_ctx.pbg_count) {
prov_ctx.pbg_count--;
}
}
void provisioner_pbg_count_inc(void)
{
prov_ctx.pbg_count++;
}
void provisioner_unprov_dev_num_dec(void)
{
if (prov_ctx.unprov_dev_num) {
prov_ctx.unprov_dev_num--;
}
}
void provisioner_clear_connecting(int index)
{
int i = index + CONFIG_BT_MESH_PBA_SAME_TIME;
#if defined(CONFIG_BT_MESH_PB_GATT)
link[i].connecting = false;
link[i].conn = NULL;
#endif
link[i].oob_info = 0x0;
memset(link[i].uuid, 0, 16);
memset(&link[i].addr, 0, sizeof(link[i].addr));
(void)atomic_test_and_clear_bit(link[i].flags, LINK_ACTIVE);
}
const struct bt_mesh_provisioner *provisioner_get_prov_info(void)
{
return provisioner;
}
int provisioner_prov_restore_nodes_info(bt_addr_le_t *addr, /* device address */
u8_t uuid[16], /* node uuid */
u16_t oob_info, /* oob info contained in adv pkt */
u8_t element_num, /* element contained in this node */
u16_t unicast_addr, /* primary unicast address of this node */
u16_t net_idx, /* Netkey index got during provisioning */
u8_t flags, /* Key refresh flag and iv update flag */
bt_u32_t iv_index, /* IV Index */
u8_t dev_key[16], /* Device key */
bt_u32_t provisioned_time /* provison time */)
{
int i;
int err;
for (i = 0; i < CONFIG_BT_MESH_MAX_PROV_NODES; i++) {
if (!node[i].provisioned) {
node[i].provisioned = true;
node[i].oob_info = oob_info;
node[i].element_num = element_num;
node[i].unicast_addr = unicast_addr;
node[i].net_idx = net_idx;
node[i].flags = flags;
node[i].iv_index = iv_index;
node[i].addr = *addr;
memcpy(node[i].uuid, uuid, 16);
node[i].provisioned_time = provisioned_time;
prov_ctx.node_count++;
err = provisioner_node_provision(i, node[i].uuid, node[i].oob_info, node[i].unicast_addr,
node[i].element_num, node[i].net_idx, node[i].flags,
node[i].iv_index, dev_key, node[i].addr.a.val);
if (err) {
BT_ERR("Provisioner store node info in upper layers fail");
return -EIO;
}
if (node[i].unicast_addr + node[i].element_num - 1 > g_restore_max_mac) {
g_restore_max_mac = node[i].unicast_addr + node[i].element_num - 1;
}
prov_ctx.current_addr += element_num;
return 0;
}
}
return 0;
}
int provisioner_prov_reset_all_nodes(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(node); i++) {
if (node[i].provisioned) {
memset(&node[i], 0, sizeof(struct node_info));
}
}
prov_ctx.node_count = 0;
return 0;
}
int provisioner_dev_find(const bt_addr_le_t *addr, const u8_t uuid[16], int *index)
{
bool uuid_match = false;
bool addr_match = false;
u8_t zero[6] = {0};
int i = 0, j = 0, comp = 0;
if (addr) {
comp = memcmp(addr->a.val, zero, 6);
}
if ((!uuid && (!addr || (comp == 0) || (addr->type > BT_ADDR_LE_RANDOM))) || !index) {
return -EINVAL;
}
/** Note: user may add a device into two unprov_dev array elements,
* one with device address, address type and another only
* with device UUID. We need to take this into consideration.
*/
if (uuid) {
for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
if (!memcmp(unprov_dev[i].uuid, uuid, 16)) {
uuid_match = true;
break;
}
}
}
if (addr && comp && (addr->type <= BT_ADDR_LE_RANDOM)) {
for (j = 0; j < ARRAY_SIZE(unprov_dev); j++) {
if (!memcmp(unprov_dev[j].addr.a.val, addr->a.val, 6) &&
unprov_dev[j].addr.type == addr->type) {
addr_match = true;
break;
}
}
}
if (!uuid_match && !addr_match) {
BT_DBG("%s: device does not exist in queue", __func__);
return -ENODEV;
}
if (uuid_match && addr_match && (i != j)) {
/** In this situation, copy address & type into device
* uuid array element, reset another element, rm_flag
* will be decided by uuid element.
* Note: need to decrement the unprov_dev_num count
*/
unprov_dev[i].addr.type = unprov_dev[j].addr.type;
memcpy(unprov_dev[i].addr.a.val, unprov_dev[j].addr.a.val, 6);
unprov_dev[i].bearer |= unprov_dev[j].bearer;
memset(&unprov_dev[j], 0x0, sizeof(struct unprov_dev_queue));
provisioner_unprov_dev_num_dec();
}
*index = uuid_match ? i : j;
return 0;
}
static int provisioner_dev_uuid_match(const u8_t dev_uuid[16])
{
if (!dev_uuid) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
if (prov_ctx.match_length) {
if (memcmp(dev_uuid + prov_ctx.match_offset,
prov_ctx.match_value, prov_ctx.match_length)) {
return -EAGAIN;
}
}
return 0;
}
u8_t prov_addr;
int bt_mesh_provisioner_add_unprov_dev(struct bt_mesh_unprov_dev_add *add_dev, u8_t flags)
{
bt_addr_le_t add_addr = {0};
u8_t zero[16] = {0};
int addr_cmp = 0, uuid_cmp = 0;
int i = 0, err = 0;
if (!add_dev) {
BT_ERR("%s: add_dev is NULL", __func__);
return -EINVAL;
}
addr_cmp = memcmp(add_dev->addr, zero, 6);
uuid_cmp = memcmp(add_dev->uuid, zero, 16);
if (add_dev->bearer == 0x0 || ((uuid_cmp == 0) &&
((addr_cmp == 0) || add_dev->addr_type > 0x01))) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
BT_DBG("add_dev->bearer add_dev->bearer add_dev->bearer: %02x", add_dev->bearer);
if ((add_dev->bearer & BT_MESH_PROV_ADV) && (add_dev->bearer & BT_MESH_PROV_GATT) &&
(flags & START_PROV_NOW)) {
BT_ERR("%s: can not start both PB-ADV & PB-GATT provision", __func__);
return -EINVAL;
}
if ((uuid_cmp == 0) && (flags & START_PROV_NOW)) {
BT_ERR("%s: can not start provisioning with zero uuid", __func__);
return -EINVAL;
}
if ((add_dev->bearer & BT_MESH_PROV_GATT) && (flags & START_PROV_NOW) &&
((addr_cmp == 0) || add_dev->addr_type > 0x01)) {
BT_ERR("%s: PB-GATT with invalid device address", __func__);
return -EINVAL;
}
if (add_dev->bearer & BT_MESH_PROV_GATT) {
#if !CONFIG_BT_MESH_PB_GATT
BT_ERR("%s: not support PB-GATT", __func__);
return -EINVAL;
#endif
}
if (add_dev->bearer & BT_MESH_PROV_ADV) {
#if !CONFIG_BT_MESH_PB_ADV
BT_ERR("%s: not support PB-ADV", __func__);
return -EINVAL;
#endif
}
/* Check if the device has already been provisioned */
for (i = 0; i < ARRAY_SIZE(node); i++) {
if (node[i].provisioned) {
if (!memcmp(node[i].uuid, add_dev->uuid, 16)) {
BT_WARN("add provisoioned node to unprov list", __func__);
return -EALREADY;
}
}
}
/* Check if the device is being provisioned now */
for (i = 0; i < ARRAY_SIZE(link); i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE) || link[i].connecting) {
if (!memcmp(link[i].uuid, add_dev->uuid, 16)) {
BT_WARN("%s: The device is being provisioned", __func__);
return -EALREADY;
}
}
}
add_addr.type = add_dev->addr_type;
memcpy(add_addr.a.val, add_dev->addr, 6);
err = provisioner_dev_find(&add_addr, add_dev->uuid, &i);
if (err == -EINVAL) {
BT_ERR("%s: invalid parameters", __func__);
return err;
} else if (err == 0) {
if (!(add_dev->bearer & unprov_dev[i].bearer)) {
BT_WARN("%s: add device with only bearer updated", __func__);
unprov_dev[i].bearer |= add_dev->bearer;
} else {
BT_WARN("%s: device already exists", __func__);
}
goto start;
}
for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
if (unprov_dev[i].bearer) {
continue;
}
if (addr_cmp && (add_dev->addr_type <= 0x01)) {
unprov_dev[i].addr.type = add_dev->addr_type;
memcpy(unprov_dev[i].addr.a.val, add_dev->addr, 6);
}
if (uuid_cmp) {
memcpy(unprov_dev[i].uuid, add_dev->uuid, 16);
}
unprov_dev[i].bearer = add_dev->bearer & BIT_MASK(2);
unprov_dev[i].flags = flags & BIT_MASK(3);
unprov_dev[i].auto_add_appkey = add_dev->auto_add_appkey;
unprov_dev[i].prov_count = 0;
goto start;
}
/* If queue is full, find flushable device and replace it */
for (i = 0; i < ARRAY_SIZE(unprov_dev); i++) {
if (unprov_dev[i].flags & FLUSHABLE_DEV) {
memset(&unprov_dev[i], 0, sizeof(struct unprov_dev_queue));
if (addr_cmp && (add_dev->addr_type <= 0x01)) {
unprov_dev[i].addr.type = add_dev->addr_type;
memcpy(unprov_dev[i].addr.a.val, add_dev->addr, 6);
}
if (uuid_cmp) {
memcpy(unprov_dev[i].uuid, add_dev->uuid, 16);
}
unprov_dev[i].bearer = add_dev->bearer & BIT_MASK(2);
unprov_dev[i].flags = flags & BIT_MASK(3);
goto start;
}
}
BT_ERR("%s: unprov_dev queue is full", __func__);
return -ENOMEM;
start:
if (!(flags & START_PROV_NOW)) {
return 0;
}
if (prov_ctx.node_count == CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_WARN("%s: Node count reachs max limit", __func__);
return -ENOMEM;
}
/* Check if current provisioned node count + active link reach max limit */
if (prov_ctx.node_count + prov_ctx.pba_count + prov_ctx.pbg_count >=
CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_WARN("%s: Node count + active link count reach max limit", __func__);
return -EIO;
}
if (add_dev->bearer & BT_MESH_PROV_ADV) {
if (prov_ctx.pba_count == CONFIG_BT_MESH_PBA_SAME_TIME) {
BT_WARN("%s: Current PB-ADV links reach max limit", __func__);
return -EIO;
}
for (i = 0; i < CONFIG_BT_MESH_PBA_SAME_TIME; i++) {
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE) && !link[i].linking) {
memcpy(link[i].uuid, add_dev->uuid, 16);
link[i].oob_info = add_dev->oob_info;
if (addr_cmp && (add_dev->addr_type <= 0x01)) {
link[i].addr.type = add_dev->addr_type;
memcpy(link[i].addr.a.val, add_dev->addr, 6);
}
break;
}
}
if (i == CONFIG_BT_MESH_PBA_SAME_TIME) {
BT_ERR("%s: no PB-ADV link available", __func__);
return -ENOMEM;
}
prov_set_pb_index(i);
send_link_open();
link[i].linking = 1;
bt_addr_le_t addr;
int index = 0;
memcpy(&addr, &link[i].addr, sizeof(bt_addr_le_t));
err = provisioner_dev_find(&addr, link[i].uuid, &index);
if (err || index > ARRAY_SIZE(unprov_dev)) {
BT_ERR("%s: find dev faild", __func__);
if (provisioner->prov_link_open) {
provisioner->prov_link_open(BT_MESH_PROV_ADV, link[i].addr.a.val, link[i].addr.type, link[i].uuid, 0);
}
} else {
unprov_dev[index].prov_count++;
if (provisioner->prov_link_open) {
provisioner->prov_link_open(BT_MESH_PROV_ADV, link[i].addr.a.val, link[i].addr.type, link[i].uuid, unprov_dev[index].prov_count);
}
}
prov_addr = add_dev->addr[0];
} else if (add_dev->bearer & BT_MESH_PROV_GATT) {
if (prov_ctx.pbg_count == CONFIG_BT_MESH_PBG_SAME_TIME) {
BT_WARN("%s: Current PB-GATT links reach max limit", __func__);
return -EIO;
}
for (i = CONFIG_BT_MESH_PBA_SAME_TIME; i < BT_MESH_PROV_SAME_TIME; i++) {
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE) && !link[i].connecting) {
memcpy(link[i].uuid, add_dev->uuid, 16);
link[i].oob_info = add_dev->oob_info;
if (addr_cmp && (add_dev->addr_type <= BT_ADDR_LE_RANDOM)) {
link[i].addr.type = add_dev->addr_type;
memcpy(link[i].addr.a.val, add_dev->addr, 6);
}
break;
}
}
if (i == BT_MESH_PROV_SAME_TIME) {
BT_ERR("%s: no PB-GATT link available", __func__);
return -ENOMEM;
}
if (true != bt_prov_check_gattc_id(i - CONFIG_BT_MESH_PBA_SAME_TIME, &link[i].addr)
|| bt_gattc_conn_create(i - CONFIG_BT_MESH_PBA_SAME_TIME, BT_UUID_16(BT_UUID_MESH_PROV)->val)) {
memset(link[i].uuid, 0, 16);
link[i].oob_info = 0x0;
memset(&link[i].addr, 0, sizeof(link[i].addr));
return -EIO;
}
link[i].connecting = true;
}
return 0;
}
int bt_mesh_provisioner_add_node(struct node_info *node_info, uint8_t dev_key[16])
{
if (!node_info || !dev_key) {
return -EINVAL;
}
uint8_t j;
int err;
for (j = 0; j < CONFIG_BT_MESH_MAX_PROV_NODES; j++) {
if (!node[j].provisioned) {
node[j].provisioned = true;
node[j].oob_info = node_info->oob_info;
node[j].element_num = node_info->element_num;
node[j].unicast_addr = node_info->unicast_addr;
node[j].net_idx = node_info->net_idx;
node[j].flags = node_info->flags;
node[j].iv_index = node_info->iv_index;
node[j].addr.type = node_info->addr.type;
memcpy(node[j].addr.a.val, node_info->addr.a.val, 6);
memcpy(node[j].uuid, node_info->uuid, 16);
node[j].provisioned_time = krhino_ticks_to_ms(k_uptime_get_32());
break;
}
}
prov_ctx.node_count++;
err = provisioner_node_provision(j, node[j].uuid, node[j].oob_info, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, node[j].flags,
node[j].iv_index, dev_key, node[j].addr.a.val);
if (err) {
BT_ERR("Provisioner store node info in upper layers fail");
return err;
}
if (provisioner->prov_complete) {
provisioner->prov_complete(j, node[j].uuid, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, false);
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mesh_node(j);
}
return 0;
}
int bt_mesh_provisioner_delete_device(struct bt_mesh_device_delete *del_dev)
{
/**
* Three Situations:
* 1. device is not being/been provisioned, just remove from device queue.
* 2. device is being provisioned, need to close link & remove from device queue.
* 3. device is been provisioned, need to send config_node_reset and may need to
* remove from device queue. config _node_reset can be added in function
* provisioner_node_reset() in provisioner_main.c.
*/
bt_addr_le_t del_addr = {0};
u8_t zero[16] = {0};
int addr_cmp = 0, uuid_cmp = 0;
bool addr_match = false;
bool uuid_match = false;
int i = 0, err = 0;
if (!del_dev) {
BT_ERR("%s: del_dev is NULL", __func__);
return -EINVAL;
}
addr_cmp = memcmp(del_dev->addr, zero, 6);
uuid_cmp = memcmp(del_dev->uuid, zero, 16);
if ((uuid_cmp == 0) && ((addr_cmp == 0) ||
del_dev->addr_type > 0x01)) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
del_addr.type = del_dev->addr_type;
memcpy(del_addr.a.val, del_dev->addr, 6);
/* First: find if the device is in the device queue */
err = provisioner_dev_find(&del_addr, del_dev->uuid, &i);
if (err) {
BT_DBG("%s: device not in the queue", __func__);
} else {
memset(&unprov_dev[i], 0x0, sizeof(struct unprov_dev_queue));
provisioner_unprov_dev_num_dec();
}
/* Second: find if the device is being provisioned */
for (i = 0; i < ARRAY_SIZE(link); i++) {
if (addr_cmp && (del_dev->addr_type <= BT_ADDR_LE_RANDOM)) {
if (!memcmp(link[i].addr.a.val, del_dev->addr, 6) &&
link[i].addr.type == del_dev->addr_type) {
addr_match = true;
}
}
if (uuid_cmp) {
if (!memcmp(link[i].uuid, del_dev->uuid, 16)) {
uuid_match = true;
}
}
if (addr_match || uuid_match) {
close_link(i, CLOSE_REASON_FAILED);
break;
}
}
/* Third: find if the device is been provisioned */
for (i = 0; i < ARRAY_SIZE(node); i++) {
if (addr_cmp && (del_dev->addr_type <= 0x01)) {
if (!memcmp(node[i].addr.a.val, del_dev->addr, 6) &&
node[i].addr.type == del_dev->addr_type) {
addr_match = true;
}
}
if (uuid_cmp) {
if (!memcmp(node[i].uuid, del_dev->uuid, 16)) {
uuid_match = true;
}
}
if (addr_match || uuid_match) {
memset(&node[i], 0, sizeof(struct node_info));
provisioner_node_reset(i);
if (prov_ctx.node_count) {
prov_ctx.node_count--;
}
break;
}
}
return 0;
}
int bt_mesh_provisioner_delete_unprov_device(struct bt_mesh_device_delete *del_dev)
{
/**
* Three Situations:
* 1. device is not being/been provisioned, just remove from device queue.
* 2. device is being provisioned, need to close link & remove from device queue.
*/
bt_addr_le_t del_addr = {0};
u8_t zero[16] = {0};
int addr_cmp = 0, uuid_cmp = 0;
bool addr_match = false;
bool uuid_match = false;
int i = 0, err = 0;
if (!del_dev) {
BT_ERR("%s: del_dev is NULL", __func__);
return -EINVAL;
}
addr_cmp = memcmp(del_dev->addr, zero, 6);
uuid_cmp = memcmp(del_dev->uuid, zero, 16);
if ((uuid_cmp == 0) && ((addr_cmp == 0) ||
del_dev->addr_type > 0x01)) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
del_addr.type = del_dev->addr_type;
memcpy(del_addr.a.val, del_dev->addr, 6);
/* First: find if the device is in the device queue */
err = provisioner_dev_find(&del_addr, del_dev->uuid, &i);
if (err) {
BT_DBG("%s: device not in the queue", __func__);
} else {
memset(&unprov_dev[i], 0x0, sizeof(struct unprov_dev_queue));
provisioner_unprov_dev_num_dec();
}
/* Second: find if the device is being provisioned */
for (i = 0; i < ARRAY_SIZE(link); i++) {
if (addr_cmp && (del_dev->addr_type <= BT_ADDR_LE_RANDOM)) {
if (!memcmp(link[i].addr.a.val, del_dev->addr, 6) &&
link[i].addr.type == del_dev->addr_type) {
addr_match = true;
}
}
if (uuid_cmp) {
if (!memcmp(link[i].uuid, del_dev->uuid, 16)) {
uuid_match = true;
}
}
if (addr_match || uuid_match) {
close_link(i, CLOSE_REASON_FAILED);
break;
}
}
return 0;
}
int bt_mesh_provisioner_set_dev_uuid_match(u8_t offset, u8_t length,
const u8_t *match, bool prov_flag)
{
if (length && (!match || (offset + length > 16))) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
#if 0
if (length && !prov_ctx.match_value) {
prov_ctx.match_value = osi_calloc(16);
if (!prov_ctx.match_value) {
BT_ERR("%s: allocate memory fail", __func__);
return -ENOMEM;
}
}
#endif
prov_ctx.match_offset = offset;
prov_ctx.match_length = length;
if (length) {
memcpy(prov_ctx.match_value, match, length);
}
prov_ctx.prov_after_match = prov_flag;
return 0;
}
int bt_mesh_prov_adv_pkt_cb_register(prov_adv_pkt_cb cb)
{
if (!cb) {
BT_ERR("%s: cb is NULL", __func__);
return -EINVAL;
}
adv_pkt_notify = cb;
return 0;
}
int bt_mesh_provisioner_set_prov_data_info(struct bt_mesh_prov_data_info *info)
{
const u8_t *key = NULL;
if (!info || info->flag == 0) {
return -EINVAL;
}
if (info->flag & NET_IDX_FLAG) {
key = provisioner_net_key_get(info->net_idx);
if (!key) {
BT_ERR("%s: add local netkey first", __func__);
return -EINVAL;
}
prov_ctx.curr_net_idx = info->net_idx;
} else if (info->flag & FLAGS_FLAG) {
prov_ctx.curr_flags = info->flags;
} else if (info->flag & IV_INDEX_FLAG) {
prov_ctx.curr_iv_index = info->iv_index;
}
return 0;
}
/* APIs for temporary provisioner */
void provisioner_temp_prov_flag_set(bool flag)
{
temp_prov_flag = flag;
}
u8_t bt_mesh_temp_prov_set_unicast_addr(u16_t min, u16_t max)
{
if (!BT_MESH_ADDR_IS_UNICAST(min) || !BT_MESH_ADDR_IS_UNICAST(max)) {
BT_WARN("%s: not a unicast address", __func__);
return 0x01; /* status is 0x01 */
}
if (min > max) {
BT_ERR("%s: min bigger than max", __func__);
return 0x02; /* status is 0x02 */
}
if (min <= temp_prov.unicast_addr_max) {
BT_WARN("%s: address overlap", __func__);
return 0x03; /* status is 0x03 */
}
temp_prov.unicast_addr_min = min;
temp_prov.unicast_addr_max = max;
prov_ctx.current_addr = temp_prov.unicast_addr_min;
return 0x0; /* status is 0x00 */
}
int bt_mesh_temp_prov_set_flags_iv_index(u8_t flags, bt_u32_t iv_index)
{
temp_prov.flags = flags;
temp_prov.iv_index = iv_index;
return 0;
}
u8_t provisioner_temp_prov_set_net_idx(const u8_t *net_key, u16_t net_idx)
{
if (!net_key) {
return 0x01; /*status: fail*/
}
temp_prov.net_idx = net_idx;
temp_prov.net_key = net_key;
return 0x0; /* status: success */
}
#if defined(CONFIG_BT_MESH_PB_ADV)
static struct net_buf_simple *bt_mesh_pba_get_buf(int id)
{
struct net_buf_simple *buf = &(adv_buf[id].buf);
net_buf_simple_init(buf, 0);
return buf;
}
#endif /* CONFIG_BT_MESH_PB_ADV */
static void prov_memory_free(int i)
{
#if 0
PROV_FREE_MEM(i, dhkey);
PROV_FREE_MEM(i, auth);
PROV_FREE_MEM(i, conf);
PROV_FREE_MEM(i, conf_salt);
PROV_FREE_MEM(i, conf_key);
PROV_FREE_MEM(i, conf_inputs);
PROV_FREE_MEM(i, prov_salt);
#endif
}
#if defined(CONFIG_BT_MESH_PB_ADV)
static void buf_sent(int err, void *user_data)
{
int i = (int)user_data;
if (!link[i].tx.buf[0]) {
return;
}
k_delayed_work_submit(&link[i].tx.retransmit, RETRANSMIT_TIMEOUT);
}
static struct bt_mesh_send_cb buf_sent_cb = {
.end = buf_sent,
};
static void free_segments(int id)
{
int i;
for (i = 0; i < ARRAY_SIZE(link[id].tx.buf); i++) {
struct net_buf *buf = link[id].tx.buf[i];
if (!buf) {
break;
}
link[id].tx.buf[i] = NULL;
/* Mark as canceled */
BT_MESH_ADV(buf)->busy = 0;
/** Change by Espressif. Add this to avoid buf->ref is 2 which will
* cause lack of buf.
*/
//if (buf->ref > 1) {
// buf->ref = 1;
//}
/* if buf is unref somewhere */
if (!buf->ref) {
return;
}
net_buf_unref(buf);
}
}
static void prov_clear_tx(int i)
{
BT_DBG("%s", __func__);
k_delayed_work_cancel(&link[i].tx.retransmit);
free_segments(i);
}
static void reset_link(int i, u8_t reason)
{
bool pub_key;
int err = 0;
int index = 0;
bt_addr_le_t dev_addr = {0};
prov_clear_tx(i);
memcpy(&dev_addr, &link[i].addr, sizeof(bt_addr_le_t));
err = provisioner_dev_find(&dev_addr, link[i].uuid, &index);
if (err || index > ARRAY_SIZE(unprov_dev)) {
BT_DBG("%s: find dev faild", __func__);
if (provisioner->prov_link_close) {
provisioner->prov_link_close(BT_MESH_PROV_ADV, reason, link[i].addr.a.val, link[i].addr.type, link[i].uuid, 0);
}
} else {
if (provisioner->prov_link_close) {
provisioner->prov_link_close(BT_MESH_PROV_ADV, reason, link[i].addr.a.val, link[i].addr.type, link[i].uuid, unprov_dev[index].prov_count);
}
}
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
pub_key = atomic_test_bit(link[i].flags, LOCAL_PUB_KEY);
prov_memory_free(i);
/* Clear everything except the retransmit delayed work config */
memset(&link[i], 0, offsetof(struct prov_link, tx.retransmit));
link[i].pending_ack = XACT_NVAL;
link[i].rx.prev_id = XACT_NVAL;
if (pub_key) {
atomic_set_bit(link[i].flags, LOCAL_PUB_KEY);
}
link[i].rx.buf = bt_mesh_pba_get_buf(i);
if (prov_ctx.pba_count) {
prov_ctx.pba_count--;
}
}
static struct net_buf *adv_buf_create(void)
{
struct net_buf *buf;
buf = bt_mesh_adv_create(BT_MESH_ADV_PROV, BT_MESH_TRANSMIT(PROV_XMIT_COUNT, PROV_XMIT_INT),
BUF_TIMEOUT);
if (!buf) {
BT_ERR("Out of provisioning buffers");
return NULL;
}
return buf;
}
static void ack_complete(u16_t duration, int err, void *user_data)
{
int i = (int)user_data;
BT_DBG("xact %u complete", (u8_t)link[i].pending_ack);
link[i].pending_ack = XACT_NVAL;
}
static void gen_prov_ack_send(u8_t xact_id)
{
static const struct bt_mesh_send_cb cb = {
.start = ack_complete,
};
const struct bt_mesh_send_cb *complete;
struct net_buf *buf;
int i = prov_get_pb_index();
BT_DBG("xact_id %u", xact_id);
if (link[i].pending_ack == xact_id) {
BT_DBG("Not sending duplicate ack");
return;
}
buf = adv_buf_create();
if (!buf) {
return;
}
if (link[i].pending_ack == XACT_NVAL) {
link[i].pending_ack = xact_id;
complete = &cb;
} else {
complete = NULL;
}
net_buf_add_be32(buf, link[i].id);
net_buf_add_u8(buf, xact_id);
net_buf_add_u8(buf, GPC_ACK);
bt_mesh_adv_send(buf, complete, (void *)i);
net_buf_unref(buf);
}
static void send_reliable(int id)
{
link[id].tx.start = k_uptime_get();
for (int i = 0; i < ARRAY_SIZE(link[id].tx.buf); i++) {
struct net_buf *buf = link[id].tx.buf[i];
if (!buf) {
break;
}
if (i + 1 < ARRAY_SIZE(link[id].tx.buf) && link[id].tx.buf[i + 1]) {
bt_mesh_adv_send(buf, NULL, NULL);
} else {
bt_mesh_adv_send(buf, &buf_sent_cb, (void *)id);
}
}
}
static int bearer_ctl_send(int i, u8_t op, void *data, u8_t data_len)
{
struct net_buf *buf;
BT_DBG("op 0x%02x data_len %u", op, data_len);
prov_clear_tx(i);
buf = adv_buf_create();
if (!buf) {
return -ENOBUFS;
}
net_buf_add_be32(buf, link[i].id);
/* Transaction ID, always 0 for Bearer messages */
net_buf_add_u8(buf, 0x00);
net_buf_add_u8(buf, GPC_CTL(op));
net_buf_add_mem(buf, data, data_len);
link[i].tx.buf[0] = buf;
send_reliable(i);
/** We can also use buf->ref and a flag to decide that
* link close has been sent 3 times.
* Here we use another way: use retransmit timer and need
* to make sure the timer is not cancelled during sending
* link close pdu, so we add link[i].tx.id = 0
*/
if (op == LINK_CLOSE) {
u8_t reason = *(u8_t *)data;
link[i].link_close = (reason << 8 | BIT(0));
link[i].tx.id = 0;
}
return 0;
}
static void send_link_open(void)
{
int i = prov_get_pb_index(), j;
/** Generate link ID, and may need to check if this id is
* currently being used, which may will not happen ever.
*/
bt_rand(&link[i].id, sizeof(bt_u32_t));
while (1) {
for (j = 0; j < CONFIG_BT_MESH_PBA_SAME_TIME; j++) {
if (atomic_test_bit(link[j].flags, LINK_ACTIVE) || link[j].linking) {
if (link[i].id == link[j].id) {
bt_rand(&link[i].id, sizeof(bt_u32_t));
break;
}
}
}
if (j == CONFIG_BT_MESH_PBA_SAME_TIME) {
break;
}
}
bearer_ctl_send(i, LINK_OPEN, link[i].uuid, 16);
/* Set LINK_ACTIVE just to be in compatibility with current Zephyr code */
atomic_set_bit(link[i].flags, LINK_ACTIVE);
prov_ctx.pba_count++;
}
static u8_t last_seg(u8_t len)
{
if (len <= START_PAYLOAD_MAX) {
return 0;
}
len -= START_PAYLOAD_MAX;
return 1 + (len / CONT_PAYLOAD_MAX);
}
static inline u8_t next_transaction_id(void)
{
int i = prov_get_pb_index();
if (link[i].tx.id < 0x7F) {
return link[i].tx.id++;
}
return 0x0;
}
static int prov_send_adv(struct net_buf_simple *msg)
{
struct net_buf *start, *buf;
u8_t seg_len, seg_id;
u8_t xact_id;
int i = prov_get_pb_index();
BT_DBG("%s, len %u: %s", __func__, msg->len, bt_hex(msg->data, msg->len));
prov_clear_tx(i);
start = adv_buf_create();
if (!start) {
return -ENOBUFS;
}
xact_id = next_transaction_id();
net_buf_add_be32(start, link[i].id);
net_buf_add_u8(start, xact_id);
net_buf_add_u8(start, GPC_START(last_seg(msg->len)));
net_buf_add_be16(start, msg->len);
net_buf_add_u8(start, bt_mesh_fcs_calc(msg->data, msg->len));
link[i].tx.buf[0] = start;
seg_len = MIN(msg->len, START_PAYLOAD_MAX);
BT_DBG("seg 0 len %u: %s", seg_len, bt_hex(msg->data, seg_len));
net_buf_add_mem(start, msg->data, seg_len);
net_buf_simple_pull(msg, seg_len);
buf = start;
for (seg_id = 1; msg->len > 0; seg_id++) {
if (seg_id >= ARRAY_SIZE(link[i].tx.buf)) {
BT_ERR("Too big message");
free_segments(i);
return -E2BIG;
}
buf = adv_buf_create();
if (!buf) {
free_segments(i);
return -ENOBUFS;
}
link[i].tx.buf[seg_id] = buf;
seg_len = MIN(msg->len, CONT_PAYLOAD_MAX);
BT_DBG("seg_id %u len %u: %s", seg_id, seg_len,
bt_hex(msg->data, seg_len));
net_buf_add_be32(buf, link[i].id);
net_buf_add_u8(buf, xact_id);
net_buf_add_u8(buf, GPC_CONT(seg_id));
net_buf_add_mem(buf, msg->data, seg_len);
net_buf_simple_pull(msg, seg_len);
}
send_reliable(i);
if (!atomic_test_and_set_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_submit(&link[i].timeout, PROVISION_TIMEOUT);
}
return 0;
}
#endif /* CONFIG_BT_MESH_PB_ADV */
#if defined(CONFIG_BT_MESH_PB_GATT)
static int prov_send_gatt(struct net_buf_simple *msg)
{
int i = prov_get_pb_index();
int err;
if (!link[i].conn) {
return -ENOTCONN;
}
err = provisioner_proxy_send(link[i].conn, BT_MESH_PROXY_PROV, msg);
if (err) {
BT_ERR("Proxy prov send fail");
return err;
}
if (!atomic_test_and_set_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_submit(&link[i].timeout, PROVISION_TIMEOUT);
}
return 0;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
static inline int prov_send(struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
if (i < CONFIG_BT_MESH_PBA_SAME_TIME) {
#if defined(CONFIG_BT_MESH_PB_ADV)
return prov_send_adv(buf);
#else
return -EINVAL;
#endif
} else if (i >= CONFIG_BT_MESH_PBA_SAME_TIME &&
i < BT_MESH_PROV_SAME_TIME) {
#if defined(CONFIG_BT_MESH_PB_GATT)
return prov_send_gatt(buf);
#else
return -EINVAL;
#endif
} else {
BT_ERR("Close link with link index exceeding upper limit");
return -EINVAL;
}
}
static void prov_buf_init(struct net_buf_simple *buf, u8_t type)
{
net_buf_simple_init(buf, PROV_BUF_HEADROOM);
net_buf_simple_add_u8(buf, type);
}
static void prov_invite(const u8_t *data)
{
BT_DBG("%s", __func__);
}
static void prov_start(const u8_t *data)
{
BT_DBG("%s", __func__);
}
static void prov_data(const u8_t *data)
{
BT_DBG("%s", __func__);
}
static void send_invite(void)
{
struct net_buf_simple *buf = PROV_BUF(2);
int i = prov_get_pb_index();
prov_buf_init(buf, PROV_INVITE);
net_buf_simple_add_u8(buf, provisioner->prov_attention);
link[i].conf_inputs[0] = provisioner->prov_attention;
if (prov_send(buf)) {
BT_ERR("Failed to send invite");
close_link(i, CLOSE_REASON_FAILED);
return;
}
link[i].expect = PROV_CAPABILITIES;
}
static void prov_capabilities(const u8_t *data)
{
struct net_buf_simple *buf = PROV_BUF(6);
u16_t algorithms, output_action, input_action;
u8_t element_num, pub_key_oob, static_oob,
output_size, input_size;
u8_t auth_method, auth_action, auth_size;
int i = prov_get_pb_index(), j;
element_num = data[0];
BT_DBG("Elements: %u", element_num);
if (!element_num) {
BT_ERR("Element number wrong");
goto fail;
}
link[i].element_num = element_num;
algorithms = sys_get_be16(&data[1]);
BT_DBG("Algorithms: %u", algorithms);
if (algorithms != BIT(PROV_ALG_P256)) {
BT_ERR("Algorithms wrong");
goto fail;
}
pub_key_oob = data[3];
BT_DBG("Public Key Type: 0x%02x", pub_key_oob);
if (pub_key_oob > 0x01) {
BT_ERR("Public key type wrong");
goto fail;
}
pub_key_oob = ((provisioner->prov_pub_key_oob &&
provisioner->prov_pub_key_oob_cb) ? pub_key_oob : 0x00);
static_oob = data[4];
BT_DBG("Static OOB Type: 0x%02x", static_oob);
if (static_oob > 0x01) {
BT_ERR("Static OOB type wrong");
goto fail;
}
static_oob = (provisioner->prov_static_oob_val ? static_oob : 0x00);
output_size = data[5];
BT_DBG("Output OOB Size: %u", output_size);
if (output_size > 0x08) {
BT_ERR("Output OOB size wrong");
goto fail;
}
output_action = sys_get_be16(&data[6]);
BT_DBG("Output OOB Action: 0x%04x", output_action);
if (output_action > 0x1f) {
BT_ERR("Output OOB action wrong");
goto fail;
}
/* Provisioner select output action */
if (output_size) {
for (j = 0; j < 5; j++) {
if (output_action & BIT(j)) {
//output_action = BIT(j);
output_action = j;
break;
}
}
}
input_size = data[8];
BT_DBG("Input OOB Size: %u", input_size);
if (input_size > 0x08) {
BT_ERR("Input OOB size wrong");
goto fail;
}
input_action = sys_get_be16(&data[9]);
BT_DBG("Input OOB Action: 0x%04x", input_action);
if (input_action > 0x0f) {
BT_ERR("Input OOB action wrong");
goto fail;
}
/* Make sure received pdu is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
/* Provisioner select input action */
if (input_size) {
for (j = 0; j < 4; j++) {
if (input_action & BIT(j)) {
//input_action = BIT(j);
input_action = j;
break;
}
}
}
if (static_oob) {
/* if static oob is valid, just use static oob */
auth_method = AUTH_METHOD_STATIC;
auth_action = 0x00;
auth_size = 0x00;
} else {
if (!output_size && !input_size) {
auth_method = AUTH_METHOD_NO_OOB;
auth_action = 0x00;
auth_size = 0x00;
} else if (!output_size && input_size) {
auth_method = AUTH_METHOD_INPUT;
auth_action = (u8_t)input_action;
auth_size = input_size;
} else {
auth_method = AUTH_METHOD_OUTPUT;
auth_action = (u8_t)output_action;
auth_size = output_size;
}
}
#if 0
auth_method = AUTH_METHOD_OUTPUT;
auth_action = (u8_t)OUTPUT_OOB_NUMBER;
auth_size = 4;
prov_input_size = auth_size;
#endif
#if 0
auth_method = AUTH_METHOD_NO_OOB;
auth_action = 0;
auth_size = 0;
prov_input_size = auth_size;
#endif
//auth_action = (u8_t)OUTPUT_OOB_NUMBER;
//auth_size = 4;
prov_input_size = auth_size;
/* Store provisioning capbilities value in conf_inputs */
memcpy(&link[i].conf_inputs[1], data, 11);
prov_buf_init(buf, PROV_START);
net_buf_simple_add_u8(buf, provisioner->prov_algorithm);
net_buf_simple_add_u8(buf, pub_key_oob);
net_buf_simple_add_u8(buf, auth_method);
net_buf_simple_add_u8(buf, auth_action);
net_buf_simple_add_u8(buf, auth_size);
memcpy(&link[i].conf_inputs[12], &buf->data[1], 5);
if (prov_send(buf)) {
BT_ERR("Failed to send start");
goto fail;
}
link[i].auth_method = auth_method;
link[i].auth_action = auth_action;
link[i].auth_size = auth_size;
/** After prov start sent, use OOB to get remote public key.
* And we just follow the procedure in Figure 5.15 of Section
* 5.4.2.3 of Mesh Profile Spec.
*/
if (pub_key_oob) {
/** Because public key sent using provisioning pdu is
* big-endian, we may believe that device public key
* received using OOB is big-endian too.
*/
if (provisioner->prov_pub_key_oob_cb(&link[i].conf_inputs[81])) {
BT_ERR("Public Key OOB fail");
goto fail;
}
atomic_set_bit(link[i].flags, REMOTE_PUB_KEY);
}
/** If using PB-ADV, need to listen for transaction ack,
* after ack is received, provisioner can send public key.
*/
#if defined(CONFIG_BT_MESH_PB_ADV)
if (i < CONFIG_BT_MESH_PBA_SAME_TIME) {
link[i].expect_ack_for = PROV_START;
return;
}
#endif /* CONFIG_BT_MESH_PB_ADV */
send_pub_key(pub_key_oob);
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static bt_mesh_output_action_t output_action(u8_t action)
{
switch (action) {
case OUTPUT_OOB_BLINK:
return BT_MESH_BLINK;
case OUTPUT_OOB_BEEP:
return BT_MESH_BEEP;
case OUTPUT_OOB_VIBRATE:
return BT_MESH_VIBRATE;
case OUTPUT_OOB_NUMBER:
return BT_MESH_DISPLAY_NUMBER;
case OUTPUT_OOB_STRING:
return BT_MESH_DISPLAY_STRING;
default:
return BT_MESH_NO_OUTPUT;
}
}
static bt_mesh_input_action_t input_action(u8_t action)
{
switch (action) {
case INPUT_OOB_PUSH:
return BT_MESH_PUSH;
case INPUT_OOB_TWIST:
return BT_MESH_TWIST;
case INPUT_OOB_NUMBER:
return BT_MESH_ENTER_NUMBER;
case INPUT_OOB_STRING:
return BT_MESH_ENTER_STRING;
default:
return BT_MESH_NO_INPUT;
}
}
static int prov_auth(u8_t method, u8_t action, u8_t size)
{
bt_mesh_output_action_t output;
bt_mesh_input_action_t input;
int i = prov_get_pb_index();
#if 0
link[i].auth = (u8_t *)osi_calloc(PROV_AUTH_VAL_SIZE);
if (!link[i].auth) {
BT_ERR("Allocate auth memory fail");
close_link(i, CLOSE_REASON_FAILED);
return -ENOMEM;
}
#endif
switch (method) {
case AUTH_METHOD_NO_OOB:
if (action || size) {
return -EINVAL;
}
memset(link[i].auth, 0, 16);
return 0;
case AUTH_METHOD_STATIC: {
if (action || size) {
return -EINVAL;
}
int ret = 0;
if (provisioner->prov_input_static_oob) {
ret = provisioner->prov_input_static_oob();
}
if (!ret) {
memcpy(link[i].auth + 16 - provisioner->prov_static_oob_len,
provisioner->prov_static_oob_val, provisioner->prov_static_oob_len);
memset(link[i].auth, 0, 16 - provisioner->prov_static_oob_len);
} else {
return ret;
}
return 0;
}
case AUTH_METHOD_OUTPUT: {
/* Use auth_action to get device output action */
output = output_action(action);
if (!output) {
return -EINVAL;
}
return provisioner->prov_input_num(output, size);
}
case AUTH_METHOD_INPUT: {
/* Use auth_action to get device input action */
input = input_action(action);
if (!input) {
return -EINVAL;
}
return provisioner->prov_output_num(input, size);
}
default:
return -EINVAL;
}
}
static void send_confirm(void)
{
struct net_buf_simple *buf = PROV_BUF(17);
int i = prov_get_pb_index();
BT_DBG("ConfInputs[0] %s", bt_hex(link[i].conf_inputs, 64));
BT_DBG("ConfInputs[64] %s", bt_hex(link[i].conf_inputs + 64, 64));
BT_DBG("ConfInputs[128] %s", bt_hex(link[i].conf_inputs + 128, 17));
#if 0
link[i].conf_salt = (u8_t *)osi_calloc(PROV_CONF_SALT_SIZE);
if (!link[i].conf_salt) {
BT_ERR("Allocate conf_salt memory fail");
goto fail;
}
#endif
#if 0
link[i].conf_key = (u8_t *)osi_calloc(PROV_CONF_KEY_SIZE);
if (!link[i].conf_key) {
BT_ERR("Allocate conf_key memory fail");
goto fail;
}
#endif
if (bt_mesh_prov_conf_salt(link[i].conf_inputs, link[i].conf_salt)) {
BT_ERR("Unable to generate confirmation salt");
goto fail;
}
BT_DBG("ConfirmationSalt: %s", bt_hex(link[i].conf_salt, 16));
if (bt_mesh_prov_conf_key(link[i].dhkey, link[i].conf_salt, link[i].conf_key)) {
BT_ERR("Unable to generate confirmation key");
goto fail;
}
BT_DBG("ConfirmationKey: %s", bt_hex(link[i].conf_key, 16));
/** Provisioner use the same random number for each provisioning
* device, if different random need to be used, here provisioner
* should allocate memory for rand and call bt_rand() every time.
*/
if (!(prov_ctx.pub_key_rand_done & BIT(1))) {
if (bt_rand(prov_ctx.random, 16)) {
BT_ERR("Unable to generate random number");
goto fail;
}
memcpy(link[i].rand, prov_ctx.random, 16);
prov_ctx.pub_key_rand_done |= BIT(1);
} else {
/* Provisioner random has already been generated. */
memcpy(link[i].rand, prov_ctx.random, 16);
}
BT_DBG("LocalRandom: %s", bt_hex(link[i].rand, 16));
prov_buf_init(buf, PROV_CONFIRM);
if (bt_mesh_prov_conf(link[i].conf_key, link[i].rand, link[i].auth,
net_buf_simple_add(buf, 16))) {
BT_ERR("Unable to generate confirmation value");
goto fail;
}
if (prov_send(buf)) {
BT_ERR("Failed to send Provisioning Confirm");
goto fail;
}
link[i].expect = PROV_CONFIRM;
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
int bt_mesh_prov_input_data(u8_t *num, u8_t size, bool num_flag)
{
/** This function should be called in the prov_input_num
* callback, after the data output by device has been
* input by provisioner.
* Paramter size is used to indicate the length of data
* indicated by Pointer num, for example, if device output
* data is 12345678(decimal), the data in auth value will
* be 0xBC614E.
* Parameter num_flag is used to indicate whether the value
* input by provisioner is number or string.
*/
int i = prov_get_pb_index();
if (num == NULL) {
return -EINVAL;
}
if (num_flag) {
/* Provisioner input number */
memset(link[i].auth, 0, 16);
memcpy(link[i].auth + 16 - size, num, size);
} else {
/* Provisioner input string */
memset(link[i].auth, 0, 16);
memcpy(link[i].auth, num, size);
}
return 0;
}
int bt_mesh_prov_output_data(u8_t *num, u8_t size, bool num_flag)
{
/** This function should be called in the prov_output_num
* callback, after the data has been output by provisioner.
* Parameter size is used to indicate the length of data
* indicated by Pointer num, for example, if provisioner
* output data is 12345678(decimal), the data in auth value
* will be 0xBC614E.
* Parameter num_flag is used to indicate whether the value
* output by provisioner is number or string.
*/
int i = prov_get_pb_index();
if (num == NULL) {
return -EINVAL;
}
if (num_flag) {
/* Provisioner output number */
memset(link[i].auth, 0, 16);
memcpy(link[i].auth + 16 - size, num, size);
BT_DBG("auth: %u, %u, %u", size, *num, size);
BT_DBG("auth: %02x, %02x, %02x, %02x", num[0], num[1], num[2], num[3]);
} else {
/* Provisioner output string */
memset(link[i].auth, 0, 16);
memcpy(link[i].auth, num, size);
BT_DBG("auth: %u, %u", size, size);
BT_DBG("auth: %s", num);
}
link[i].expect = PROV_INPUT_COMPLETE;
return 0;
}
static void prov_dh_key_cb(const u8_t key[32])
{
int i = prov_get_pb_index();
BT_DBG("%p", key);
if (!key) {
BT_ERR("DHKey generation failed");
goto fail;
}
#if 0
link[i].dhkey = (u8_t *)osi_calloc(PROV_DH_KEY_SIZE);
if (!link[i].dhkey) {
BT_ERR("Allocate dhkey memory fail");
goto fail;
}
#endif
sys_memcpy_swap(link[i].dhkey, key, 32);
BT_DBG("DHkey: %s", bt_hex(link[i].dhkey, 32));
atomic_set_bit(link[i].flags, HAVE_DHKEY);
/** After dhkey is generated, if auth_method is No OOB or
* Static OOB, provisioner can start to send confirmation.
* If output OOB is used by the device, provisioner need
* to watch out the output number and input it as auth_val.
* If input OOB is used by the device, provisioner need
* to output a value, and wait for prov input complete pdu.
*/
if (prov_auth(link[i].auth_method,
link[i].auth_action, link[i].auth_size) < 0) {
BT_ERR("Prov_auth fail");
goto fail;
}
if (link[i].expect != PROV_INPUT_COMPLETE) {
send_confirm();
}
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static void prov_gen_dh_key(void)
{
u8_t pub_key[64];
int i = prov_get_pb_index();
/* Copy device public key in little-endian for bt_dh_key_gen().
* X and Y halves are swapped independently.
*/
sys_memcpy_swap(&pub_key[0], &link[i].conf_inputs[81], 32);
sys_memcpy_swap(&pub_key[32], &link[i].conf_inputs[113], 32);
if (bt_dh_key_gen(pub_key, prov_dh_key_cb)) {
BT_ERR("Failed to generate DHKey");
close_link(i, CLOSE_REASON_FAILED);
return;
}
}
static void send_pub_key(u8_t oob)
{
struct net_buf_simple *buf = PROV_BUF(65);
const u8_t *key = NULL;
int i = prov_get_pb_index();
if (!(prov_ctx.pub_key_rand_done & BIT(0))) {
key = bt_pub_key_get();
if (!key) {
BT_ERR("No public key available");
close_link(i, CLOSE_REASON_FAILED);
return;
}
BT_DBG("Local Public Key: %s", bt_hex(key, 64));
/** For provisioner, once public key is generated, just store
* public key in prov_ctx, and no need to generate the public
* key during the provisioning of other devices.
*/
memcpy(prov_ctx.public_key, key, 64);
prov_ctx.pub_key_rand_done |= BIT(0);
} else {
/* Provisioner public key has already been generated */
key = prov_ctx.public_key;
}
atomic_set_bit(link[i].flags, LOCAL_PUB_KEY);
prov_buf_init(buf, PROV_PUB_KEY);
/* Swap X and Y halves independently to big-endian */
sys_memcpy_swap(net_buf_simple_add(buf, 32), key, 32);
sys_memcpy_swap(net_buf_simple_add(buf, 32), &key[32], 32);
/* Store provisioner public key value in conf_inputs */
memcpy(&link[i].conf_inputs[17], &buf->data[1], 64);
if (prov_send(buf)) {
BT_ERR("Failed to send public key");
close_link(i, CLOSE_REASON_FAILED);
return;
}
if (!oob) {
link[i].expect = PROV_PUB_KEY;
} else {
/** Have already got device public key. If next is to
* send confirm(not wait for input complete), need to
* wait for transactiona ack for public key then send
* provisioning confirm pdu.
*/
#if defined(CONFIG_BT_MESH_PB_ADV)
if (i < CONFIG_BT_MESH_PBA_SAME_TIME) {
link[i].expect_ack_for = PROV_PUB_KEY;
return;
}
#endif /* CONFIG_BT_MESH_PB_ADV */
prov_gen_dh_key();
}
}
static void prov_pub_key(const u8_t *data)
{
int i = prov_get_pb_index();
BT_DBG("Remote Public Key: %s", bt_hex(data, 64));
/* Make sure received pdu is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
memcpy(&link[i].conf_inputs[81], data, 64);
if (!atomic_test_bit(link[i].flags, LOCAL_PUB_KEY)) {
/* Clear retransmit timer */
#if defined(CONFIG_BT_MESH_PB_ADV)
prov_clear_tx(i);
#endif
atomic_set_bit(link[i].flags, REMOTE_PUB_KEY);
BT_WARN("Waiting for local public key");
return;
}
prov_gen_dh_key();
}
static void prov_input_complete(const u8_t *data)
{
int i = prov_get_pb_index();
BT_DBG("input complete");
/* Make sure received pdu is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
/* Provisioner receives input complete and send confirm */
send_confirm();
}
static void prov_confirm(const u8_t *data)
{
/** Here Zephyr uses PROV_BUF(16). Currently test with PROV_BUF(16)
* and PROV_BUF(17) on branch feature/btdm_ble_mesh_debug both
* work fine.
*/
struct net_buf_simple *buf = PROV_BUF(17);
int i = prov_get_pb_index();
BT_DBG("Remote Confirm: %s", bt_hex(data, 16));
/* Make sure received pdu is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
#if 0
link[i].conf = (u8_t *)osi_calloc(PROV_CONFIRM_SIZE);
if (!link[i].conf) {
BT_ERR("Allocate conf memory fail");
close_link(i, CLOSE_REASON_FAILED);
return;
}
#endif
memcpy(link[i].conf, data, 16);
if (!atomic_test_bit(link[i].flags, HAVE_DHKEY)) {
#if defined(CONFIG_BT_MESH_PB_ADV)
prov_clear_tx(i);
#endif
atomic_set_bit(link[i].flags, SEND_CONFIRM);
}
prov_buf_init(buf, PROV_RANDOM);
net_buf_simple_add_mem(buf, link[i].rand, 16);
if (prov_send(buf)) {
BT_ERR("Failed to send Provisioning Random");
close_link(i, CLOSE_REASON_FAILED);
return;
}
link[i].expect = PROV_RANDOM;
}
static void send_prov_data(void)
{
struct net_buf_simple *buf = PROV_BUF(34);
const u8_t *netkey = NULL;
int i = prov_get_pb_index();
int j, err;
bool already_flag = false;
u8_t session_key[16];
u8_t nonce[13];
u8_t pdu[25];
static u8_t power_on_flag = 0;
u16_t max_addr;
err = bt_mesh_session_key(link[i].dhkey, link[i].prov_salt, session_key);
if (err) {
BT_ERR("Unable to generate session key");
goto fail;
}
BT_DBG("SessionKey: %s", bt_hex(session_key, 16));
err = bt_mesh_prov_nonce(link[i].dhkey, link[i].prov_salt, nonce);
if (err) {
BT_ERR("Unable to generate session nonce");
goto fail;
}
BT_DBG("Nonce: %s", bt_hex(nonce, 13));
/** Assign provisioning data for the device. Currently all provisioned devices
* will be added to primary subnet, and may add API to let users choose which
* subnet will the device be provisioned to later.
*/
if (TEMP_PROV_FLAG_GET()) {
netkey = temp_prov.net_key;
if (!netkey) {
BT_ERR("Unable to get netkey for provisioning data");
goto fail;
}
memcpy(pdu, netkey, 16);
sys_put_be16(temp_prov.net_idx, &pdu[16]);
pdu[18] = temp_prov.flags;
sys_put_be32(temp_prov.iv_index, &pdu[19]);
} else {
netkey = provisioner_net_key_get(prov_ctx.curr_net_idx);
if (!netkey) {
BT_ERR("Unable to get netkey for provisioning data");
goto fail;
}
memcpy(pdu, netkey, 16);
sys_put_be16(prov_ctx.curr_net_idx, &pdu[16]);
pdu[18] = prov_ctx.curr_flags;
sys_put_be32(prov_ctx.curr_iv_index, &pdu[19]);
}
/** 1. Check if this device is a previously deleted device,
* or a device has bot been deleted but been reset, if
* so, reuse the unicast address assigned to this device
* before, see Mesh Spec Provisioning 5.4.2.5.
* 2. The Provisioner must not reuse unicast addresses
* that have been allocated to a device and sent in a
* Provisioning Data PDU until the Provisioner receives
* an Unprovisioned Device beacon or Service Data for
* the Mesh Provisioning Service from that same device,
* identified using the Device UUID of the device.
* 3. And once the provisioning data for the device has
* been sent, we will add the data sent to this device
* into the already_prov_info structure.
* 4. Currently we don't deal with a situation which is:
* a device is re-provisioned, but the element num has
* changed.
*/
/* Check if this device is a re-provisioned device */
for (j = 0; j < BT_MESH_ALREADY_PROV_NUM; j++) {
if (memcmp(link[i].uuid, prov_ctx.already_prov[j].uuid, 16) == 0) {
already_flag = true;
sys_put_be16(prov_ctx.already_prov[j].unicast_addr, &pdu[23]);
link[i].unicast_addr = prov_ctx.already_prov[j].unicast_addr;
break;
}
}
max_addr = TEMP_PROV_FLAG_GET() ? temp_prov.unicast_addr_max : 0x7FFF;
if (!already_flag) {
/* If this device to be provisioned is a new device */
if (!prov_ctx.current_addr) {
BT_ERR("No unicast address can be assigned for this device");
goto fail;
}
if (prov_ctx.current_addr + link[i].element_num - 1 > max_addr) {
BT_ERR("Not enough unicast address for this device");
goto fail;
}
//to avoid the provisioner assign the same unicast_addr to two nodes
if (!power_on_flag) {
BT_DBG("current addr:%04x,max restore addr:%04x\r\n", prov_ctx.current_addr + link[i].element_num - 1, g_restore_max_mac);
prov_ctx.current_addr = g_restore_max_mac + 1;
power_on_flag = 1;
}
sys_put_be16(prov_ctx.current_addr, &pdu[23]);
link[i].unicast_addr = prov_ctx.current_addr;
}
prov_buf_init(buf, PROV_DATA);
err = bt_mesh_prov_encrypt(session_key, nonce, pdu, net_buf_simple_add(buf, 33));
if (err) {
BT_ERR("Unable to encrypt provisioning data");
goto fail;
}
if (prov_send(buf)) {
BT_ERR("Failed to send Provisioning Data");
goto fail;
} else {
/** If provisioning data is sent successfully, add
* the assigned information into the already_prov_info
* structure if this device is new.
* Also, if send successfully, update the current_addr
* in prov_ctx structure.
*/
if (!already_flag) {
for (j = 0; j < BT_MESH_ALREADY_PROV_NUM; j++) {
if (!prov_ctx.already_prov[j].element_num) {
memcpy(prov_ctx.already_prov[j].uuid, link[i].uuid, 16);
prov_ctx.already_prov[j].element_num = link[i].element_num;
prov_ctx.already_prov[j].unicast_addr = link[i].unicast_addr;
break;
}
}
/** We update the next unicast address to be assigned here because
* if provisioner is provisioning two devices at the same time, we
* need to assign the unicast address for them correctly. Hence we
* should not update the prov_ctx.current_addr after the proper
* provisioning complete pdu is received.
*/
prov_ctx.current_addr += link[i].element_num;
if (prov_ctx.current_addr > max_addr) {
/* No unicast address will be used for further provisioning */
prov_ctx.current_addr = 0x0000;
}
}
}
if (TEMP_PROV_FLAG_GET()) {
link[i].ki_flags = temp_prov.flags;
link[i].iv_index = temp_prov.iv_index;
} else {
link[i].ki_flags = prov_ctx.curr_flags;
link[i].iv_index = prov_ctx.curr_iv_index;
}
link[i].expect = PROV_COMPLETE;
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static void prov_random(const u8_t *data)
{
u8_t conf_verify[16];
int i = prov_get_pb_index();
BT_DBG("Remote Random: %s", bt_hex(data, 16));
if (bt_mesh_prov_conf(link[i].conf_key, data, link[i].auth, conf_verify)) {
BT_ERR("Unable to calculate confirmation verification");
goto fail;
}
if (memcmp(conf_verify, link[i].conf, 16)) {
BT_ERR("Invalid confirmation value");
BT_DBG("Received: %s", bt_hex(link[i].conf, 16));
BT_DBG("Calculated: %s", bt_hex(conf_verify, 16));
goto fail;
}
/*Verify received confirm is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
/** After provisioner receives provisioning random from device,
* and successfully check the confirmation, the following
* should be done:
* 1. osi_calloc memory for prov_salt
* 2. calculate prov_salt
* 3. prepare provisioning data and send
*/
#if 0
link[i].prov_salt = (u8_t *)osi_calloc(PROV_PROV_SALT_SIZE);
if (!link[i].prov_salt) {
BT_ERR("Allocate prov_salt memory fail");
goto fail;
}
#endif
if (bt_mesh_prov_salt(link[i].conf_salt, link[i].rand, data,
link[i].prov_salt)) {
BT_ERR("Failed to generate provisioning salt");
goto fail;
}
BT_DBG("ProvisioningSalt: %s", bt_hex(link[i].prov_salt, 16));
send_prov_data();
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static void prov_complete(const u8_t *data)
{
u8_t device_key[16];
int i = prov_get_pb_index(), j;
int err, rm = 0;
bool gatt_flag;
/* Make sure received pdu is ok and cancel the timeout timer */
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
/** If provisioning complete is received, the provisioning device
* will be stored into the node_info structure and become a node
* within the mesh network
*/
err = bt_mesh_dev_key(link[i].dhkey, link[i].prov_salt, device_key);
if (err) {
BT_ERR("Unable to generate device key");
close_link(i, CLOSE_REASON_FAILED);
return;
}
for (j = 0; j < CONFIG_BT_MESH_MAX_PROV_NODES; j++) {
if (!node[j].provisioned) {
node[j].provisioned = true;
node[j].oob_info = link[i].oob_info;
node[j].element_num = link[i].element_num;
node[j].unicast_addr = link[i].unicast_addr;
if (TEMP_PROV_FLAG_GET()) {
node[j].net_idx = temp_prov.net_idx;
} else {
node[j].net_idx = prov_ctx.curr_net_idx;
}
node[j].flags = link[i].ki_flags;
node[j].iv_index = link[i].iv_index;
node[j].addr.type = link[i].addr.type;
memcpy(node[j].addr.a.val, link[i].addr.a.val, 6);
memcpy(node[j].uuid, link[i].uuid, 16);
node[j].provisioned_time = krhino_ticks_to_ms(k_uptime_get_32());
break;
}
}
if (j == CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_ERR("Provisioner prov nodes is full\n");
close_link(i, CLOSE_REASON_FAILED);
return;
}
prov_ctx.node_count++;
err = provisioner_node_provision(j, node[j].uuid, node[j].oob_info, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, node[j].flags,
node[j].iv_index, device_key, node[j].addr.a.val);
if (err) {
BT_ERR("Provisioner store node info in upper layers fail");
close_link(i, CLOSE_REASON_FAILED);
return;
}
if (i >= CONFIG_BT_MESH_PBG_SAME_TIME) {
gatt_flag = true;
} else {
gatt_flag = false;
}
err = provisioner_dev_find(&link[i].addr, link[i].uuid, &rm);
if (!err) {
node[j].auto_add_appkey = unprov_dev[rm].auto_add_appkey;
if (unprov_dev[rm].flags & RM_AFTER_PROV) {
memset(&unprov_dev[rm], 0, sizeof(struct unprov_dev_queue));
provisioner_unprov_dev_num_dec();
}
} else if (err == -ENODEV) {
BT_DBG("%s: Device is not found in queue", __func__);
} else {
BT_WARN("%s: Remove device from queue failed", __func__);
}
if (provisioner->prov_complete) {
provisioner->prov_complete(j, node[j].uuid, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, gatt_flag);
}
BT_DBG("XXXXXXXX==========XXXXXXXXXXX");
close_link(i, CLOSE_REASON_SUCCESS);
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mesh_node(j);
}
}
uint8_t get_node_auto_add_appkey_flag(u16_t unicast_addr)
{
for (int i = 0; i < CONFIG_BT_MESH_MAX_PROV_NODES; i++) {
if (node[i].provisioned && node[i].unicast_addr == unicast_addr) {
return node[i].auto_add_appkey;
}
}
return 0;
}
static void prov_failed(const u8_t *data)
{
int i = prov_get_pb_index();
BT_WARN("Error: 0x%02x", data[0]);
close_link(i, CLOSE_REASON_FAILED);
}
static const struct {
void (*func)(const u8_t *data);
u16_t len;
} prov_handlers[] = {
{ prov_invite, 1 },
{ prov_capabilities, 11 },
{ prov_start, 5 },
{ prov_pub_key, 64 },
{ prov_input_complete, 0 },
{ prov_confirm, 16 },
{ prov_random, 16 },
{ prov_data, 33 },
{ prov_complete, 0 },
{ prov_failed, 1 },
};
static void close_link(int i, u8_t reason)
{
struct bt_conn *conn;
int err;
if (i < CONFIG_BT_MESH_PBA_SAME_TIME) {
#if defined(CONFIG_BT_MESH_PB_ADV)
bearer_ctl_send(i, LINK_CLOSE, &reason, sizeof(reason));
#endif
} else if (i >= CONFIG_BT_MESH_PBA_SAME_TIME &&
i < BT_MESH_PROV_SAME_TIME) {
#if defined(CONFIG_BT_MESH_PB_GATT)
conn = link[i].conn;
if (conn) {
err = bt_conn_disconnect(conn, 0x13);
if (err) {
printf("disconnect err %d\n", err);
}
}
#endif
} else {
BT_ERR("Close link with unexpected link id");
}
}
static void prov_timeout(struct k_work *work)
{
int i = work->index;
BT_DBG("%s", __func__);
close_link(i, CLOSE_REASON_TIMEOUT);
}
#if defined(CONFIG_BT_MESH_PB_ADV)
static void prov_retransmit(struct k_work *work)
{
int id = work->index;
BT_DBG("%s", __func__);
if (!atomic_test_bit(link[id].flags, LINK_ACTIVE)) {
BT_WARN("Link not active");
return;
}
if (k_uptime_get() - link[id].tx.start > TRANSACTION_TIMEOUT) {
BT_WARN("Giving up transaction");
close_link(id, CLOSE_REASON_TIMEOUT);
return;
}
if (link[id].link_close & BIT(0)) {
if (link[id].link_close >> 1 & 0x02) {
reset_link(id, link[id].link_close >> 8);
return;
}
link[id].link_close += BIT(1);
}
for (int i = 0; i < ARRAY_SIZE(link[id].tx.buf); i++) {
struct net_buf *buf = link[id].tx.buf[i];
if (!buf) {
break;
}
if (BT_MESH_ADV(buf)->busy) {
continue;
}
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (i + 1 < ARRAY_SIZE(link[id].tx.buf) && link[id].tx.buf[i + 1]) {
bt_mesh_adv_send(buf, NULL, NULL);
} else {
bt_mesh_adv_send(buf, &buf_sent_cb, (void *)id);
}
}
}
static void link_ack(struct prov_rx *rx, struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
BT_DBG("len %u", buf->len);
if (buf->len) {
BT_ERR("Link ack message length is wrong");
close_link(i, CLOSE_REASON_FAILED);
return;
}
if (link[i].expect == PROV_CAPABILITIES) {
BT_WARN("Link ack already received");
return;
}
#if 0
link[i].conf_inputs = (u8_t *)osi_calloc(PROV_CONF_INPUTS_SIZE);
if (!link[i].conf_inputs) {
BT_ERR("Allocate memory for conf_inputs fail");
close_link(i, CLOSE_REASON_FAILED);
return;
}
#endif
/** After received link_ack, we don't call prov_clear_tx() to
* cancel retransmit timer, because retransmit timer will be
* cancelled after we send the provisioning invite pdu.
*/
send_invite();
}
static void link_close(struct prov_rx *rx, struct net_buf_simple *buf)
{
u8_t reason;
int i = prov_get_pb_index();
BT_DBG("len %u", buf->len);
reason = net_buf_simple_pull_u8(buf);
reset_link(i, reason);
}
static void gen_prov_ctl(struct prov_rx *rx, struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
BT_DBG("op 0x%02x len %u i %u", BEARER_CTL(rx->gpc), buf->len, i);
switch (BEARER_CTL(rx->gpc)) {
case LINK_OPEN:
break;
case LINK_ACK:
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
BT_DBG("flags return");
return;
}
link_ack(rx, buf);
break;
case LINK_CLOSE:
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
return;
}
link_close(rx, buf);
break;
default:
BT_ERR("Unknown bearer opcode: 0x%02x", BEARER_CTL(rx->gpc));
return;
}
}
static void prov_msg_recv(void)
{
int i = prov_get_pb_index();
u8_t type = link[i].rx.buf->data[0];
BT_DBG("type 0x%02x len %u", type, link[i].rx.buf->len);
/** Provisioner first checks information of the received
* provisioing pdu, and once succeed, check the fcs
*/
if (type != PROV_FAILED && type != link[i].expect) {
BT_ERR("Unexpected msg 0x%02x != 0x%02x", type, link[i].expect);
goto fail;
}
if (type >= 0x0A) {
BT_ERR("Unknown provisioning PDU type 0x%02x", type);
goto fail;
}
if (1 + prov_handlers[type].len != link[i].rx.buf->len) {
BT_ERR("Invalid length %u for type 0x%02x", link[i].rx.buf->len, type);
goto fail;
}
if (!bt_mesh_fcs_check(link[i].rx.buf, link[i].rx.fcs)) {
BT_ERR("Incorrect FCS");
goto fail;
}
gen_prov_ack_send(link[i].rx.id);
link[i].rx.prev_id = link[i].rx.id;
link[i].rx.id = 0;
prov_handlers[type].func(&link[i].rx.buf->data[1]);
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static void gen_prov_cont(struct prov_rx *rx, struct net_buf_simple *buf)
{
u8_t seg = CONT_SEG_INDEX(rx->gpc);
int i = prov_get_pb_index();
BT_DBG("len %u, seg_index %u", buf->len, seg);
if (!link[i].rx.seg && link[i].rx.prev_id == rx->xact_id) {
BT_DBG("Resending ack");
gen_prov_ack_send(rx->xact_id);
return;
}
if (rx->xact_id != link[i].rx.id) {
BT_ERR("Data for unknown transaction (%u != %u)",
rx->xact_id, link[i].rx.id);
/** If provisioner receives a unknown tranaction id,
* currently we close the link.
*/
goto fail;
}
if (seg > link[i].rx.last_seg) {
BT_ERR("Invalid segment index %u", seg);
goto fail;
} else if (seg == link[i].rx.last_seg) {
u8_t expect_len;
expect_len = (link[i].rx.buf->len - 20 -
(23 * (link[i].rx.last_seg - 1)));
if (expect_len != buf->len) {
BT_ERR("Incorrect last seg len: %u != %u",
expect_len, buf->len);
goto fail;
}
}
if (!(link[i].rx.seg & BIT(seg))) {
BT_DBG("Ignoring already received segment");
return;
}
memcpy(XACT_SEG_DATA(seg), buf->data, buf->len);
XACT_SEG_RECV(seg);
if (!link[i].rx.seg) {
prov_msg_recv();
}
return;
fail:
close_link(i, CLOSE_REASON_FAILED);
return;
}
static void gen_prov_ack(struct prov_rx *rx, struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
u8_t ack_type, pub_key_oob;
BT_DBG("len %u", buf->len);
if (!link[i].tx.buf[0]) {
return;
}
if (!link[i].tx.id) {
return;
}
if (rx->xact_id == (link[i].tx.id - 1)) {
prov_clear_tx(i);
ack_type = link[i].expect_ack_for;
switch (ack_type) {
case PROV_START:
pub_key_oob = link[i].conf_inputs[13];
send_pub_key(pub_key_oob);
break;
case PROV_PUB_KEY:
prov_gen_dh_key();
break;
default:
break;
}
link[i].expect_ack_for = 0x00;
}
}
static void gen_prov_start(struct prov_rx *rx, struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
if (link[i].rx.seg) {
BT_WARN("Got Start while there are unreceived segments");
return;
}
if (link[i].rx.prev_id == rx->xact_id) {
BT_DBG("Resending ack");
gen_prov_ack_send(rx->xact_id);
return;
}
link[i].rx.buf->len = net_buf_simple_pull_be16(buf);
link[i].rx.id = rx->xact_id;
link[i].rx.fcs = net_buf_simple_pull_u8(buf);
BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len,
START_LAST_SEG(rx->gpc), link[i].rx.buf->len, link[i].rx.fcs);
/* Provisioner can not receive zero-length provisioning pdu */
if (link[i].rx.buf->len < 1) {
BT_ERR("Ignoring zero-length provisioning PDU");
close_link(i, CLOSE_REASON_FAILED);
return;
}
if (link[i].rx.buf->len > link[i].rx.buf->size) {
BT_ERR("Too large provisioning PDU (%u bytes)", link[i].rx.buf->len);
close_link(i, CLOSE_REASON_FAILED);
return;
}
if (START_LAST_SEG(rx->gpc) > 0 && link[i].rx.buf->len <= 20) {
BT_ERR("Too small total length for multi-segment PDU");
close_link(i, CLOSE_REASON_FAILED);
return;
}
link[i].rx.seg = (1 << (START_LAST_SEG(rx->gpc) + 1)) - 1;
link[i].rx.last_seg = START_LAST_SEG(rx->gpc);
memcpy(link[i].rx.buf->data, buf->data, buf->len);
XACT_SEG_RECV(0);
if (!link[i].rx.seg) {
prov_msg_recv();
}
}
static const struct {
void (*const func)(struct prov_rx *rx, struct net_buf_simple *buf);
const u8_t require_link;
const u8_t min_len;
} gen_prov[] = {
{ gen_prov_start, true, 3 },
{ gen_prov_ack, true, 0 },
{ gen_prov_cont, true, 0 },
{ gen_prov_ctl, true, 0 },
};
static void gen_prov_recv(struct prov_rx *rx, struct net_buf_simple *buf)
{
int i = prov_get_pb_index();
if (buf->len < gen_prov[GPCF(rx->gpc)].min_len) {
BT_ERR("Too short GPC message type %u", GPCF(rx->gpc));
close_link(i, CLOSE_REASON_FAILED);
return;
}
/** require_link flag can be used combined with link[].linking flag
* to set LINK_ACTIVE status after link_ack pdu is received.
* And if so, we shall not check LINK_ACTIVE status in the
* function find_link().
*/
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE) &&
gen_prov[GPCF(rx->gpc)].require_link) {
BT_DBG("Ignoring message that requires active link");
return;
}
gen_prov[GPCF(rx->gpc)].func(rx, buf);
}
static int find_link(bt_u32_t link_id, bool set)
{
int i;
/* link for PB-ADV is from 0 to CONFIG_BT_MESH_PBA_SAME_TIME */
for (i = 0; i < CONFIG_BT_MESH_PBA_SAME_TIME; i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
if (link[i].id == link_id) {
if (set) {
prov_set_pb_index(i);
}
return 0;
}
}
}
return -1;
}
void provisioner_pb_adv_recv(struct net_buf_simple *buf)
{
struct prov_rx rx;
int i;
rx.link_id = net_buf_simple_pull_be32(buf);
if (find_link(rx.link_id, true) < 0) {
BT_DBG("Data for unexpected link");
return;
}
i = prov_get_pb_index();
if (buf->len < 2) {
BT_ERR("Too short provisioning packet (len %u)", buf->len);
close_link(i, CLOSE_REASON_FAILED);
return;
}
rx.xact_id = net_buf_simple_pull_u8(buf);
rx.gpc = net_buf_simple_pull_u8(buf);
BT_DBG("link_id 0x%08x xact_id %u", rx.link_id, rx.xact_id);
gen_prov_recv(&rx, buf);
}
#endif /* CONFIG_BT_MESH_PB_ADV */
#if defined(CONFIG_BT_MESH_PB_GATT)
static struct bt_conn *find_conn(struct bt_conn *conn, bool set)
{
int i;
/* link for PB-GATT is from CONFIG_BT_MESH_PBA_SAME_TIME to BT_MESH_PROV_SAME_TIME */
for (i = CONFIG_BT_MESH_PBA_SAME_TIME; i < BT_MESH_PROV_SAME_TIME; i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
if (link[i].conn == conn) {
if (set) {
prov_set_pb_index(i);
}
return conn;
}
}
}
return NULL;
}
int provisioner_pb_gatt_recv(struct bt_conn *conn, struct net_buf_simple *buf)
{
u8_t type;
int i;
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (!find_conn(conn, true)) {
BT_ERR("Data for unexpected connection");
return -ENOTCONN;
}
i = prov_get_pb_index();
if (buf->len < 1) {
BT_ERR("Too short provisioning packet (len %u)", buf->len);
goto fail;
}
type = net_buf_simple_pull_u8(buf);
if (type != PROV_FAILED && type != link[i].expect) {
BT_ERR("Unexpected msg 0x%02x != 0x%02x", type, link[i].expect);
goto fail;
}
if (type >= 0x0A) {
BT_ERR("Unknown provisioning PDU type 0x%02x", type);
goto fail;
}
if (prov_handlers[type].len != buf->len) {
BT_ERR("Invalid length %u for type 0x%02x", buf->len, type);
goto fail;
}
prov_handlers[type].func(buf->data);
return 0;
fail:
/* Mesh Spec Section 5.4.4 Provisioning errors */
close_link(i, CLOSE_REASON_FAILED);
return -EINVAL;
}
int provisioner_set_prov_conn(struct bt_conn *conn, int index)
{
if (!conn || index >= CONFIG_BT_MESH_PBG_SAME_TIME) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
link[CONFIG_BT_MESH_PBA_SAME_TIME + index].conn = bt_conn_ref(conn);
return 0;
}
int provisioner_clear_prov_conn(struct bt_conn *conn)
{
int i;
if (!conn) {
BT_ERR("%s: invalid parameters", __func__);
return -EINVAL;
}
for (i = CONFIG_BT_MESH_PBA_SAME_TIME; i < BT_MESH_PROV_SAME_TIME; i++) {
if (link[i].conn == conn) {
link[i].connecting = false;
bt_conn_unref(link[i].conn);
break;
}
}
return 0;
}
int provisioner_pb_gatt_open(struct bt_conn *conn, u8_t *addr)
{
int i, id = 0;
int err = 0 ;
bt_addr_le_t dev_addr = {0};
int index = 0;
BT_DBG("conn %p", conn);
/** Double check if the device is currently being provisioned
* using PB-ADV.
* Provisioner binds conn with proper device when
* proxy_prov_connected() is invoked, and here after proper GATT
* procedures are completed, we just check if this conn already
* exists in the proxy servers array.
*/
for (i = CONFIG_BT_MESH_PBA_SAME_TIME; i < BT_MESH_PROV_SAME_TIME; i++) {
if (link[i].conn == conn) {
id = i;
break;
}
}
if (i == BT_MESH_PROV_SAME_TIME) {
BT_ERR("%s: no link found", __func__);
return -ENOTCONN;
}
prov_set_pb_index(id);
for (i = 0; i < CONFIG_BT_MESH_PBA_SAME_TIME; i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
if (!memcmp(link[i].uuid, link[id].uuid, 16)) {
BT_ERR("Provision using PB-GATT & PB-ADV same time");
close_link(id, CLOSE_REASON_FAILED);
return -EALREADY;
}
}
}
atomic_set_bit(link[id].flags, LINK_ACTIVE);
//link[id].conn = bt_conn_ref(conn);
/* May use lcd to indicate starting provisioning each device */
memcpy(&dev_addr, &link[i].addr, sizeof(bt_addr_le_t));
err = provisioner_dev_find(&dev_addr, link[i].uuid, &index);
if (err || index > ARRAY_SIZE(unprov_dev)) {
BT_DBG("%s: find dev faild", __func__);
if (provisioner->prov_link_open) {
provisioner->prov_link_open(BT_MESH_PROV_GATT, link[i].addr.a.val, link[i].addr.type, link[i].uuid, 0);
}
} else {
unprov_dev[index].prov_count++;
if (provisioner->prov_link_open) {
provisioner->prov_link_open(BT_MESH_PROV_GATT, link[i].addr.a.val, link[i].addr.type, link[i].uuid, unprov_dev[index].prov_count);
}
}
#if 0
link[id].conf_inputs = (u8_t *)osi_calloc(PROV_CONF_INPUTS_SIZE);
if (!link[id].conf_inputs) {
/* Disconnect this connection, clear corresponding informations */
BT_ERR("Allocate memory for conf_inputs fail");
close_link(id, CLOSE_REASON_FAILED);
return -ENOMEM;
}
#endif
send_invite();
return 0;
}
static void prov_reset_pbg_link(int i)
{
prov_memory_free(i);
memset(&link[i], 0, offsetof(struct prov_link, timeout));
}
int provisioner_pb_gatt_close(struct bt_conn *conn, u8_t reason)
{
bool pub_key;
int i;
int err = 0;
bt_addr_le_t dev_addr;
int index = 0;
BT_DBG("conn %p", conn);
if (!find_conn(conn, true)) {
BT_ERR("Not connected");
return -ENOTCONN;
}
i = prov_get_pb_index();
memcpy(&dev_addr, &link[i].addr, sizeof(bt_addr_le_t));
err = provisioner_dev_find(&dev_addr, link[i].uuid, &index);
if (err || index > ARRAY_SIZE(unprov_dev)) {
BT_DBG("%s: find dev faild", __func__);
if (provisioner->prov_link_close) {
provisioner->prov_link_close(BT_MESH_PROV_GATT, reason, link[i].addr.a.val, link[i].addr.type, link[i].uuid, 0);
}
} else {
if (provisioner->prov_link_close) {
provisioner->prov_link_close(BT_MESH_PROV_GATT, reason, link[i].addr.a.val, link[i].addr.type, link[i].uuid, unprov_dev[index].prov_count);
}
}
if (atomic_test_and_clear_bit(link[i].flags, TIMEOUT_START)) {
k_delayed_work_cancel(&link[i].timeout);
}
pub_key = atomic_test_bit(link[i].flags, LOCAL_PUB_KEY);
prov_reset_pbg_link(i);
if (pub_key) {
atomic_set_bit(link[i].flags, LOCAL_PUB_KEY);
}
return 0;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
int provisioner_prov_init(const struct bt_mesh_provisioner *provisioner_info)
{
int i;
if (!provisioner_info) {
BT_ERR("No provisioning context provided");
return -EINVAL;
}
if (CONFIG_BT_MESH_PBG_SAME_TIME > CONFIG_BT_MAX_CONN) {
BT_ERR("PBG same time exceed max connection");
return -EINVAL;
}
provisioner = provisioner_info;
#if defined(CONFIG_BT_MESH_PB_ADV)
for (i = 0; i < CONFIG_BT_MESH_PBA_SAME_TIME; i++) {
adv_buf[i].buf.size = ADV_BUF_SIZE;
link[i].pending_ack = XACT_NVAL;
k_delayed_work_init(&link[i].tx.retransmit, prov_retransmit);
link[i].tx.retransmit.work.index = i;
link[i].rx.prev_id = XACT_NVAL;
link[i].rx.buf = bt_mesh_pba_get_buf(i);
}
#endif
for (i = 0; i < BT_MESH_PROV_SAME_TIME; i++) {
k_delayed_work_init(&link[i].timeout, prov_timeout);
link[i].timeout.work.index = i;
}
/* for PB-GATT, use servers[] array in proxy_provisioner.c */
prov_ctx.current_addr = provisioner->prov_start_address;
prov_ctx.curr_net_idx = BT_MESH_KEY_PRIMARY;
prov_ctx.curr_flags = provisioner->flags;
prov_ctx.curr_iv_index = provisioner->iv_index;
g_restore_max_mac = provisioner->prov_start_address - 1;
k_sem_init(&prov_input_sem, 0, 1);
return 0;
}
void provisioner_unprov_beacon_recv(struct net_buf_simple *buf)
{
#if defined(CONFIG_BT_MESH_PB_ADV)
const bt_addr_le_t *addr = NULL;
u8_t *dev_uuid = NULL;
u16_t oob_info;
int i, res;
BT_DBG("recv unprov beacon");
if (buf->len != 0x12 && buf->len != 0x16) {
BT_ERR("Unprovisioned device beacon with wrong length");
return;
}
if (prov_ctx.pba_count == CONFIG_BT_MESH_PBA_SAME_TIME) {
BT_DBG("Current PB-ADV devices reach max limit");
return;
}
dev_uuid = buf->data;
if (provisioner_dev_uuid_match(dev_uuid)) {
BT_DBG("%s: dev_uuid not match", __func__);
return;
}
/* Check if the device with this dev_uuid has already been provisioned. */
for (i = 0; i < CONFIG_BT_MESH_MAX_PROV_NODES; i++) {
if (node[i].provisioned) {
/* May also need to check device address and address type */
if (!memcmp(node[i].uuid, dev_uuid, 16)) {
BT_WARN("Provisioned before, start to provision again");
provisioner_node_reset(i);
memset(&node[i], 0, sizeof(struct node_info));
if (prov_ctx.node_count) {
prov_ctx.node_count--;
}
break;
}
}
}
if (prov_ctx.node_count == CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_WARN("Current provisioned devices reach max limit");
return;
}
/* Check if this device is currently being provisioned */
for (i = 0; i < BT_MESH_PROV_SAME_TIME; i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE)) {
if (!memcmp(link[i].uuid, dev_uuid, 16)) {
BT_DBG("This device is currently being provisioned");
return;
}
}
}
if (prov_ctx.prov_after_match == false) {
extern const bt_addr_le_t *bt_mesh_pba_get_addr(void);
addr = bt_mesh_pba_get_addr();
res = provisioner_dev_find(addr, dev_uuid, &i);
if (res) {
BT_DBG("%s: device not found, notify to upper layer", __func__);
/* Invoke callback and notify to upper layer */
net_buf_simple_pull(buf, 16);
oob_info = net_buf_simple_pull_be16(buf);
#if 1
if (adv_pkt_notify && addr) {
adv_pkt_notify(addr->a.val, addr->type, BT_LE_ADV_NONCONN_IND, dev_uuid, oob_info, PROV_ADV);
}
#else
struct bt_mesh_unprov_dev_add add_dev;
u8_t flags;
memcpy(add_dev.addr, addr->a.val, 6);
add_dev.addr_type = addr->type;
add_dev.bearer = PROV_ADV;
add_dev.oob_info = oob_info;
memcpy(add_dev.uuid, dev_uuid, 16);
flags = RM_AFTER_PROV | START_PROV_NOW | FLUSHABLE_DEV;
bt_mesh_provisioner_add_unprov_dev(&add_dev, flags);
#endif
return;
}
if (!(unprov_dev[i].bearer & PROV_ADV)) {
BT_DBG("%s: not support pb-adv", __func__);
return;
}
}
/* Mesh beacon uses big-endian to send beacon data */
for (i = 0; i < CONFIG_BT_MESH_PBA_SAME_TIME; i++) {
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE) && !link[i].linking) {
memcpy(link[i].uuid, dev_uuid, 16);
net_buf_simple_pull(buf, 16);
link[i].oob_info = net_buf_simple_pull_be16(buf);
if (addr) {
link[i].addr.type = addr->type;
memcpy(link[i].addr.a.val, addr->a.val, 6);
}
break;
}
}
if (i == CONFIG_BT_MESH_PBA_SAME_TIME) {
return;
}
/** Once unprovisioned device beacon is received, and previous
* checks are all passed, we can send link_open
*/
prov_set_pb_index(i);
send_link_open();
unprov_dev[i].prov_count++;
if (provisioner->prov_link_open) {
provisioner->prov_link_open(BT_MESH_PROV_ADV, link[i].addr.a.val, link[i].addr.type, link[i].uuid, unprov_dev[i].prov_count);
}
/** If provisioner sets LINK_ACTIVE bit once link_open is sent, here
* we may not need to use linking flag(like PB-GATT) to prevent
* the stored device information(like UUID, oob_info) been replaced
* by other received unprovisioned device beacon.
* But if provisioner sets LINK_ACTIVE bit after link_ack pdu is
* received, we need to use linking flag to prevent information-
* been replaced issue.
* Currently we set LINK_ACTIVE after we send link_open pdu
*/
link[i].linking = 1;
#endif /* CONFIG_BT_MESH_PB_ADV */
}
bool provisioner_flags_match(struct net_buf_simple *buf)
{
u8_t flags;
if (buf->len != 1) {
BT_DBG("%s: Unexpected flags length", __func__);
return false;
}
flags = net_buf_simple_pull_u8(buf);
BT_DBG("Received adv pkt with flags: 0x%02x", flags);
/* Flags context will not be checked curently */
(void)flags;
return true;
}
u16_t provisioner_srv_uuid_recv(struct net_buf_simple *buf)
{
u16_t uuid = 0;
if (buf->len != 2) {
BT_DBG("Length not match mesh service uuid");
return false;
}
uuid = net_buf_simple_pull_le16(buf);
BT_DBG("Received adv pkt with service UUID: %d", uuid);
if ((uuid != BT_UUID_MESH_PROV_VAL) && (uuid != BT_UUID_MESH_PROXY_VAL)) {
return false;
}
return uuid;
}
static void provisioner_prov_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr);
void provisioner_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr, u16_t uuid)
{
u16_t uuid_type;
if (!buf || !addr) {
BT_ERR("%s: invalid parameters", __func__);
return;
}
uuid_type = net_buf_simple_pull_le16(buf);
if (uuid_type != uuid) {
BT_DBG("Received adv pkt with service data uuid: %d", uuid_type);
return;
}
switch (uuid) {
case BT_UUID_MESH_PROV_VAL:
if (buf->len != BT_MESH_PROV_SRV_DATA_LEN) {
BT_ERR("Received adv pkt with prov service data len: %d", buf->len);
return;
}
BT_DBG("Start to deal with provisioning service adv data");
provisioner_prov_srv_data_recv(buf, addr);
break;
case BT_UUID_MESH_PROXY_VAL:
if (buf->len != BT_MESH_PROXY_SRV_DATA_LEN1 &&
buf->len != BT_MESH_PROXY_SRV_DATA_LEN2) {
BT_ERR("Received adv pkt with proxy service data len: %d", buf->len);
return;
}
BT_DBG("Start to deal with proxy service adv data");
provisioner_proxy_srv_data_recv(buf, addr);
break;
default:
break;
}
}
static void provisioner_prov_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr)
{
#if defined(CONFIG_BT_MESH_PB_GATT)
u8_t *dev_uuid;
u16_t oob_info;
int i, res;
if (prov_ctx.pbg_count == CONFIG_BT_MESH_PBG_SAME_TIME) {
BT_DBG("Current PB-GATT devices reach max limit");
return;
}
dev_uuid = buf->data;
BT_DBG("xxxxxx %s: dev_uuid: %02x, %02x, %02x, %02x, %02x, %02x",
__func__,
dev_uuid[0], dev_uuid[1], dev_uuid[2],
dev_uuid[3], dev_uuid[4], dev_uuid[5],
dev_uuid[6], dev_uuid[7]);
if (provisioner_dev_uuid_match(dev_uuid)) {
BT_DBG("%s: dev_uuid not match", __func__);
return;
}
/* Check if the device with this device_uuid has already been provisioned. */
for (i = 0; i < CONFIG_BT_MESH_MAX_PROV_NODES; i++) {
if (node[i].provisioned) {
/* May also need to check device address and address type */
/* unprovision beacons may cached in buffer, so a provisoned node can't provision in 30s, */
if (!memcmp(node[i].uuid, dev_uuid, 16)) {
if ((krhino_ticks_to_ms(k_uptime_get_32()) - node[i].provisioned_time) < K_SECONDS(30)) {
BT_WARN("Node should not reprovison in 30s");
return;
} else {
BT_WARN("Provisioned before, start to provision again");
provisioner_node_reset(i);
memset(&node[i], 0, sizeof(struct node_info));
if (prov_ctx.node_count) {
prov_ctx.node_count--;
}
break;
}
}
}
}
if (prov_ctx.node_count == CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_WARN("Current provisioned devices reach max limit");
return;
}
/** Check if this device is currently being provisioned
* According to Zephyr's device code, if we connect with
* one device and start to provision it, we may still can
* receive the connectable prov adv pkt from this device.
* Here we check both PB-GATT and PB-ADV link status.
*/
for (i = 0; i < BT_MESH_PROV_SAME_TIME; i++) {
if (atomic_test_bit(link[i].flags, LINK_ACTIVE) || link[i].connecting) {
if (!memcmp(link[i].uuid, dev_uuid, 16)) {
BT_DBG("This device is currently being provisioned");
return;
}
}
}
if (prov_ctx.prov_after_match == false) {
res = provisioner_dev_find(addr, dev_uuid, &i);
if (res) {
BT_DBG("%s: device not found, notify to upper layer", __func__);
/* Invoke callback and notify to upper layer */
net_buf_simple_pull(buf, 16);
oob_info = net_buf_simple_pull_be16(buf);
#if 1
if (adv_pkt_notify && addr) {
adv_pkt_notify(addr->a.val, addr->type, BT_LE_ADV_IND, dev_uuid, oob_info, PROV_GATT);
}
#else
struct bt_mesh_unprov_dev_add add_dev;
u8_t flags;
memcpy(add_dev.addr, addr->a.val, 6);
add_dev.addr_type = addr->type;
add_dev.bearer = PROV_GATT;
add_dev.oob_info = oob_info;
memcpy(add_dev.uuid, dev_uuid, 16);
flags = RM_AFTER_PROV | START_PROV_NOW | FLUSHABLE_DEV;
bt_mesh_provisioner_add_unprov_dev(&add_dev, flags);
#endif
return;
}
if (!(unprov_dev[i].bearer & PROV_GATT)) {
BT_DBG("%s: not support pb-gatt", __func__);
return;
}
}
/** If previous checks succeed, we will copy the device uuid
* and oob info into an unused link structure, and at this
* moment, the link has not been activated. Even if we re-
* ceived an unprovisioned device beacon and a connectable
* provisioning adv pkt from a device at the same time, copy
* information received in each adv pkt into two links will
* not effect the final provisioning of this device, because
* no matter which one among PB-GATT and PB-ADV is activated
* first, the other PB will be dropped, and the link structure
* occupied by the dropped PB will be used by other devices (
* because the link is not activated).
* Use connecting flag to prevent if two devices's adv pkts are
* both received, the previous one info will be replaced by the
* second one.
* Another way:
* During creating connection and doing the following GATT
* procedures, disable scanning for this period. But this may
* affect PB-ADV procedure if PB-GATT and PB-ADV are used at
* the same time.
*/
for (i = CONFIG_BT_MESH_PBA_SAME_TIME; i < BT_MESH_PROV_SAME_TIME; i++) {
if (!atomic_test_bit(link[i].flags, LINK_ACTIVE) && !link[i].connecting) {
memcpy(link[i].uuid, dev_uuid, 16);
net_buf_simple_pull(buf, 16);
link[i].oob_info = net_buf_simple_pull_le16(buf);
if (addr) {
link[i].addr.type = addr->type;
memcpy(link[i].addr.a.val, addr->a.val, 6);
}
break;
}
}
if (i == BT_MESH_PROV_SAME_TIME) {
return;
}
if (true != bt_prov_check_gattc_id(i - CONFIG_BT_MESH_PBA_SAME_TIME, &link[i].addr)
|| bt_gattc_conn_create(i - CONFIG_BT_MESH_PBA_SAME_TIME, BT_UUID_16(BT_UUID_MESH_PROV)->val)) {
memset(link[i].uuid, 0, 16);
link[i].oob_info = 0x0;
memset(&link[i].addr, 0, sizeof(link[i].addr));
return;
}
link[i].connecting = true;
#endif /* CONFIG_BT_MESH_PB_GATT */
}
int bt_mesh_provisioner_local_provision()
{
const u8_t *net_key = NULL;
u8_t netkey[16];
u8_t dev_key[16];
int err;
int j;
const struct bt_mesh_comp *comp = NULL;
const struct bt_mesh_prov *prov = NULL;
extern const struct bt_mesh_comp *bt_mesh_comp_get(void);
extern const struct bt_mesh_prov *bt_mesh_prov_get(void);
comp = bt_mesh_comp_get();
prov = bt_mesh_prov_get();
if (!comp || !prov) {
BT_ERR("%s: Provisioner comp or prov is NULL", __func__);
return -EINVAL;
}
if (atomic_test_and_set_bit(bt_mesh.flags, BT_MESH_VALID)) {
return -EALREADY;
}
net_key = provisioner_net_key_get(prov_ctx.curr_net_idx);
if (!net_key) {
bt_rand(netkey, 16);
net_key = netkey;
BT_DBG("generate netkey %s\n", bt_hex(net_key, 16));
}
err = bt_mesh_net_create(prov_ctx.curr_net_idx, prov_ctx.curr_flags, net_key, prov_ctx.curr_iv_index);
if (err) {
atomic_clear_bit(bt_mesh.flags, BT_MESH_VALID);
return err;
}
extern void bt_mesh_comp_provision(u16_t addr);
bt_mesh_comp_provision(provisioner->prov_unicast_addr);
bt_rand(dev_key, 16);
memcpy(bt_mesh.dev_key, dev_key, 16);
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
BT_DBG("Storing network information persistently");
bt_mesh_store_net();
bt_mesh_store_subnet(&bt_mesh.sub[0], 0);
bt_mesh_store_iv(false);
}
struct bt_le_oob oob = {0};
bt_le_oob_get_local(0, &oob);
for (j = 0; j < CONFIG_BT_MESH_MAX_PROV_NODES; j++) {
if (!node[j].provisioned) {
node[j].provisioned = true;
node[j].oob_info = prov->oob_info;
node[j].element_num = comp->elem_count;
node[j].unicast_addr = provisioner->prov_unicast_addr;
node[j].net_idx = prov_ctx.curr_net_idx;
node[j].flags = prov_ctx.curr_flags;
node[j].iv_index = prov_ctx.curr_iv_index;
node[j].addr = oob.addr;
memcpy(node[j].uuid, prov->uuid, 16);
node[j].provisioned_time = krhino_ticks_to_ms(k_uptime_get_32());
break;
}
}
if (j == CONFIG_BT_MESH_MAX_PROV_NODES) {
BT_ERR("Provisioner prov nodes is full\n");
return -ENOMEM;
}
err = provisioner_node_provision(j, node[j].uuid, node[j].oob_info, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, node[j].flags,
node[j].iv_index, dev_key, node[j].addr.a.val);
if (err) {
BT_ERR("Provisioner store node info in upper layers fail");
return err;
}
if (provisioner->prov_complete) {
provisioner->prov_complete(j, node[j].uuid, node[j].unicast_addr,
node[j].element_num, node[j].net_idx, 0);
}
prov_ctx.node_count++;
if (node[j].unicast_addr + node[j].element_num > prov_ctx.current_addr) {
prov_ctx.current_addr = node[j].unicast_addr + node[j].element_num;
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_mesh_node(j);
}
return 0;
}
#endif /* CONFIG_BT_MESH_PROVISIONER */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/provisioner_prov.c | C | apache-2.0 | 110,563 |
// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ble_os.h>
#include <api/mesh.h>
#ifdef CONFIG_BT_MESH_PROVISIONER
#include <bt_errno.h>
#include <atomic.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/conn.h>
//#include "mesh_def.h"
#include "bluetooth/gatt.h"
#include "bluetooth/uuid.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROXY)
#include "common/log.h"
#include <host/conn_internal.h>
#include "adv.h"
#include "net.h"
#include "access.h"
#include "beacon.h"
#include "foundation.h"
#include "provisioner_main.h"
#include "provisioner_prov.h"
#include "provisioner_proxy.h"
#include "provisioner_beacon.h"
#include "mesh_hal_ble.h"
//#include "bt_mesh_custom_log.h"
#define PDU_TYPE(data) (data[0] & BIT_MASK(6))
#define PDU_SAR(data) (data[0] >> 6)
#define SAR_COMPLETE 0x00
#define SAR_FIRST 0x01
#define SAR_CONT 0x02
#define SAR_LAST 0x03
#define CFG_FILTER_SET 0x00
#define CFG_FILTER_ADD 0x01
#define CFG_FILTER_REMOVE 0x02
#define CFG_FILTER_STATUS 0x03
#define PDU_HDR(sar, type) (sar << 6 | (type & BIT_MASK(6)))
#define SERVER_BUF_SIZE 68
#define ID_TYPE_NET 0x00
#define ID_TYPE_NODE 0x01
#define NODE_ID_LEN 19
#define NET_ID_LEN 11
#define CLOSE_REASON_PROXY 0xFF
static int conn_count;
static struct bt_mesh_proxy_server {
struct bt_conn *conn;
/* Provisioner can use filter to double check the dst within mesh messages */
u16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE];
enum __packed {
NONE,
WHITELIST,
BLACKLIST,
PROV,
} filter_type;
u8_t msg_type;
struct net_buf_simple buf;
u8_t server_buf_data[SERVER_BUF_SIZE];
} servers[CONFIG_BT_MESH_PBG_SAME_TIME] = { 0 };
static struct bt_mesh_proxy_server *find_server(struct bt_conn *conn)
{
int i;
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn == conn) {
return &servers[i];
}
}
return NULL;
}
static int filter_status(struct bt_mesh_proxy_server *server, struct net_buf_simple *buf)
{
/* TODO: Deal with received proxy configuration status messages */
return 0;
}
#if 0
static void send_filter_set(struct bt_mesh_proxy_server *server,
struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
/* TODO: Act as proxy client, send proxy configuration set messages */
}
static void send_filter_add(struct bt_mesh_proxy_server *server,
struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
/* TODO: Act as proxy client, send proxy configuration add messages */
}
static void send_filter_remove(struct bt_mesh_proxy_server *server,
struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
/* TODO: Act as proxy client, send proxy configuration remove messages */
}
#endif
static void proxy_cfg(struct bt_mesh_proxy_server *server)
{
struct net_buf_simple *buf = NET_BUF_SIMPLE(29);
struct bt_mesh_net_rx rx;
u8_t opcode;
int err;
/** In order to deal with proxy configuration messages, provisioner should
* do sth. like create mesh network after each device is provisioned.
*/
err = bt_mesh_net_decode(&server->buf, BT_MESH_NET_IF_PROXY_CFG, &rx, buf);
if (err) {
BT_ERR("Failed to decode Proxy Configuration (err %d)", err);
return;
}
/* Remove network headers */
net_buf_simple_pull(buf, BT_MESH_NET_HDR_LEN);
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
if (buf->len < 1) {
BT_WARN("Too short proxy configuration PDU");
return;
}
opcode = net_buf_simple_pull_u8(buf);
switch (opcode) {
case CFG_FILTER_STATUS:
filter_status(server, buf);
break;
default:
BT_WARN("Unhandled configuration OpCode 0x%02x", opcode);
break;
}
}
static void proxy_complete_pdu(struct bt_mesh_proxy_server *server)
{
switch (server->msg_type) {
#if defined(CONFIG_BT_MESH_GATT_PROXY)
case BT_MESH_PROXY_NET_PDU:
BT_DBG("Mesh Network PDU");
bt_mesh_net_recv(&server->buf, 0, BT_MESH_NET_IF_PROXY);
break;
case BT_MESH_PROXY_BEACON:
BT_DBG("Mesh Beacon PDU");
provisioner_beacon_recv(&server->buf);
break;
case BT_MESH_PROXY_CONFIG:
BT_DBG("Mesh Configuration PDU");
proxy_cfg(server);
break;
#endif
#if defined(CONFIG_BT_MESH_PB_GATT)
case BT_MESH_PROXY_PROV:
BT_DBG("Mesh Provisioning PDU");
provisioner_pb_gatt_recv(server->conn, &server->buf);
break;
#endif
default:
BT_WARN("Unhandled Message Type 0x%02x", server->msg_type);
break;
}
net_buf_simple_init(&server->buf, 0);
}
#define ATTR_IS_PROV(uuid) (uuid == BT_UUID_MESH_PROV_VAL)
static ssize_t proxy_recv(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len,
u16_t offset, u8_t flags)
{
struct bt_mesh_proxy_server *server = find_server(conn);
const u8_t *data = buf;
u16_t srvc_uuid = 0;
if (!server) {
return -ENOTCONN;
}
if (len < 1) {
BT_WARN("Too small Proxy PDU");
return -EINVAL;
}
srvc_uuid = bt_mesh_get_srvc_uuid(conn);
if (!srvc_uuid) {
BT_ERR("No service uuid found");
return -ENOTCONN;
}
if (ATTR_IS_PROV(srvc_uuid) != (PDU_TYPE(data) == BT_MESH_PROXY_PROV)) {
BT_WARN("Proxy PDU type doesn't match GATT service uuid");
return -EINVAL;
}
if (len - 1 > net_buf_simple_tailroom(&server->buf)) {
BT_WARN("Too big proxy PDU");
return -EINVAL;
}
switch (PDU_SAR(data)) {
case SAR_COMPLETE:
if (server->buf.len) {
BT_WARN("Complete PDU while a pending incomplete one");
return -EINVAL;
}
server->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
proxy_complete_pdu(server);
break;
case SAR_FIRST:
if (server->buf.len) {
BT_WARN("First PDU while a pending incomplete one");
return -EINVAL;
}
server->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
break;
case SAR_CONT:
if (!server->buf.len) {
BT_WARN("Continuation with no prior data");
return -EINVAL;
}
if (server->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in continuation");
return -EINVAL;
}
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
break;
case SAR_LAST:
if (!server->buf.len) {
BT_WARN("Last SAR PDU with no prior data");
return -EINVAL;
}
if (server->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in last SAR PDU");
return -EINVAL;
}
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
proxy_complete_pdu(server);
break;
}
return len;
}
struct k_sem proxy_complete_sem;
static void proxy_open_complete(struct bt_conn *conn)
{
struct bt_mesh_proxy_server *server;
server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server found");
return;
}
if (server->filter_type == NONE) {
server->filter_type = WHITELIST;
}
k_sem_give(&proxy_complete_sem);
return;
}
static void prov_open_complete(struct bt_conn *conn)
{
struct bt_mesh_proxy_server *server;
server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server found");
return;
}
if (server->filter_type == NONE) {
server->filter_type = PROV;
provisioner_pb_gatt_open(conn, NULL);
}
}
static void proxy_prov_connected(struct bt_conn *conn, u8_t err)
{
if (!bt_mesh_is_provisioner_en()) {
return;
}
struct bt_mesh_proxy_server *server = NULL;
int id = bt_prov_get_gattc_id(conn->le.dst.a.val);
conn_count++;
BT_DBG("proxy connected conn 0x%x, err %d", conn, err);
if (err) {
conn_count--;
provisioner_clear_connecting(0);
provisioner_pbg_count_dec();
bt_mesh_scan_enable();
BT_WARN("proxy connect err %d", err);
return;
}
if (id < 0) {
bt_conn_disconnect(conn, 0x13);
bt_mesh_scan_enable();
BT_ERR("No matching gattc info");
return;
}
if (!servers[id].conn) {
server = &servers[id];
}
if (!server) {
BT_ERR("No matching Proxy Client objects");
/** Disconnect current connection, clear part of prov_link
* information, like uuid, dev_addr, linking flag, etc.
*/
bt_conn_disconnect(conn, 0x13);
bt_mesh_scan_enable();
return;
}
server->conn = bt_conn_ref(conn);
server->filter_type = NONE;
memset(server->filter, 0, sizeof(server->filter));
net_buf_simple_init(&server->buf, 0);
if (BT_UUID_MESH_PROXY_VAL == bt_mesh_get_srvc_uuid(server->conn)) {
bt_mesh_gatt_conn_open(server->conn, proxy_open_complete);
} else if (BT_UUID_MESH_PROV_VAL == bt_mesh_get_srvc_uuid(server->conn)) {
if (provisioner_set_prov_conn(server->conn, id)) {
BT_ERR("%s: Fail to set prov_conn", __func__);
bt_mesh_conn_disconnect(server->conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
return;
}
bt_mesh_gatt_conn_open(server->conn, prov_open_complete);
}
}
static void proxy_prov_disconnected(struct bt_conn *conn, u8_t reason)
{
int i;
if (!bt_mesh_is_provisioner_en()) {
return;
}
BT_DBG("conn %p, handle is %d, reason 0x%02x", conn, conn->handle, reason);
if (conn_count) {
conn_count--;
}
provisioner_pbg_count_dec();
bt_mesh_scan_enable();
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
if (server->conn == conn) {
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) {
provisioner_clear_prov_conn(conn);
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && server->filter_type == PROV) {
provisioner_pb_gatt_close(conn, reason);
}
if (server->conn) {
bt_conn_unref(server->conn);
}
server->conn = NULL;
break;
}
}
}
#if defined(CONFIG_BT_MESH_PB_GATT)
ssize_t prov_write_ccc_descr(struct bt_conn *conn, u8_t *addr)
{
struct bt_mesh_proxy_server *server;
server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server found");
return -ENOTCONN;
}
if (server->filter_type == NONE) {
server->filter_type = PROV;
return provisioner_pb_gatt_open(conn, addr);
}
return -EINVAL;
}
ssize_t prov_notification(struct bt_conn *conn, u8_t *data, u16_t len)
{
struct bt_mesh_proxy_server *server;
server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server found");
return -ENOTCONN;
}
if (server->filter_type == PROV) {
return proxy_recv(conn, NULL, data, len, 0, 0);
}
return -EINVAL;
}
int provisioner_pb_gatt_enable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn) {
servers[i].filter_type = PROV;
}
}
return 0;
}
int provisioner_pb_gatt_disable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
if (server->conn && server->filter_type == PROV) {
bt_mesh_conn_disconnect(server->conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
server->filter_type = NONE;
}
}
return 0;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
#if defined(CONFIG_BT_MESH_GATT_PROXY)
ssize_t proxy_write_ccc_descr(struct bt_conn *conn)
{
struct bt_mesh_proxy_server *server;
server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server found");
return -ENOTCONN;
}
if (server->filter_type == NONE) {
server->filter_type = WHITELIST;
return 0;
}
return -EINVAL;
}
ssize_t proxy_notification(struct bt_conn *conn, u8_t *data, u16_t len)
{
return proxy_recv(conn, NULL, data, len, 0, 0);
}
/** Currently provisioner does't need bt_mesh_provisioner_proxy_enable()
* and bt_mesh_provisioner_proxy_disable() functions, and once they are
* used, provisioner can be enabled to parse node_id_adv and net_id_adv
* in order to support proxy client role.
* And if gatt_proxy is disabled, provisioner can stop dealing with
* these two kinds of connectable advertising packets.
*/
int bt_mesh_provisioner_proxy_enable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn) {
servers[i].filter_type = WHITELIST;
}
}
/** TODO: Once at leat one device has been provisioned, provisioner
* can be set to allow receiving and parsing node_id & net_id adv
* packets, and we may use a global flag to indicate this.
*/
return 0;
}
static void bt_mesh_proxy_gatt_proxy_disconnect(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
if (server->conn && (server->filter_type == WHITELIST || server->filter_type == BLACKLIST)) {
server->filter_type = NONE;
bt_conn_disconnect(server->conn, 0x13);
}
}
}
int bt_mesh_provisioner_proxy_disable(void)
{
BT_DBG("%s", __func__);
/** TODO: Once this function is invoked, provisioner shall stop
* receiving and parsing node_id & net_id adv packets, and if
* proxy connection exists, we should disconnect it.
*/
bt_mesh_proxy_gatt_proxy_disconnect();
return 0;
}
#endif /* CONFIG_BT_MESH_GATT_PROXY */
static int proxy_send(struct bt_conn *conn, const void *data, u16_t len)
{
BT_DBG("%u bytes: %s", len, bt_hex(data, len));
#if defined(CONFIG_BT_MESH_GATT_PROXY) || defined(CONFIG_BT_MESH_PB_GATT)
u16_t handle = bt_gatt_get_data_in_handle(conn);
return bt_gatt_write_without_response(conn, handle, data, len, false);
#endif
return 0;
}
static int proxy_prov_segment_and_send(struct bt_conn *conn, u8_t type, struct net_buf_simple *msg)
{
u16_t mtu;
BT_DBG("conn %p type 0x%02x len %u: %s", conn, type, msg->len, bt_hex(msg->data, msg->len));
mtu = bt_gatt_prov_get_mtu(conn);
if (!mtu) {
BT_ERR("Conn used to get mtu does not exist");
return -ENOTCONN;
}
/* ATT_MTU - OpCode (1 byte) - Handle (2 bytes) */
mtu -= 3;
if (mtu > msg->len) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_COMPLETE, type));
return proxy_send(conn, msg->data, msg->len);
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_FIRST, type));
proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
while (msg->len) {
if (msg->len + 1 < mtu) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_LAST, type));
proxy_send(conn, msg->data, msg->len);
break;
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_CONT, type));
proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
}
return 0;
}
int provisioner_proxy_send(struct bt_conn *conn, u8_t type, struct net_buf_simple *msg)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_DBG("No Proxy Server found");
return -ENOTCONN;
}
if ((server->filter_type == PROV) != (type == BT_MESH_PROXY_PROV)) {
BT_WARN("Invalid PDU type for PROV Client");
return -EINVAL;
}
if ((server->filter_type == WHITELIST) != (type == BT_MESH_PROXY_NET_PDU)) {
BT_WARN("Invalid PDU type for PROXY Client %u", server->filter_type);
return -EINVAL;
}
return proxy_prov_segment_and_send(conn, type, msg);
}
int provisioner_proxy_pdu_send(struct net_buf_simple *msg)
{
struct bt_conn *conn;
conn = bt_mesh_get_curr_conn();
if (conn == NULL) {
return -EINVAL;
}
return provisioner_proxy_send(conn, BT_MESH_PROXY_NET_PDU, msg);
}
static struct bt_conn_cb conn_callbacks = {
.connected = proxy_prov_connected,
.disconnected = proxy_prov_disconnected,
};
extern u8_t prov_addr;
void provisioner_proxy_srv_data_recv(struct net_buf_simple *buf, const bt_addr_le_t *addr)
{
/** TODO: Parse node_id_adv or net_id_adv pkts. Currently we
* don't support this function, and if realized later, proxy
* client need to check if there is server structure left
* before create connection with a server.
* check conn_count & CONFIG_BT_MESH_PBG_SAME_TIME
*/
if (provisioner_is_node_provisioned(addr->a.val) && addr->a.val[0] == prov_addr) {
int gattc_id = 0;
//gattc_id = bt_prov_get_gattc_id(addr->a.val);
set_my_addr(gattc_id, addr->a.val, addr->type);
if (gattc_id >= 0) {
//bt_gattc_conn_create(gattc_id, BT_UUID_MESH_PROXY_VAL);
}
}
return;
}
void send_my_proxy_config(u8_t opcode, u8_t *data)
{
struct bt_mesh_proxy_server *server;
server = &servers[0];
struct net_buf_simple *buf = NET_BUF_SIMPLE(29);
struct bt_mesh_msg_ctx cur_ctx = { 0 };
struct bt_mesh_net_tx tx = {
.sub = &(bt_mesh.sub[0]),
.ctx = &cur_ctx,
.src = bt_mesh_primary_addr(),
};
int err;
if (!server) {
BT_ERR("No Proxy Server found");
return;
}
tx.ctx->app_idx = BT_MESH_KEY_UNUSED;
tx.ctx->send_ttl = 0;
//u16_t addr = 1;
/* Configuration messages always have dst unassigned */
tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED;
//init
net_buf_simple_init(buf, 10);
//opcode
net_buf_simple_add_u8(buf, opcode);
//data
switch (opcode) {
case CFG_FILTER_SET:
net_buf_simple_add_u8(buf, data[0]);
break;
case CFG_FILTER_ADD:
net_buf_simple_add_be16(buf, *(u16_t *)data);
break;
case CFG_FILTER_REMOVE:
net_buf_simple_add_be16(buf, *(u16_t *)data);
break;
}
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
err = bt_mesh_net_encode(&tx, buf, true);
if (err) {
BT_ERR("Encoding Proxy cfg message failed (err %d)", err);
return;
}
err = proxy_prov_segment_and_send(server->conn, BT_MESH_PROXY_CONFIG, buf);
if (err) {
BT_ERR("Failed to send proxy cfg message (err %d)", err);
}
}
void send_white_list(u8_t index)
{
u8_t wl = 0;
u16_t src = bt_mesh_primary_addr();
switch (index) {
case 1:
send_my_proxy_config(CFG_FILTER_SET, &wl);
send_my_proxy_config(CFG_FILTER_ADD, (u8_t *)&src);
break;
case 2:
send_my_proxy_config(CFG_FILTER_REMOVE, (u8_t *)&src);
break;
}
BT_DBG("%d", index);
}
int provisioner_proxy_init(void)
{
int i;
/* Initialize the server receive buffers */
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
server->conn = NULL;
server->buf.size = SERVER_BUF_SIZE;
}
bt_conn_cb_register(&conn_callbacks);
bt_mesh_gatt_recv_callback(proxy_recv);
return 0;
}
#endif /* CONFIG_BT_MESH_PROVISIONER */
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/provisioner_proxy.c | C | apache-2.0 | 20,368 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/conn.h>
#include <bluetooth/gatt.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROXY)
#include "common/log.h"
#include "mesh.h"
#include "adv.h"
#include "net.h"
#include "prov.h"
#include "beacon.h"
#include "foundation.h"
#include "access.h"
#include "proxy.h"
#include "bt_errno.h"
#ifdef CONFIG_GENIE_OTA
#include "genie_crypto.h"
#include "genie_ais.h"
#endif
#ifdef CONFIG_GENIE_OTA
extern int genie_ota_pre_init(void);
extern void genie_ais_adv_init(uint8_t ad_structure[14], uint8_t is_silent);
#endif
#ifdef CONFIG_BT_MESH_GATT_PROXY
#define PDU_TYPE(data) (data[0] & BIT_MASK(6))
#define PDU_SAR(data) (data[0] >> 6)
#define SAR_COMPLETE 0x00
#define SAR_FIRST 0x01
#define SAR_CONT 0x02
#define SAR_LAST 0x03
#define CFG_FILTER_SET 0x00
#define CFG_FILTER_ADD 0x01
#define CFG_FILTER_REMOVE 0x02
#define CFG_FILTER_STATUS 0x03
#define PDU_HDR(sar, type) (sar << 6 | (type & BIT_MASK(6)))
#define CLIENT_BUF_SIZE 68
#if defined(CONFIG_BT_MESH_DEBUG_USE_ID_ADDR)
#define ADV_OPT (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME | BT_LE_ADV_OPT_USE_IDENTITY)
#else
#define ADV_OPT (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME)
#endif
#if defined(CONFIG_BT_MESH_PB_GATT)
static const struct bt_le_adv_param slow_adv_param = {
.options = ADV_OPT,
#ifdef CONFIG_GENIE_MESH_ENABLE
.interval_min = BT_GAP_ADV_FAST_INT_MIN_2,
.interval_max = BT_GAP_ADV_FAST_INT_MAX_2,
#else
.interval_min = BT_GAP_ADV_SLOW_INT_MIN,
.interval_max = BT_GAP_ADV_SLOW_INT_MAX,
#endif
};
#endif
static const struct bt_le_adv_param fast_adv_param = {
.options = ADV_OPT,
.interval_min = BT_GAP_ADV_FAST_INT_MIN_2,
.interval_max = BT_GAP_ADV_FAST_INT_MAX_2,
};
static bool proxy_adv_enabled;
#if defined(CONFIG_BT_MESH_GATT_PROXY)
static void proxy_send_beacons(struct k_work *work);
static u16_t proxy_ccc_val;
#endif
#if defined(CONFIG_BT_MESH_PB_GATT)
static u16_t prov_ccc_val;
static bool prov_fast_adv;
#endif
static struct bt_mesh_proxy_client {
struct bt_conn *conn;
u16_t filter[CONFIG_BT_MESH_PROXY_FILTER_SIZE];
enum __packed {
NONE,
WHITELIST,
BLACKLIST,
PROV,
} filter_type;
u8_t msg_type;
#if defined(CONFIG_BT_MESH_GATT_PROXY)
struct k_work send_beacons;
#endif
struct net_buf_simple buf;
} clients[CONFIG_BT_MAX_CONN] = {
[0 ... (CONFIG_BT_MAX_CONN - 1)] = {
#if defined(CONFIG_BT_MESH_GATT_PROXY)
// .send_beacons = _K_WORK_INITIALIZER(proxy_send_beacons),
#endif
},
};
static u8_t __noinit client_buf_data[CLIENT_BUF_SIZE * CONFIG_BT_MAX_CONN];
/* Track which service is enabled */
static enum {
MESH_GATT_NONE,
MESH_GATT_PROV,
MESH_GATT_PROXY,
} gatt_svc = MESH_GATT_NONE;
static struct bt_mesh_proxy_client *find_client(struct bt_conn *conn)
{
int i;
for (i = 0; i < ARRAY_SIZE(clients); i++) {
if (clients[i].conn == conn) {
return &clients[i];
}
}
return NULL;
}
#if defined(CONFIG_BT_MESH_GATT_PROXY)
/* Next subnet in queue to be advertised */
static int next_idx;
static int proxy_segment_and_send(struct bt_conn *conn, u8_t type, struct net_buf_simple *msg);
static int filter_set(struct bt_mesh_proxy_client *client, struct net_buf_simple *buf)
{
u8_t type;
if (buf->len < 1) {
BT_WARN("Too short Filter Set message");
return -EINVAL;
}
type = net_buf_simple_pull_u8(buf);
BT_DBG("type 0x%02x", type);
switch (type) {
case 0x00:
memset(client->filter, 0, sizeof(client->filter));
client->filter_type = WHITELIST;
break;
case 0x01:
memset(client->filter, 0, sizeof(client->filter));
client->filter_type = BLACKLIST;
break;
default:
BT_WARN("Prohibited Filter Type 0x%02x", type);
return -EINVAL;
}
return 0;
}
static void filter_add(struct bt_mesh_proxy_client *client, u16_t addr)
{
int i;
BT_DBG("addr 0x%04x", addr);
if (addr == BT_MESH_ADDR_UNASSIGNED) {
return;
}
for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] == addr) {
return;
}
}
for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] == BT_MESH_ADDR_UNASSIGNED) {
client->filter[i] = addr;
return;
}
}
}
static void filter_remove(struct bt_mesh_proxy_client *client, u16_t addr)
{
int i;
BT_DBG("addr 0x%04x", addr);
if (addr == BT_MESH_ADDR_UNASSIGNED) {
return;
}
for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] == addr) {
client->filter[i] = BT_MESH_ADDR_UNASSIGNED;
return;
}
}
}
static void send_filter_status(struct bt_mesh_proxy_client *client, struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
struct bt_mesh_net_tx tx = {
.sub = rx->sub,
.ctx = &rx->ctx,
.src = bt_mesh_primary_addr(),
};
u16_t filter_size;
int i, err;
/* Configuration messages always have dst unassigned */
tx.ctx->addr = BT_MESH_ADDR_UNASSIGNED;
net_buf_simple_reset(buf);
net_buf_simple_reserve(buf, 10);
net_buf_simple_add_u8(buf, CFG_FILTER_STATUS);
if (client->filter_type == WHITELIST) {
net_buf_simple_add_u8(buf, 0x00);
} else {
net_buf_simple_add_u8(buf, 0x01);
}
for (filter_size = 0, i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] != BT_MESH_ADDR_UNASSIGNED) {
filter_size++;
}
}
net_buf_simple_add_be16(buf, filter_size);
BT_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
err = bt_mesh_net_encode(&tx, buf, true);
if (err) {
BT_ERR("Encoding Proxy cfg message failed (err %d)", err);
return;
}
err = proxy_segment_and_send(client->conn, BT_MESH_PROXY_CONFIG, buf);
if (err) {
BT_ERR("Failed to send proxy cfg message (err %d)", err);
}
}
static void proxy_cfg(struct bt_mesh_proxy_client *client)
{
struct bt_mesh_net_rx rx;
u8_t opcode;
int err;
if (client->buf.len > BT_MESH_NET_MAX_PDU_LEN) {
BT_ERR("Proxy cfg data is too long %d(%d)", client->buf.len, BT_MESH_NET_MAX_PDU_LEN);
return;
}
NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
err = bt_mesh_net_decode(&client->buf, BT_MESH_NET_IF_PROXY_CFG, &rx, &buf);
if (err) {
BT_ERR("Failed to decode Proxy Configuration (err %d)", err);
return;
}
/* Remove network headers */
net_buf_simple_pull(&buf, BT_MESH_NET_HDR_LEN);
BT_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len));
if (buf.len < 1) {
BT_WARN("Too short proxy configuration PDU");
return;
}
opcode = net_buf_simple_pull_u8(&buf);
switch (opcode) {
case CFG_FILTER_SET:
filter_set(client, &buf);
send_filter_status(client, &rx, &buf);
break;
case CFG_FILTER_ADD:
while (buf.len >= 2) {
u16_t addr;
addr = net_buf_simple_pull_be16(&buf);
filter_add(client, addr);
}
send_filter_status(client, &rx, &buf);
break;
case CFG_FILTER_REMOVE:
while (buf.len >= 2) {
u16_t addr;
addr = net_buf_simple_pull_be16(&buf);
filter_remove(client, addr);
}
send_filter_status(client, &rx, &buf);
break;
default:
BT_WARN("Unhandled configuration OpCode 0x%02x", opcode);
break;
}
}
static int beacon_send(struct bt_conn *conn, struct bt_mesh_subnet *sub)
{
NET_BUF_SIMPLE_DEFINE(buf, 23);
net_buf_simple_reserve(&buf, 1);
bt_mesh_beacon_create(sub, &buf);
return proxy_segment_and_send(conn, BT_MESH_PROXY_BEACON, &buf);
}
static void proxy_send_beacons(struct k_work *work)
{
struct bt_mesh_proxy_client *client;
int i;
client = CONTAINER_OF(work, struct bt_mesh_proxy_client, send_beacons);
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx != BT_MESH_KEY_UNUSED) {
beacon_send(client->conn, sub);
}
}
}
void bt_mesh_proxy_beacon_send(struct bt_mesh_subnet *sub)
{
int i;
if (!sub) {
/* NULL means we send on all subnets */
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) {
bt_mesh_proxy_beacon_send(&bt_mesh.sub[i]);
}
}
return;
}
for (i = 0; i < ARRAY_SIZE(clients); i++) {
if (clients[i].conn) {
beacon_send(clients[i].conn, sub);
}
}
}
void bt_mesh_proxy_identity_start(struct bt_mesh_subnet *sub)
{
sub->node_id = BT_MESH_NODE_IDENTITY_RUNNING;
sub->node_id_start = k_uptime_get_32();
/* Prioritize the recently enabled subnet */
next_idx = sub - bt_mesh.sub;
}
void bt_mesh_proxy_identity_stop(struct bt_mesh_subnet *sub)
{
sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
sub->node_id_start = 0;
}
int bt_mesh_proxy_identity_enable(void)
{
int i, count = 0;
BT_DBG("");
if (!bt_mesh_is_provisioned()) {
return -EAGAIN;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (sub->node_id == BT_MESH_NODE_IDENTITY_NOT_SUPPORTED) {
continue;
}
bt_mesh_proxy_identity_start(sub);
count++;
}
if (count) {
bt_mesh_adv_update();
}
return 0;
}
int bt_mesh_proxy_identity_disable(void)
{
int i, count = 0;
BT_DBG("");
if (!bt_mesh_is_provisioned()) {
return -EAGAIN;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
if (sub->node_id == BT_MESH_NODE_IDENTITY_NOT_SUPPORTED) {
continue;
}
bt_mesh_proxy_identity_stop(sub);
count++;
}
if (count) {
bt_mesh_adv_update();
}
return 0;
}
#endif /* GATT_PROXY */
static void proxy_complete_pdu(struct bt_mesh_proxy_client *client)
{
switch (client->msg_type) {
#if defined(CONFIG_BT_MESH_GATT_PROXY)
case BT_MESH_PROXY_NET_PDU:
BT_DBG("Mesh Network PDU");
bt_mesh_net_recv(&client->buf, 0, BT_MESH_NET_IF_PROXY);
break;
case BT_MESH_PROXY_BEACON:
BT_DBG("Mesh Beacon PDU");
bt_mesh_beacon_recv(&client->buf);
break;
case BT_MESH_PROXY_CONFIG:
BT_DBG("Mesh Configuration PDU");
proxy_cfg(client);
break;
#endif
#if defined(CONFIG_BT_MESH_PB_GATT)
case BT_MESH_PROXY_PROV:
BT_DBG("Mesh Provisioning PDU");
bt_mesh_pb_gatt_recv(client->conn, &client->buf);
break;
#endif
default:
BT_WARN("Unhandled Message Type 0x%02x", client->msg_type);
break;
}
net_buf_simple_reset(&client->buf);
}
#define ATTR_IS_PROV(attr) (attr->user_data != NULL)
static ssize_t proxy_recv(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len,
u16_t offset, u8_t flags)
{
struct bt_mesh_proxy_client *client = find_client(conn);
const u8_t *data = buf;
if (!client) {
return -ENOTCONN;
}
if (len < 1) {
BT_WARN("Too small Proxy PDU");
return -EINVAL;
}
if (ATTR_IS_PROV(attr) != (PDU_TYPE(data) == BT_MESH_PROXY_PROV)) {
BT_WARN("Proxy PDU type doesn't match GATT service");
return -EINVAL;
}
if (len - 1 > net_buf_simple_tailroom(&client->buf)) {
BT_WARN("Too big proxy PDU");
return -EINVAL;
}
switch (PDU_SAR(data)) {
case SAR_COMPLETE:
if (client->buf.len) {
BT_WARN("Complete PDU while a pending incomplete one");
return -EINVAL;
}
client->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&client->buf, data + 1, len - 1);
proxy_complete_pdu(client);
break;
case SAR_FIRST:
if (client->buf.len) {
BT_WARN("First PDU while a pending incomplete one");
return -EINVAL;
}
client->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&client->buf, data + 1, len - 1);
break;
case SAR_CONT:
if (!client->buf.len) {
BT_WARN("Continuation with no prior data");
return -EINVAL;
}
if (client->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in continuation");
return -EINVAL;
}
net_buf_simple_add_mem(&client->buf, data + 1, len - 1);
break;
case SAR_LAST:
if (!client->buf.len) {
BT_WARN("Last SAR PDU with no prior data");
return -EINVAL;
}
if (client->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in last SAR PDU");
return -EINVAL;
}
net_buf_simple_add_mem(&client->buf, data + 1, len - 1);
proxy_complete_pdu(client);
break;
}
return len;
}
static int conn_count;
uint8_t is_proxy_connected()
{
return conn_count > 0 ? 1 : 0;
}
static void proxy_connected(struct bt_conn *conn, u8_t err)
{
struct bt_mesh_proxy_client *client;
int i;
conn_count++;
BT_DBG("pconn:%p\r\n", conn);
/* Since we use ADV_OPT_ONE_TIME */
proxy_adv_enabled = false;
extern int bt_mesh_adv_disable();
// make sure adv and scan stop first
bt_mesh_adv_disable();
bt_mesh_scan_disable();
// enable scan again
bt_mesh_scan_enable();
/* Try to re-enable advertising in case it's possible */
if (conn_count < CONFIG_BT_MAX_CONN) {
bt_mesh_adv_update();
}
for (client = NULL, i = 0; i < ARRAY_SIZE(clients); i++) {
if (!clients[i].conn) {
client = &clients[i];
break;
}
}
if (!client) {
BT_ERR("No free Proxy Client objects");
return;
}
client->conn = bt_conn_ref(conn);
client->filter_type = NONE;
memset(client->filter, 0, sizeof(client->filter));
net_buf_simple_reset(&client->buf);
#ifdef CONFIG_GENIE_OTA
genie_ais_connect((struct bt_conn *)conn);
#endif
}
static void proxy_disconnected(struct bt_conn *conn, u8_t reason)
{
int i;
printf("proxy disconn:%p reason:0x%02x\r\n", conn, reason);
conn_count--;
for (i = 0; i < ARRAY_SIZE(clients); i++) {
struct bt_mesh_proxy_client *client = &clients[i];
if (client->conn == conn) {
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT) && client->filter_type == PROV) {
bt_mesh_pb_gatt_close(conn);
}
bt_conn_unref(client->conn);
client->conn = NULL;
break;
}
}
bt_mesh_adv_update();
#ifdef CONFIG_GENIE_OTA
genie_ais_disconnect(0);
#endif
}
struct net_buf_simple *bt_mesh_proxy_get_buf(void)
{
struct net_buf_simple *buf = &clients[0].buf;
net_buf_simple_reset(buf);
return buf;
}
#if defined(CONFIG_BT_MESH_PB_GATT)
static ssize_t prov_ccc_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len,
u16_t offset, u8_t flags)
{
struct bt_mesh_proxy_client *client;
u16_t *value = attr->user_data;
BT_DBG("len %u: %s", len, bt_hex(buf, len));
if (len != sizeof(*value)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
*value = sys_get_le16(buf);
if (*value != BT_GATT_CCC_NOTIFY) {
BT_WARN("Client wrote 0x%04x instead enabling notify", *value);
return len;
}
/* If a connection exists there must be a client */
client = find_client(conn);
__ASSERT(client, "No client for connection");
if (client->filter_type == NONE) {
client->filter_type = PROV;
bt_mesh_pb_gatt_open(conn);
}
return len;
}
static ssize_t prov_ccc_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset)
{
u16_t *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value));
}
/* Mesh Provisioning Service Declaration */
static struct bt_gatt_attr prov_attrs[] = {
BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROV),
BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_IN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_WRITE, NULL,
proxy_recv, (void *)1),
BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROV_DATA_OUT, BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_NONE, NULL, NULL, NULL),
/* Add custom CCC as clients need to be tracked individually */
BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, BT_GATT_PERM_WRITE | BT_GATT_PERM_READ, prov_ccc_read, prov_ccc_write,
&prov_ccc_val),
};
static struct bt_gatt_service prov_svc = BT_GATT_SERVICE(prov_attrs);
int bt_mesh_proxy_prov_enable(void)
{
int i;
BT_DBG("");
if (gatt_svc == MESH_GATT_PROV) {
return -EALREADY;
}
if (gatt_svc != MESH_GATT_NONE) {
return -EBUSY;
}
bt_gatt_service_register(&prov_svc);
gatt_svc = MESH_GATT_PROV;
prov_fast_adv = true;
for (i = 0; i < ARRAY_SIZE(clients); i++) {
if (clients[i].conn) {
clients[i].filter_type = PROV;
}
}
return 0;
}
int bt_mesh_proxy_prov_disable(bool disconnect)
{
int i;
BT_DBG("");
if (gatt_svc == MESH_GATT_NONE) {
return -EALREADY;
}
if (gatt_svc != MESH_GATT_PROV) {
return -EBUSY;
}
bt_gatt_service_unregister(&prov_svc);
gatt_svc = MESH_GATT_NONE;
for (i = 0; i < ARRAY_SIZE(clients); i++) {
struct bt_mesh_proxy_client *client = &clients[i];
if (!client->conn || client->filter_type != PROV) {
continue;
}
if (disconnect) {
bt_conn_disconnect(client->conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
} else {
bt_mesh_pb_gatt_close(client->conn);
client->filter_type = NONE;
}
}
bt_mesh_adv_update();
return 0;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
#if defined(CONFIG_BT_MESH_GATT_PROXY)
static ssize_t proxy_ccc_write(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, u16_t len,
u16_t offset, u8_t flags)
{
struct bt_mesh_proxy_client *client;
u16_t value;
BT_DBG("len %u: %s", len, bt_hex(buf, len));
if (len != sizeof(value)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
value = sys_get_le16(buf);
if (value != BT_GATT_CCC_NOTIFY) {
BT_WARN("Client wrote 0x%04x instead enabling notify", value);
return len;
}
/* If a connection exists there must be a client */
client = find_client(conn);
__ASSERT(client, "No client for connection");
if (client->filter_type == NONE) {
client->filter_type = WHITELIST;
k_work_submit(&client->send_beacons);
}
return len;
}
static ssize_t proxy_ccc_read(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, u16_t len, u16_t offset)
{
u16_t *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value, sizeof(*value));
}
/* Mesh Proxy Service Declaration */
static struct bt_gatt_attr proxy_attrs[] = {
BT_GATT_PRIMARY_SERVICE(BT_UUID_MESH_PROXY),
BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_IN, BT_GATT_CHRC_WRITE_WITHOUT_RESP, BT_GATT_PERM_WRITE, NULL,
proxy_recv, NULL),
BT_GATT_CHARACTERISTIC(BT_UUID_MESH_PROXY_DATA_OUT, BT_GATT_CHRC_NOTIFY, BT_GATT_PERM_NONE, NULL, NULL, NULL),
/* Add custom CCC as clients need to be tracked individually */
BT_GATT_DESCRIPTOR(BT_UUID_GATT_CCC, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, proxy_ccc_read, proxy_ccc_write,
&proxy_ccc_val),
};
static struct bt_gatt_service proxy_svc = BT_GATT_SERVICE(proxy_attrs);
int bt_mesh_proxy_gatt_enable(void)
{
int i;
BT_DBG("");
if (gatt_svc == MESH_GATT_PROXY) {
return -EALREADY;
}
if (gatt_svc != MESH_GATT_NONE) {
return -EBUSY;
}
bt_gatt_service_register(&proxy_svc);
gatt_svc = MESH_GATT_PROXY;
for (i = 0; i < ARRAY_SIZE(clients); i++) {
if (clients[i].conn) {
clients[i].filter_type = WHITELIST;
}
}
return 0;
}
void bt_mesh_proxy_gatt_disconnect(void)
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(clients); i++) {
struct bt_mesh_proxy_client *client = &clients[i];
if (client->conn && (client->filter_type == WHITELIST || client->filter_type == BLACKLIST)) {
client->filter_type = NONE;
bt_conn_disconnect(client->conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
}
}
}
int bt_mesh_proxy_gatt_disable(void)
{
BT_DBG("");
if (gatt_svc == MESH_GATT_NONE) {
return -EALREADY;
}
if (gatt_svc != MESH_GATT_PROXY) {
return -EBUSY;
}
bt_mesh_proxy_gatt_disconnect();
bt_gatt_service_unregister(&proxy_svc);
gatt_svc = MESH_GATT_NONE;
return 0;
}
void bt_mesh_proxy_addr_add(struct net_buf_simple *buf, u16_t addr)
{
struct bt_mesh_proxy_client *client = CONTAINER_OF(buf, struct bt_mesh_proxy_client, buf);
BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr);
if (client->filter_type == WHITELIST) {
filter_add(client, addr);
} else if (client->filter_type == BLACKLIST) {
filter_remove(client, addr);
}
}
static bool client_filter_match(struct bt_mesh_proxy_client *client, u16_t addr)
{
int i;
BT_DBG("filter_type %u addr 0x%04x", client->filter_type, addr);
if (client->filter_type == WHITELIST) {
for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] == addr) {
return true;
}
}
#ifdef CONFIG_GENIE_MESH_ENABLE
/*[Genie begin] add by lgy at 2020-09-10*/
/* add tmall genie groupcast address in filter list by default */
if (addr == BT_MESH_ADDR_TMALL_GENIE) {
return true;
}
/*[Genie end] add by lgy at 2020-09-10*/
#endif
return false;
}
if (client->filter_type == BLACKLIST) {
for (i = 0; i < ARRAY_SIZE(client->filter); i++) {
if (client->filter[i] == addr) {
return false;
}
}
return true;
}
return false;
}
bool bt_mesh_proxy_relay(struct net_buf_simple *buf, u16_t dst)
{
bool relayed = false;
int i;
BT_DBG("%u bytes to dst 0x%04x", buf->len, dst);
for (i = 0; i < ARRAY_SIZE(clients); i++) {
struct bt_mesh_proxy_client *client = &clients[i];
NET_BUF_SIMPLE_DEFINE(msg, 32);
if (!client->conn) {
continue;
}
if (!client_filter_match(client, dst)) {
continue;
}
/* Proxy PDU sending modifies the original buffer,
* so we need to make a copy.
*/
net_buf_simple_reserve(&msg, 1);
net_buf_simple_add_mem(&msg, buf->data, buf->len);
bt_mesh_proxy_send(client->conn, BT_MESH_PROXY_NET_PDU, &msg);
relayed = true;
}
return relayed;
}
#endif /* CONFIG_BT_MESH_GATT_PROXY */
static int proxy_send(struct bt_conn *conn, const void *data, u16_t len)
{
BT_DBG("%u bytes: %s", len, bt_hex(data, len));
#if defined(CONFIG_BT_MESH_GATT_PROXY)
if (gatt_svc == MESH_GATT_PROXY) {
return bt_gatt_notify(conn, &proxy_attrs[3], data, len);
}
#endif
#if defined(CONFIG_BT_MESH_PB_GATT)
if (gatt_svc == MESH_GATT_PROV) {
return bt_gatt_notify(conn, &prov_attrs[3], data, len);
}
#endif
return 0;
}
static int proxy_segment_and_send(struct bt_conn *conn, u8_t type, struct net_buf_simple *msg)
{
u16_t mtu;
BT_DBG("conn %p type 0x%02x len %u: %s", conn, type, msg->len, bt_hex(msg->data, msg->len));
/* ATT_MTU - OpCode (1 byte) - Handle (2 bytes) */
mtu = bt_gatt_get_mtu(conn) - 3;
if (mtu > msg->len) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_COMPLETE, type));
return proxy_send(conn, msg->data, msg->len);
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_FIRST, type));
proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
while (msg->len) {
if (msg->len + 1 < mtu) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_LAST, type));
proxy_send(conn, msg->data, msg->len);
break;
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_CONT, type));
proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
}
return 0;
}
int bt_mesh_proxy_send(struct bt_conn *conn, u8_t type, struct net_buf_simple *msg)
{
struct bt_mesh_proxy_client *client = find_client(conn);
if (!client) {
BT_ERR("No Proxy Client found");
return -ENOTCONN;
}
if ((client->filter_type == PROV) != (type == BT_MESH_PROXY_PROV)) {
BT_ERR("Invalid PDU type for Proxy Client");
return -EINVAL;
}
return proxy_segment_and_send(conn, type, msg);
}
#if defined(CONFIG_BT_MESH_PB_GATT)
static u8_t prov_svc_data[20] = {
0x27,
0x18,
};
static const struct bt_data prov_ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x27, 0x18),
BT_DATA(BT_DATA_SVC_DATA16, prov_svc_data, sizeof(prov_svc_data)),
};
#ifdef CONFIG_GENIE_OTA
static u8_t g_ais_adv_data[14] = {
0xa8, 0x01, // taobao
0x85, // vid & sub
0x15, // FMSK
0x15, 0x11, 0x22, 0x33, // PID
0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33 // MAC
};
struct bt_data ais_prov_sd[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID16_SOME, 0xB3, 0xFE),
BT_DATA(BT_DATA_MANUFACTURER_DATA, g_ais_adv_data, 14),
};
#endif
#endif /* PB_GATT */
#if defined(CONFIG_BT_MESH_GATT_PROXY)
#define ID_TYPE_NET 0x00
#define ID_TYPE_NODE 0x01
#define NODE_ID_LEN 19
#define NET_ID_LEN 11
#define NODE_ID_TIMEOUT K_SECONDS(CONFIG_BT_MESH_NODE_ID_TIMEOUT)
static u8_t proxy_svc_data[NODE_ID_LEN] = {
0x28,
0x18,
};
static const struct bt_data node_id_ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18),
BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NODE_ID_LEN),
};
static const struct bt_data net_id_ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0x28, 0x18),
BT_DATA(BT_DATA_SVC_DATA16, proxy_svc_data, NET_ID_LEN),
};
static int node_id_adv(struct bt_mesh_subnet *sub)
{
u8_t tmp[16];
int err;
BT_DBG("");
proxy_svc_data[2] = ID_TYPE_NODE;
err = bt_rand(proxy_svc_data + 11, 8);
if (err) {
return err;
}
memset(tmp, 0, 6);
memcpy(tmp + 6, proxy_svc_data + 11, 8);
sys_put_be16(bt_mesh_primary_addr(), tmp + 14);
err = bt_encrypt_be(sub->keys[sub->kr_flag].identity, tmp, tmp);
if (err) {
return err;
}
memcpy(proxy_svc_data + 3, tmp + 8, 8);
#ifdef CONFIG_GENIE_OTA
genie_crypto_adv_create(g_ais_adv_data, 1);
err = bt_mesh_adv_enable(&fast_adv_param, node_id_ad, ARRAY_SIZE(node_id_ad), ais_prov_sd, ARRAY_SIZE(ais_prov_sd));
#else
err = bt_mesh_adv_enable(&fast_adv_param, node_id_ad, ARRAY_SIZE(node_id_ad), NULL, 0);
#endif
if (err) {
BT_WARN("Failed to advertise using Node ID (err %d)", err);
return err;
}
proxy_adv_enabled = true;
return 0;
}
static int net_id_adv(struct bt_mesh_subnet *sub)
{
int err;
BT_DBG("");
proxy_svc_data[2] = ID_TYPE_NET;
BT_DBG("Advertising with NetId %s", bt_hex(sub->keys[sub->kr_flag].net_id, 8));
memcpy(proxy_svc_data + 3, sub->keys[sub->kr_flag].net_id, 8);
#ifdef CONFIG_GENIE_OTA
genie_crypto_adv_create(g_ais_adv_data, 1);
err = bt_mesh_adv_enable(&fast_adv_param, net_id_ad, ARRAY_SIZE(net_id_ad), ais_prov_sd, ARRAY_SIZE(ais_prov_sd));
#else
err = bt_mesh_adv_enable(&fast_adv_param, net_id_ad, ARRAY_SIZE(net_id_ad), NULL, 0);
#endif
if (err) {
BT_WARN("Failed to advertise using Network ID (err %d)", err);
return err;
}
proxy_adv_enabled = true;
return 0;
}
static bool advertise_subnet(struct bt_mesh_subnet *sub)
{
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
return false;
}
return (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING || bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED);
}
static struct bt_mesh_subnet *next_sub(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub;
sub = &bt_mesh.sub[(i + next_idx) % ARRAY_SIZE(bt_mesh.sub)];
if (advertise_subnet(sub)) {
next_idx = (next_idx + 1) % ARRAY_SIZE(bt_mesh.sub);
return sub;
}
}
return NULL;
}
static int sub_count(void)
{
int i, count = 0;
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
if (advertise_subnet(sub)) {
count++;
}
}
return count;
}
static bt_s32_t gatt_proxy_advertise(struct bt_mesh_subnet *sub)
{
bt_s32_t remaining = K_FOREVER;
int subnet_count;
BT_DBG("");
if (conn_count == CONFIG_BT_MAX_CONN) {
BT_WARN("Connectable advertising deferred (max connections)");
return remaining;
}
if (!sub) {
BT_DBG("No subnets to advertise on");
return remaining;
}
if (sub->node_id == BT_MESH_NODE_IDENTITY_RUNNING) {
bt_u32_t active = k_uptime_get_32() - sub->node_id_start;
if (active < NODE_ID_TIMEOUT) {
remaining = NODE_ID_TIMEOUT - active;
BT_DBG("Node ID active for %u ms, %d ms remaining", active, remaining);
node_id_adv(sub);
} else {
bt_mesh_proxy_identity_stop(sub);
BT_DBG("Node ID stopped");
}
}
if (sub->node_id == BT_MESH_NODE_IDENTITY_STOPPED) {
if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
net_id_adv(sub);
} else {
return gatt_proxy_advertise(next_sub());
}
}
subnet_count = sub_count();
BT_DBG("sub_count %u", subnet_count);
if (subnet_count > 1) {
bt_s32_t max_timeout;
/* We use NODE_ID_TIMEOUT as a starting point since it may
* be less than 60 seconds. Divide this period into at least
* 6 slices, but make sure that a slice is at least one
* second long (to avoid excessive rotation).
*/
max_timeout = NODE_ID_TIMEOUT / MAX(subnet_count, 6);
max_timeout = MAX(max_timeout, K_SECONDS(1));
if (remaining > max_timeout || remaining < 0) {
remaining = max_timeout;
}
}
BT_DBG("Advertising %d ms for net_idx 0x%04x", remaining, sub->net_idx);
return remaining;
}
#endif /* GATT_PROXY */
#if defined(CONFIG_BT_MESH_PB_GATT)
static size_t gatt_prov_adv_create(struct bt_data prov_sd[2])
{
const struct bt_mesh_prov *prov = bt_mesh_prov_get();
const char *name = bt_get_name();
size_t name_len = strlen(name);
size_t prov_sd_len = 0;
size_t sd_space = 31;
memcpy(prov_svc_data + 2, prov->uuid, 16);
sys_put_be16(prov->oob_info, prov_svc_data + 18);
if (prov->uri) {
size_t uri_len = strlen(prov->uri);
if (uri_len > 29) {
/* There's no way to shorten an URI */
BT_WARN("Too long URI to fit advertising packet");
} else {
prov_sd[0].type = BT_DATA_URI;
prov_sd[0].data_len = uri_len;
prov_sd[0].data = (const u8_t *)prov->uri;
sd_space -= 2 + uri_len;
prov_sd_len++;
}
}
if (sd_space > 2 && name_len > 0) {
sd_space -= 2;
if (sd_space < name_len) {
prov_sd[prov_sd_len].type = BT_DATA_NAME_SHORTENED;
prov_sd[prov_sd_len].data_len = sd_space;
} else {
prov_sd[prov_sd_len].type = BT_DATA_NAME_COMPLETE;
prov_sd[prov_sd_len].data_len = name_len;
}
prov_sd[prov_sd_len].data = (const u8_t *)name;
prov_sd_len++;
}
return prov_sd_len;
}
#endif /* CONFIG_BT_MESH_PB_GATT */
bt_s32_t bt_mesh_proxy_adv_start(void)
{
BT_DBG("");
if (gatt_svc == MESH_GATT_NONE) {
return K_FOREVER;
}
#if defined(CONFIG_BT_MESH_PB_GATT)
int err;
if (!bt_mesh_is_provisioned() && (conn_count < CONFIG_BT_MAX_CONN)) {
const struct bt_le_adv_param *param;
static struct bt_data prov_sd[2];
#ifndef CONFIG_GENIE_OTA
static size_t prov_sd_len;
#endif
if (prov_fast_adv) {
param = &fast_adv_param;
} else {
param = &slow_adv_param;
}
#ifndef CONFIG_GENIE_OTA
prov_sd_len = gatt_prov_adv_create(prov_sd);
#else
gatt_prov_adv_create(prov_sd);
#endif
#ifdef CONFIG_GENIE_OTA
genie_crypto_adv_create(g_ais_adv_data, 0);
err = bt_mesh_adv_enable(param, prov_ad, ARRAY_SIZE(prov_ad), ais_prov_sd, ARRAY_SIZE(ais_prov_sd));
#else
err = bt_mesh_adv_enable(param, prov_ad, ARRAY_SIZE(prov_ad), prov_sd, prov_sd_len);
#endif
if (err == 0) {
proxy_adv_enabled = true;
/* Advertise 60 seconds using fast interval */
if (prov_fast_adv) {
prov_fast_adv = false;
return K_SECONDS(60);
}
} else {
BT_ERR("proxy adv err %d", err);
}
}
#endif /* PB_GATT */
#if defined(CONFIG_BT_MESH_GATT_PROXY)
if (bt_mesh_is_provisioned() && (conn_count < CONFIG_BT_MAX_CONN)) {
return gatt_proxy_advertise(next_sub());
}
#endif /* GATT_PROXY */
return K_FOREVER;
}
void bt_mesh_proxy_adv_stop(void)
{
int err;
BT_DBG("adv_enabled %u", proxy_adv_enabled);
if (!proxy_adv_enabled) {
return;
}
err = bt_mesh_adv_disable();
if (err) {
BT_ERR("Failed to stop advertising (err %d)", err);
} else {
proxy_adv_enabled = false;
}
}
static struct bt_conn_cb conn_callbacks = {
.connected = proxy_connected,
.disconnected = proxy_disconnected,
};
int bt_mesh_proxy_init(void)
{
int i;
/* Initialize the client receive buffers */
for (i = 0; i < ARRAY_SIZE(clients); i++) {
struct bt_mesh_proxy_client *client = &clients[i];
client->buf.size = CLIENT_BUF_SIZE;
client->buf.__buf = client_buf_data + (i * CLIENT_BUF_SIZE);
#if defined(CONFIG_BT_MESH_GATT_PROXY)
k_work_init(&client->send_beacons, proxy_send_beacons);
#endif
}
bt_conn_cb_register(&conn_callbacks);
#ifdef CONFIG_GENIE_OTA
genie_ota_pre_init();
#endif
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/proxy.c | C | apache-2.0 | 35,592 |
/*
* Copyright (c) 2018 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <settings/settings.h>
#include <net/buf.h>
#include <bluetooth/hci.h>
#include <bluetooth/conn.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_SETTINGS)
#include "common/log.h"
#include "host/settings.h"
#include "mesh.h"
#include "net.h"
#include "crypto.h"
#include "ble_transport.h"
#include "access.h"
#include "foundation.h"
#include "proxy.h"
// #include "settings.h"
#include "lpn.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "provisioner_proxy.h"
#endif
#ifdef CONFIG_BT_SETTINGS
#ifndef CONFIG_BT_MESH_RPL_STORE_RATE
#define CONFIG_BT_MESH_RPL_STORE_RATE 100
#endif
/* Tracking of what storage changes are pending for App and Net Keys. We
* track this in a separate array here instead of within the respective
* bt_mesh_app_key and bt_mesh_subnet structs themselves, since once a key
* gets deleted its struct becomes invalid and may be reused for other keys.
*/
struct key_update {
u16_t key_idx:12, /* AppKey or NetKey Index */
valid:1, /* 1 if this entry is valid, 0 if not */
app_key:1, /* 1 if this is an AppKey, 0 if a NetKey */
clear:1, /* 1 if key needs clearing, 0 if storing */
p_key:1; /* 1 if is provisioner key */
};
// #ifdef CONFIG_BT_MESH_PROVISIONER
// static struct key_update key_updates[CONFIG_BT_MESH_APP_KEY_COUNT + CONFIG_BT_MESH_SUBNET_COUNT + CONFIG_BT_MESH_PROVISIONER_APP_KEY_COUNT + CONFIG_BT_MESH_PROVISIONER_SUBNET_COUNT];
// #else
static struct key_update key_updates[CONFIG_BT_MESH_APP_KEY_COUNT + CONFIG_BT_MESH_SUBNET_COUNT];
// #endif
static struct k_delayed_work pending_store;
/* Mesh network storage information */
struct net_val {
u16_t primary_addr;
u8_t dev_key[16];
} __packed;
/* Sequence number storage */
struct seq_val {
u8_t val[3];
} __packed;
/* Heartbeat Publication storage */
struct hb_pub_val {
u16_t dst;
u8_t period;
u8_t ttl;
u16_t feat;
u16_t net_idx:12, indefinite:1;
};
/* Miscelaneous configuration server model states */
struct cfg_val {
u8_t net_transmit;
u8_t relay;
u8_t relay_retransmit;
u8_t beacon;
u8_t gatt_proxy;
u8_t frnd;
u8_t default_ttl;
};
/* IV Index & IV Update storage */
struct iv_val {
bt_u32_t iv_index;
u8_t iv_update:1, iv_duration:7;
} __packed;
/* Replay Protection List storage */
struct rpl_val {
bt_u32_t seq:24, old_iv:1;
};
/* NetKey storage information */
struct net_key_val {
u8_t kr_flag:1, kr_phase:7;
u8_t val[2][16];
} __packed;
/* AppKey storage information */
struct app_key_val {
u16_t net_idx;
bool updated;
u8_t val[2][16];
} __packed;
struct mod_pub_val {
u16_t addr;
u16_t key;
u8_t ttl;
u8_t retransmit;
u8_t period;
u8_t period_div:4, cred:1;
};
/* We need this so we don't overwrite app-hardcoded values in case FCB
* contains a history of changes but then has a NULL at the end.
*/
static struct {
bool valid;
struct cfg_val cfg;
} stored_cfg;
static inline int mesh_x_set(settings_read_cb read_cb, void *cb_arg, void *out, size_t read_len)
{
ssize_t len;
len = read_cb(cb_arg, out, read_len);
if (len < 0) {
BT_ERR("Failed to read value (err %d)", len);
return len;
}
// BT_HEXDUMP_DBG(out, len, "val");
if (len != read_len) {
BT_ERR("Unexpected value length (%zd != %u)", len, read_len);
return -EINVAL;
}
return 0;
}
static int net_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct net_val net;
int err;
if (len_rd == 0) {
bt_mesh_comp_unprovision();
memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key));
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &net, sizeof(net));
if (err) {
BT_ERR("Failed to set 'net'");
return err;
}
memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key));
bt_mesh_comp_provision(net.primary_addr);
BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr);
BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16));
return 0;
}
static int iv_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct iv_val iv;
int err;
if (len_rd == 0) {
bt_mesh.iv_index = 0U;
atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &iv, sizeof(iv));
if (err) {
BT_ERR("Failed to set 'iv'");
return err;
}
bt_mesh.iv_index = iv.iv_index;
atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update);
bt_mesh.ivu_duration = iv.iv_duration;
BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours", iv.iv_index, iv.iv_update, iv.iv_duration);
return 0;
}
static int seq_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct seq_val seq;
int err;
if (len_rd == 0) {
BT_DBG("val (null)");
bt_mesh.seq = 0U;
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &seq, sizeof(seq));
if (err) {
BT_ERR("Failed to set 'seq'");
return err;
}
bt_mesh.seq = sys_get_le24(seq.val);
if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) {
/* Make sure we have a large enough sequence number. We
* subtract 1 so that the first transmission causes a write
* to the settings storage.
*/
bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE - (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE));
bt_mesh.seq--;
}
BT_DBG("Sequence Number 0x%06x", bt_mesh.seq);
return 0;
}
static struct bt_mesh_rpl *rpl_find(u16_t src)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
if (bt_mesh.rpl[i].src == src) {
return &bt_mesh.rpl[i];
}
}
return NULL;
}
static struct bt_mesh_rpl *rpl_alloc(u16_t src)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
if (!bt_mesh.rpl[i].src) {
bt_mesh.rpl[i].src = src;
return &bt_mesh.rpl[i];
}
}
return NULL;
}
static int rpl_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_rpl *entry;
struct rpl_val rpl;
int err;
u16_t src;
if (!name) {
BT_ERR("Insufficient number of arguments");
return -ENOENT;
}
src = strtol(name, NULL, 16);
entry = rpl_find(src);
if (len_rd == 0) {
BT_DBG("val (null)");
if (entry) {
(void)memset(entry, 0, sizeof(*entry));
} else {
BT_WARN("Unable to find RPL entry for 0x%04x", src);
}
return 0;
}
if (!entry) {
entry = rpl_alloc(src);
if (!entry) {
BT_ERR("Unable to allocate RPL entry for 0x%04x", src);
return -ENOMEM;
}
}
err = mesh_x_set(read_cb, cb_arg, &rpl, sizeof(rpl));
if (err) {
BT_ERR("Failed to set `net`");
return err;
}
entry->seq = rpl.seq;
entry->old_iv = rpl.old_iv;
BT_DBG("RPL entry for 0x%04x: Seq 0x%06x old_iv %u", entry->src, entry->seq, entry->old_iv);
return 0;
}
static int net_key_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_subnet *sub;
struct net_key_val key;
int i, err;
u16_t net_idx;
if (!name) {
BT_ERR("Insufficient number of arguments");
return -ENOENT;
}
net_idx = strtol(name, NULL, 16);
sub = bt_mesh_subnet_get(net_idx);
if (len_rd == 0) {
BT_DBG("val (null)");
if (!sub) {
BT_ERR("No subnet with NetKeyIndex 0x%03x", net_idx);
return -ENOENT;
}
BT_DBG("Deleting NetKeyIndex 0x%03x", net_idx);
bt_mesh_subnet_del(sub, false);
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key));
if (err) {
BT_ERR("Failed to set \'net-key\'");
return err;
}
if (sub) {
BT_DBG("Updating existing NetKeyIndex 0x%03x", net_idx);
sub->kr_flag = key.kr_flag;
sub->kr_phase = key.kr_phase;
memcpy(sub->keys[0].net, &key.val[0], 16);
memcpy(sub->keys[1].net, &key.val[1], 16);
return 0;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx == BT_MESH_KEY_UNUSED) {
sub = &bt_mesh.sub[i];
break;
}
}
if (!sub) {
BT_ERR("No space to allocate a new subnet");
return -ENOMEM;
}
sub->net_idx = net_idx;
sub->kr_flag = key.kr_flag;
sub->kr_phase = key.kr_phase;
memcpy(sub->keys[0].net, &key.val[0], 16);
memcpy(sub->keys[1].net, &key.val[1], 16);
BT_DBG("NetKeyIndex 0x%03x recovered from storage", net_idx);
return 0;
}
static int app_key_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_app_key *app;
struct app_key_val key;
u16_t app_idx;
int err;
if (!name) {
BT_ERR("Insufficient number of arguments");
return -ENOENT;
}
app_idx = strtol(name, NULL, 16);
if (len_rd == 0) {
BT_DBG("val (null)");
BT_DBG("Deleting AppKeyIndex 0x%03x", app_idx);
app = bt_mesh_app_key_find(app_idx);
if (app) {
bt_mesh_app_key_del(app, false);
}
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key));
if (err) {
BT_ERR("Failed to set \'app-key\'");
return err;
}
app = bt_mesh_app_key_find(app_idx);
if (!app) {
app = bt_mesh_app_key_alloc(app_idx);
}
if (!app) {
BT_ERR("No space for a new app key");
return -ENOMEM;
}
app->net_idx = key.net_idx;
app->app_idx = app_idx;
app->updated = key.updated;
app->appkey_active = 1;
memcpy(app->keys[0].val, key.val[0], 16);
memcpy(app->keys[1].val, key.val[1], 16);
bt_mesh_app_id(app->keys[0].val, &app->keys[0].id);
bt_mesh_app_id(app->keys[1].val, &app->keys[1].id);
BT_DBG("AppKeyIndex 0x%03x recovered from storage", app_idx);
return 0;
}
#ifdef CONFIG_BT_MESH_PROVISIONER
// static int pnet_key_set(const char *name, size_t len_rd, settings_read_cb read_cb,
// void *cb_arg)
// {
// struct bt_mesh_subnet *sub;
// struct net_key_val key;
// int i, err;
// u16_t net_idx;
// net_idx = strtol(name, NULL, 16);
// sub = provisioner_subnet_get(net_idx);
// if (len_rd == 0) {
// if (!sub) {
// BT_ERR("No subnet with NetKeyIndex 0x%03x", net_idx);
// return -ENOENT;
// }
// BT_DBG("Deleting NetKeyIndex 0x%03x", net_idx);
// bt_mesh_provisioner_local_net_key_delete(net_idx);
// return 0;
// }
// err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key));
// if (err) {
// BT_ERR("Failed to set \'pnet key\'");
// return err;
// }
// if (sub) {
// BT_DBG("Updating existing NetKeyIndex 0x%03x", net_idx);
// sub->kr_flag = key.kr_flag;
// sub->kr_phase = key.kr_phase;
// memcpy(sub->keys[0].net, &key.val[0], 16);
// memcpy(sub->keys[1].net, &key.val[1], 16);
// return 0;
// }
// for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
// if (bt_mesh.p_sub[i].net_idx == BT_MESH_KEY_UNUSED) {
// sub = &bt_mesh.p_sub[i];
// sub->net_idx = net_idx;
// sub->kr_flag = key.kr_flag;
// sub->kr_phase = key.kr_phase;
// memcpy(sub->keys[0].net, &key.val[0], 16);
// memcpy(sub->keys[1].net, &key.val[1], 16);
// break;
// }
// }
// BT_DBG("NetKeyIndex 0x%03x recovered from storage", net_idx);
// return 0;
// }
static int papp_key_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_app_key *app;
struct app_key_val key;
u16_t app_idx;
int err;
app_idx = strtol(name, NULL, 16);
if (len_rd == 0) {
BT_DBG("Deleting AppKeyIndex 0x%03x", app_idx);
app = provisioner_app_key_find(app_idx);
if (app) {
bt_mesh_provisioner_local_app_key_delete(0, app_idx);
}
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &key, sizeof(key));
if (err) {
BT_ERR("Failed to set \'papp key\'");
return err;
}
app = provisioner_app_key_find(app_idx);
if (!app) {
app = bt_mesh_provisioner_p_app_key_alloc();
}
if (!app) {
BT_ERR("No space for a new app key");
return -ENOMEM;
}
app->net_idx = key.net_idx;
app->app_idx = app_idx;
app->updated = key.updated;
app->appkey_active = 1;
memcpy(app->keys[0].val, key.val[0], 16);
memcpy(app->keys[1].val, key.val[1], 16);
bt_mesh_app_id(app->keys[0].val, &app->keys[0].id);
bt_mesh_app_id(app->keys[1].val, &app->keys[1].id);
BT_DBG("AppKeyIndex 0x%03x recovered from storage", app_idx);
return 0;
}
#endif
static int hb_pub_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get();
struct hb_pub_val hb_val;
int err;
if (!pub) {
return -ENOENT;
}
if (len_rd == 0) {
pub->dst = BT_MESH_ADDR_UNASSIGNED;
pub->count = 0U;
pub->ttl = 0U;
pub->period = 0U;
pub->feat = 0U;
BT_DBG("Cleared heartbeat publication");
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &hb_val, sizeof(hb_val));
if (err) {
BT_ERR("Failed to set \'hb_val\'");
return err;
}
pub->dst = hb_val.dst;
pub->period = hb_val.period;
pub->ttl = hb_val.ttl;
pub->feat = hb_val.feat;
pub->net_idx = hb_val.net_idx;
if (hb_val.indefinite) {
pub->count = 0xffff;
} else {
pub->count = 0U;
}
BT_DBG("Restored heartbeat publication");
return 0;
}
static int cfg_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get();
int err;
if (!cfg) {
return -ENOENT;
}
if (len_rd == 0) {
stored_cfg.valid = false;
BT_DBG("Cleared configuration state");
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &stored_cfg.cfg, sizeof(stored_cfg.cfg));
if (err) {
BT_ERR("Failed to set \'cfg\'");
return err;
}
stored_cfg.valid = true;
BT_DBG("Restored configuration state");
return 0;
}
static int mod_set_bind(struct bt_mesh_model *mod, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
ssize_t len;
int i;
/* Start with empty array regardless of cleared or set value */
for (i = 0; i < ARRAY_SIZE(mod->keys); i++) {
mod->keys[i] = BT_MESH_KEY_UNUSED;
}
if (len_rd == 0) {
BT_DBG("Cleared bindings for model");
return 0;
}
len = read_cb(cb_arg, mod->keys, sizeof(mod->keys));
if (len < 0) {
BT_ERR("Failed to read value (err %zd)", len);
return len;
}
BT_DBG("Decoded %zu bound keys for model", len / sizeof(mod->keys[0]));
return 0;
}
static int mod_set_sub(struct bt_mesh_model *mod, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
ssize_t len;
/* Start with empty array regardless of cleared or set value */
(void)memset(mod->groups, 0, sizeof(mod->groups));
if (len_rd == 0) {
BT_DBG("Cleared subscriptions for model");
return 0;
}
len = read_cb(cb_arg, mod->groups, sizeof(mod->groups));
if (len < 0) {
BT_ERR("Failed to read value (err %zd)", len);
return len;
}
BT_DBG("Decoded %zu subscribed group addresses for model", len / sizeof(mod->groups[0]));
return 0;
}
static int mod_set_pub(struct bt_mesh_model *mod, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct mod_pub_val pub;
int err;
if (!mod->pub) {
BT_WARN("Model has no publication context!");
return -EINVAL;
}
if (len_rd == 0) {
mod->pub->addr = BT_MESH_ADDR_UNASSIGNED;
mod->pub->key = 0U;
mod->pub->cred = 0U;
mod->pub->ttl = 0U;
mod->pub->period = 0U;
mod->pub->retransmit = 0U;
mod->pub->count = 0U;
BT_DBG("Cleared publication for model");
return 0;
}
err = mesh_x_set(read_cb, cb_arg, &pub, sizeof(pub));
if (err) {
BT_ERR("Failed to set \'model-pub\'");
return err;
}
mod->pub->addr = pub.addr;
mod->pub->key = pub.key;
mod->pub->cred = pub.cred;
mod->pub->ttl = pub.ttl;
mod->pub->period = pub.period;
mod->pub->retransmit = pub.retransmit;
mod->pub->count = 0U;
BT_DBG("Restored model publication, dst 0x%04x app_idx 0x%03x", pub.addr, pub.key);
return 0;
}
static int mod_set(bool vnd, const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_model *mod;
u8_t elem_idx, mod_idx;
u16_t mod_key;
int len;
const char *next;
if (!name) {
BT_ERR("Insufficient number of arguments");
return -ENOENT;
}
mod_key = strtol(name, NULL, 16);
elem_idx = mod_key >> 8;
mod_idx = mod_key;
BT_DBG("Decoded mod_key 0x%04x as elem_idx %u mod_idx %u", mod_key, elem_idx, mod_idx);
mod = bt_mesh_model_get(vnd, elem_idx, mod_idx);
if (!mod) {
BT_ERR("Failed to get model for elem_idx %u mod_idx %u", elem_idx, mod_idx);
return -ENOENT;
}
len = settings_name_next(name, &next);
if (!next) {
BT_ERR("Insufficient number of arguments");
return -ENOENT;
}
if (!strncmp(next, "bind", len)) {
return mod_set_bind(mod, len_rd, read_cb, cb_arg);
}
if (!strncmp(next, "sub", len)) {
return mod_set_sub(mod, len_rd, read_cb, cb_arg);
}
if (!strncmp(next, "pub", len)) {
return mod_set_pub(mod, len_rd, read_cb, cb_arg);
}
BT_WARN("Unknown module key %s", next);
return -ENOENT;
}
static int sig_mod_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
return mod_set(false, name, len_rd, read_cb, cb_arg);
}
static int vnd_mod_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
return mod_set(true, name, len_rd, read_cb, cb_arg);
}
#ifdef CONFIG_BT_MESH_PROVISIONER
static int prov_node_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
struct bt_mesh_node_t node_info = { 0 };
int node_id = 0;
int err;
if (name == NULL) {
BT_ERR("Invail name NULL");
return -EINVAL;
}
node_id = strtol(name, NULL, 16);
BT_DBG("Restore Node %d", node_id);
(void)node_id;
err = mesh_x_set(read_cb, cb_arg, &node_info, sizeof(node_info));
if (err) {
BT_ERR("Failed to set \'cfg\'");
return err;
}
bt_addr_le_t addr;
addr.type = node_info.addr_type;
memcpy(addr.a.val, node_info.addr_val, 6);
provisioner_prov_restore_nodes_info(&addr, node_info.dev_uuid, node_info.oob_info, node_info.element_num,
node_info.unicast_addr, node_info.net_idx, node_info.flags, node_info.iv_index,
node_info.dev_key, 0);
return 0;
}
#endif
const struct mesh_setting {
const char *name;
int (*func)(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg);
} settings[] = {
{ "Net", net_set }, { "IV", iv_set }, { "Seq", seq_set }, { "RPL", rpl_set },
{ "NetKey", net_key_set }, { "AppKey", app_key_set }, { "HBPub", hb_pub_set }, { "Cfg", cfg_set },
{ "s", sig_mod_set }, { "v", vnd_mod_set },
#ifdef CONFIG_BT_MESH_PROVISIONER
{ "Node", prov_node_set },
// { "pNetKey", pnet_key_set },
// { "pAppKey", papp_key_set },
#endif
};
static int mesh_set(const char *name, size_t len_rd, settings_read_cb read_cb, void *cb_arg)
{
int i, len;
const char *next;
if (!name) {
BT_ERR("Insufficient number of arguments");
return -EINVAL;
}
len = settings_name_next(name, &next);
for (i = 0; i < ARRAY_SIZE(settings); i++) {
if (!strncmp(settings[i].name, name, len)) {
return settings[i].func(next, len_rd, read_cb, cb_arg);
}
}
BT_WARN("No matching handler for key %s", log_strdup(name));
return -ENOENT;
}
static int subnet_init(struct bt_mesh_subnet *sub)
{
int err;
err = bt_mesh_net_keys_create(&sub->keys[0], sub->keys[0].net);
if (err) {
BT_ERR("Unable to generate keys for subnet");
return -EIO;
}
if (sub->kr_phase != BT_MESH_KR_NORMAL) {
err = bt_mesh_net_keys_create(&sub->keys[1], sub->keys[1].net);
if (err) {
BT_ERR("Unable to generate keys for subnet");
memset(&sub->keys[0], 0, sizeof(sub->keys[0]));
return -EIO;
}
}
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
} else {
sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
}
/* Make sure we have valid beacon data to be sent */
bt_mesh_net_beacon_update(sub);
return 0;
}
static void commit_mod(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary, void *user_data)
{
if (mod->pub && mod->pub->update && mod->pub->addr != BT_MESH_ADDR_UNASSIGNED) {
bt_s32_t ms = bt_mesh_model_pub_period_get(mod);
if (ms) {
BT_DBG("Starting publish timer (period %u ms)", ms);
k_delayed_work_submit(&mod->pub->timer, ms);
}
}
}
static int mesh_commit(void)
{
struct bt_mesh_hb_pub *hb_pub;
struct bt_mesh_cfg_srv *cfg;
int i;
#ifdef CONFIG_BT_MESH_PROVISIONER
// BT_DBG("sub[0].net_idx 0x%03x", bt_mesh.p_sub[0].net_idx);
// if (bt_mesh.p_sub[0].net_idx != BT_MESH_KEY_UNUSED) {
// for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
// struct bt_mesh_subnet *sub = &bt_mesh.p_sub[i];
// if (sub->net_idx == BT_MESH_KEY_UNUSED) {
// continue;
// }
// if (sub->kr_flag) {
// if (bt_mesh_net_keys_create(&sub->keys[1], sub->keys[1].net)) {
// BT_ERR("%s: create net_keys fail", __func__);
// sub->subnet_active = false;
// continue;
// }
// sub->kr_phase = BT_MESH_KR_PHASE_2;
// } else {
// /* Currently provisioner only use keys[0] */
// if (bt_mesh_net_keys_create(&sub->keys[0], sub->keys[0].net)) {
// BT_ERR("%s: create net_keys fail", __func__);
// sub->subnet_active = false;
// continue;
// }
// sub->kr_phase = BT_MESH_KR_NORMAL;
// }
// sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
// sub->subnet_active = true;
// }
// }
if (IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_mesh.seq && CONFIG_BT_MESH_SEQ_STORE_RATE > 0) {
/* Make sure we have a large enough sequence number. We
* subtract 1 so that the first transmission causes a write
* to the settings storage.
*/
bt_mesh.seq = CONFIG_BT_MESH_SEQ_STORE_RATE - 1;
}
#endif
BT_DBG("sub[0].net_idx 0x%03x", bt_mesh.sub[0].net_idx);
if (bt_mesh.sub[0].net_idx == BT_MESH_KEY_UNUSED) {
/* Nothing to do since we're not yet provisioned */
return 0;
}
if (IS_ENABLED(CONFIG_BT_MESH_PB_GATT)) {
bt_mesh_proxy_prov_disable(true);
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
int err;
if (sub->net_idx == BT_MESH_KEY_UNUSED) {
continue;
}
err = subnet_init(sub);
if (err) {
BT_ERR("Failed to init subnet 0x%03x", sub->net_idx);
} else {
sub->subnet_active = true;
}
}
if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
}
bt_mesh_model_foreach(commit_mod, NULL);
hb_pub = bt_mesh_hb_pub_get();
if (hb_pub && hb_pub->dst != BT_MESH_ADDR_UNASSIGNED && hb_pub->count && hb_pub->period) {
BT_DBG("Starting heartbeat publication");
k_work_submit(&hb_pub->timer.work);
}
cfg = bt_mesh_cfg_get();
if (cfg && stored_cfg.valid) {
cfg->net_transmit = stored_cfg.cfg.net_transmit;
cfg->relay = stored_cfg.cfg.relay;
cfg->relay_retransmit = stored_cfg.cfg.relay_retransmit;
cfg->beacon = stored_cfg.cfg.beacon;
cfg->gatt_proxy = stored_cfg.cfg.gatt_proxy;
cfg->frnd = stored_cfg.cfg.frnd;
cfg->default_ttl = stored_cfg.cfg.default_ttl;
}
atomic_set_bit(bt_mesh.flags, BT_MESH_VALID);
// #ifndef CONFIG_BT_MESH_PROVISIONER
bt_mesh_net_start();
// #endif
return 0;
}
//BT_SETTINGS_DEFINE(mesh, mesh_set, mesh_commit, NULL);
static void schedule_store(int flag)
{
bt_s32_t timeout;
atomic_set_bit(bt_mesh.flags, flag);
if (atomic_test_bit(bt_mesh.flags, BT_MESH_NET_PENDING) || atomic_test_bit(bt_mesh.flags, BT_MESH_IV_PENDING) ||
atomic_test_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING) || atomic_test_bit(bt_mesh.flags, BT_MESH_KEYS_PENDING) ||
atomic_test_bit(bt_mesh.flags, BT_MESH_MOD_PENDING) || atomic_test_bit(bt_mesh.flags, BT_MESH_CFG_PENDING) ||
atomic_test_bit(bt_mesh.flags, BT_MESH_HB_PUB_PENDING)
#ifdef CONFIG_BT_MESH_PROVISIONER
|| atomic_test_bit(bt_mesh.flags, BT_MESH_PROV_NODE_PENDING)
#endif
) {
timeout = K_NO_WAIT;
} else if (atomic_test_bit(bt_mesh.flags, BT_MESH_RPL_PENDING) &&
(CONFIG_BT_MESH_RPL_STORE_TIMEOUT < CONFIG_BT_MESH_STORE_TIMEOUT)) {
timeout = K_SECONDS(CONFIG_BT_MESH_RPL_STORE_TIMEOUT);
} else {
timeout = K_SECONDS(CONFIG_BT_MESH_STORE_TIMEOUT);
}
BT_DBG("Waiting %d seconds", timeout / MSEC_PER_SEC);
k_delayed_work_submit(&pending_store, timeout);
}
static void clear_iv(void)
{
int err;
err = settings_delete("bt/mesh/IV");
if (err) {
BT_ERR("Failed to clear IV");
} else {
BT_DBG("Cleared IV");
}
}
static void clear_net(void)
{
int err;
err = settings_delete("bt/mesh/Net");
if (err) {
BT_ERR("Failed to clear Network");
} else {
BT_DBG("Cleared Network");
}
}
static void store_pending_net(void)
{
struct net_val net;
int err;
BT_DBG("addr 0x%04x DevKey %s", bt_mesh_primary_addr(), bt_hex(bt_mesh.dev_key, 16));
net.primary_addr = bt_mesh_primary_addr();
memcpy(net.dev_key, bt_mesh.dev_key, 16);
err = settings_save_one("bt/mesh/Net", &net, sizeof(net));
if (err) {
BT_ERR("Failed to store Network value");
} else {
BT_DBG("Stored Network value");
}
}
void bt_mesh_store_net(void)
{
schedule_store(BT_MESH_NET_PENDING);
}
static void store_pending_iv(void)
{
struct iv_val iv;
int err;
iv.iv_index = bt_mesh.iv_index;
iv.iv_update = atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
iv.iv_duration = bt_mesh.ivu_duration;
err = settings_save_one("bt/mesh/IV", &iv, sizeof(iv));
if (err) {
BT_ERR("Failed to store IV value");
} else {
BT_DBG("Stored IV value");
}
}
void bt_mesh_store_iv(bool only_duration)
{
schedule_store(BT_MESH_IV_PENDING);
if (!only_duration) {
/* Always update Seq whenever IV changes */
schedule_store(BT_MESH_SEQ_PENDING);
}
}
static void store_pending_seq(void)
{
struct seq_val seq;
int err;
sys_put_le24(bt_mesh.seq, seq.val);
err = settings_save_one("bt/mesh/Seq", &seq, sizeof(seq));
if (err) {
BT_ERR("Failed to stor Seq value");
} else {
BT_DBG("Stored Seq value");
}
}
void bt_mesh_store_seq(void)
{
if (CONFIG_BT_MESH_SEQ_STORE_RATE && (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)) {
return;
}
schedule_store(BT_MESH_SEQ_PENDING);
}
static void store_rpl(struct bt_mesh_rpl *entry)
{
struct rpl_val rpl;
char path[18];
int err;
BT_DBG("src 0x%04x seq 0x%06x old_iv %u", entry->src, entry->seq, entry->old_iv);
rpl.seq = entry->seq;
rpl.old_iv = entry->old_iv;
snprintk(path, sizeof(path), "bt/mesh/RPL/%x", entry->src);
err = settings_save_one(path, &rpl, sizeof(rpl));
if (err) {
BT_ERR("Failed to store RPL %s value", log_strdup(path));
} else {
BT_DBG("Stored RPL %s value", log_strdup(path));
}
}
static void clear_rpl(void)
{
int i, err;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
char path[18];
if (!rpl->src) {
continue;
}
snprintk(path, sizeof(path), "bt/mesh/RPL/%x", rpl->src);
err = settings_delete(path);
if (err) {
BT_ERR("Failed to clear RPL");
} else {
BT_DBG("Cleared RPL");
}
(void)memset(rpl, 0, sizeof(*rpl));
}
}
static void store_pending_rpl(void)
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
if (rpl->store) {
rpl->store = false;
store_rpl(rpl);
}
}
}
static void store_pending_hb_pub(void)
{
struct bt_mesh_hb_pub *pub = bt_mesh_hb_pub_get();
struct hb_pub_val val;
int err;
if (!pub) {
return;
}
if (pub->dst == BT_MESH_ADDR_UNASSIGNED) {
err = settings_delete("bt/mesh/HBPub");
} else {
val.indefinite = (pub->count == 0xffff);
val.dst = pub->dst;
val.period = pub->period;
val.ttl = pub->ttl;
val.feat = pub->feat;
val.net_idx = pub->net_idx;
err = settings_save_one("bt/mesh/HBPub", &val, sizeof(val));
}
if (err) {
BT_ERR("Failed to store Heartbeat Publication");
} else {
BT_DBG("Stored Heartbeat Publication");
}
}
static void store_pending_cfg(void)
{
struct bt_mesh_cfg_srv *cfg = bt_mesh_cfg_get();
struct cfg_val val;
int err;
if (!cfg) {
return;
}
val.net_transmit = cfg->net_transmit;
val.relay = cfg->relay;
val.relay_retransmit = cfg->relay_retransmit;
val.beacon = cfg->beacon;
val.gatt_proxy = cfg->gatt_proxy;
val.frnd = cfg->frnd;
val.default_ttl = cfg->default_ttl;
err = settings_save_one("bt/mesh/Cfg", &val, sizeof(val));
if (err) {
BT_ERR("Failed to store configuration value");
} else {
BT_DBG("Stored configuration value");
BT_HEXDUMP_DBG(&val, sizeof(val), "raw value");
}
}
static void clear_cfg(void)
{
int err;
err = settings_delete("bt/mesh/Cfg");
if (err) {
BT_ERR("Failed to clear configuration");
} else {
BT_DBG("Cleared configuration");
}
}
static void clear_app_key(u16_t app_idx, bool p_key)
{
int err;
char path[21];
BT_DBG("AppKeyIndex 0x%03x", app_idx);
#ifdef CONFIG_BT_MESH_PROVISIONER
if (p_key) {
snprintk(path, sizeof(path), "bt/mesh/pAppKey/%x", app_idx);
} else
#endif
{
snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app_idx);
}
err = settings_delete(path);
if (err) {
BT_ERR("Failed to clear AppKeyIndex 0x%03x", app_idx);
} else {
BT_DBG("Cleared AppKeyIndex 0x%03x", app_idx);
}
}
static void clear_net_key(u16_t net_idx, bool p_key)
{
int err;
char path[21];
BT_DBG("NetKeyIndex 0x%03x", net_idx);
#ifdef CONFIG_BT_MESH_PROVISIONER
if (p_key) {
snprintk(path, sizeof(path), "bt/mesh/pNetKey/%x", net_idx);
} else
#endif
{
snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", net_idx);
}
err = settings_delete(path);
if (err) {
BT_ERR("Failed to clear NetKeyIndex 0x%03x", net_idx);
} else {
BT_DBG("Cleared NetKeyIndex 0x%03x", net_idx);
}
}
static void store_net_key(struct bt_mesh_subnet *sub, bool p_key)
{
int err;
struct net_key_val key;
char path[21];
BT_DBG("NetKeyIndex 0x%03x NetKey %s", sub->net_idx, bt_hex(sub->keys[0].net, 16));
memcpy(&key.val[0], sub->keys[0].net, 16);
memcpy(&key.val[1], sub->keys[1].net, 16);
key.kr_flag = sub->kr_flag;
key.kr_phase = sub->kr_phase;
#ifdef CONFIG_BT_MESH_PROVISIONER
if (p_key) {
snprintk(path, sizeof(path), "bt/mesh/pNetKey/%x", sub->net_idx);
} else
#endif
{
snprintk(path, sizeof(path), "bt/mesh/NetKey/%x", sub->net_idx);
}
err = settings_save_one(path, &key, sizeof(key));
if (err) {
BT_ERR("Failed to store NetKey value");
} else {
BT_DBG("Stored NetKey value");
}
}
static void store_app_key(struct bt_mesh_app_key *app, bool p_key)
{
int err;
struct app_key_val key;
char path[21];
key.net_idx = app->net_idx;
key.updated = app->updated;
memcpy(key.val[0], app->keys[0].val, 16);
memcpy(key.val[1], app->keys[1].val, 16);
#ifdef CONFIG_BT_MESH_PROVISIONER
if (p_key) {
snprintk(path, sizeof(path), "bt/mesh/pAppKey/%x", app->app_idx);
} else
#endif
{
snprintk(path, sizeof(path), "bt/mesh/AppKey/%x", app->app_idx);
}
err = settings_save_one(path, &key, sizeof(key));
if (err) {
BT_ERR("Failed to store AppKey %s value", log_strdup(path));
} else {
BT_DBG("Stored AppKey %s value", log_strdup(path));
}
}
static void store_pending_keys(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(key_updates); i++) {
struct key_update *update = &key_updates[i];
if (!update->valid) {
continue;
}
if (update->clear) {
if (update->app_key) {
clear_app_key(update->key_idx, update->p_key);
} else {
clear_net_key(update->key_idx, update->p_key);
}
} else {
if (update->app_key) {
struct bt_mesh_app_key *key = NULL;
#ifdef CONFIG_BT_MESH_PROVISIONER
if (update->p_key) {
key = provisioner_app_key_find(update->key_idx);
} else
#endif
{
key = bt_mesh_app_key_find(update->key_idx);
}
if (key) {
store_app_key(key, update->p_key);
} else {
BT_WARN("AppKeyIndex 0x%03x not found", update->key_idx);
}
} else {
struct bt_mesh_subnet *sub;
// #ifdef CONFIG_BT_MESH_PROVISIONER
// if (update->p_key) {
// sub = provisioner_subnet_get(update->key_idx);
// } else
// #endif
{
sub = bt_mesh_subnet_get(update->key_idx);
}
if (sub) {
store_net_key(sub, update->p_key);
} else {
BT_WARN("NetKeyIndex 0x%03x not found", update->key_idx);
}
}
}
update->valid = 0;
}
}
static void encode_mod_path(struct bt_mesh_model *mod, bool vnd, const char *key, char *path, size_t path_len)
{
u16_t mod_key = (((u16_t)mod->elem_idx << 8) | mod->mod_idx);
if (vnd) {
snprintk(path, path_len, "bt/mesh/v/%x/%s", mod_key, key);
} else {
snprintk(path, path_len, "bt/mesh/s/%x/%s", mod_key, key);
}
}
static void store_pending_mod_bind(struct bt_mesh_model *mod, bool vnd)
{
u16_t keys[CONFIG_BT_MESH_MODEL_KEY_COUNT];
char path[20];
int i, count, err;
for (i = 0, count = 0; i < ARRAY_SIZE(mod->keys); i++) {
if (mod->keys[i] != BT_MESH_KEY_UNUSED) {
keys[count++] = mod->keys[i];
}
}
encode_mod_path(mod, vnd, "bind", path, sizeof(path));
if (count) {
err = settings_save_one(path, keys, count * sizeof(keys[0]));
} else {
err = settings_delete(path);
}
if (err) {
BT_ERR("Failed to store %s value", log_strdup(path));
} else {
BT_DBG("Stored %s value", log_strdup(path));
}
}
static void store_pending_mod_sub(struct bt_mesh_model *mod, bool vnd)
{
u16_t groups[CONFIG_BT_MESH_MODEL_GROUP_COUNT];
char path[20];
int i, count, err;
for (i = 0, count = 0; i < ARRAY_SIZE(mod->groups); i++) {
if (mod->groups[i] != BT_MESH_ADDR_UNASSIGNED) {
groups[count++] = mod->groups[i];
}
}
encode_mod_path(mod, vnd, "sub", path, sizeof(path));
if (count) {
err = settings_save_one(path, groups, count * sizeof(groups[0]));
} else {
err = settings_delete(path);
}
if (err) {
BT_ERR("Failed to store %s value", log_strdup(path));
} else {
BT_DBG("Stored %s value", log_strdup(path));
}
}
static void store_pending_mod_pub(struct bt_mesh_model *mod, bool vnd)
{
struct mod_pub_val pub;
char path[20];
int err;
encode_mod_path(mod, vnd, "pub", path, sizeof(path));
if (!mod->pub || mod->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
err = settings_delete(path);
} else {
pub.addr = mod->pub->addr;
pub.key = mod->pub->key;
pub.ttl = mod->pub->ttl;
pub.retransmit = mod->pub->retransmit;
pub.period = mod->pub->period;
pub.period_div = mod->pub->period_div;
pub.cred = mod->pub->cred;
err = settings_save_one(path, &pub, sizeof(pub));
}
if (err) {
BT_ERR("Failed to store %s value", log_strdup(path));
} else {
BT_DBG("Stored %s value", log_strdup(path));
}
}
static void store_pending_mod(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary,
void *user_data)
{
if (!mod->flags) {
return;
}
if (mod->flags & BT_MESH_MOD_BIND_PENDING) {
mod->flags &= ~BT_MESH_MOD_BIND_PENDING;
store_pending_mod_bind(mod, vnd);
}
if (mod->flags & BT_MESH_MOD_SUB_PENDING) {
mod->flags &= ~BT_MESH_MOD_SUB_PENDING;
store_pending_mod_sub(mod, vnd);
}
if (mod->flags & BT_MESH_MOD_PUB_PENDING) {
mod->flags &= ~BT_MESH_MOD_PUB_PENDING;
store_pending_mod_pub(mod, vnd);
}
}
#ifdef CONFIG_BT_MESH_PROVISIONER
static void clear_prov_nodes(int node_index)
{
char path[20] = { 0 };
snprintk(path, sizeof(path), "bt/mesh/Node/%d", node_index);
settings_delete(path);
}
static void store_pending_prov_nodes(void)
{
struct bt_mesh_node_t *node = NULL;
char path[20] = { 0 };
int i;
int node_count = provisioner_get_prov_node_count();
for (i = 0; i < node_count; i++) {
node = bt_mesh_provisioner_get_node_info_by_id(i);
if (node && node->flag == MESH_NODE_FLAG_STORE) {
snprintk(path, sizeof(path), "bt/mesh/Node/%d", i);
settings_save_one(path, node, sizeof(*node));
}
}
}
#endif
static void store_pending(struct k_work *work)
{
BT_DBG("");
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_RPL_PENDING)) {
if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
store_pending_rpl();
} else {
clear_rpl();
}
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_KEYS_PENDING)) {
store_pending_keys();
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_NET_PENDING)) {
if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
store_pending_net();
} else {
clear_net();
}
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IV_PENDING)) {
if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
store_pending_iv();
} else {
clear_iv();
}
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_SEQ_PENDING)) {
store_pending_seq();
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_HB_PUB_PENDING)) {
store_pending_hb_pub();
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_CFG_PENDING)) {
if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
store_pending_cfg();
} else {
clear_cfg();
}
}
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_MOD_PENDING)) {
bt_mesh_model_foreach(store_pending_mod, NULL);
}
#ifdef CONFIG_BT_MESH_PROVISIONER
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_PROV_NODE_PENDING)) {
store_pending_prov_nodes();
}
#endif
}
void bt_mesh_store_rpl(struct bt_mesh_rpl *entry)
{
entry->store = true;
if ((entry->seq) % CONFIG_BT_MESH_RPL_STORE_RATE == 0) {
schedule_store(BT_MESH_RPL_PENDING);
}
}
void bt_mesh_clear_node_rpl(uint16_t addr)
{
char path[18];
BT_DBG("");
snprintk(path, sizeof(path), "bt/mesh/RPL/%x", addr);
settings_delete(path);
return;
}
void bt_mesh_clear_all_node_rpl()
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
char path[18];
if (!rpl->src) {
continue;
}
snprintk(path, sizeof(path), "bt/mesh/RPL/%x", rpl->src);
settings_delete(path);
}
}
static struct key_update *key_update_find(bool app_key, u16_t key_idx, struct key_update **free_slot, bool p_key)
{
struct key_update *match;
int i;
match = NULL;
*free_slot = NULL;
for (i = 0; i < ARRAY_SIZE(key_updates); i++) {
struct key_update *update = &key_updates[i];
if (!update->valid) {
*free_slot = update;
continue;
}
if (update->app_key != app_key) {
continue;
}
if (update->p_key != p_key) {
continue;
}
if (update->key_idx == key_idx) {
match = update;
}
}
return match;
}
void bt_mesh_store_subnet(struct bt_mesh_subnet *sub, bool p_key)
{
struct key_update *update, *free_slot;
BT_DBG("NetKeyIndex 0x%03x", sub->net_idx);
update = key_update_find(false, sub->net_idx, &free_slot, p_key);
if (update) {
update->clear = 0;
schedule_store(BT_MESH_KEYS_PENDING);
return;
}
if (!free_slot) {
store_net_key(sub, p_key);
return;
}
free_slot->valid = 1;
free_slot->key_idx = sub->net_idx;
free_slot->app_key = 0;
free_slot->clear = 0;
free_slot->p_key = p_key;
schedule_store(BT_MESH_KEYS_PENDING);
}
void bt_mesh_store_app_key(struct bt_mesh_app_key *key, bool p_key)
{
struct key_update *update, *free_slot;
BT_DBG("AppKeyIndex 0x%03x", key->app_idx);
update = key_update_find(true, key->app_idx, &free_slot, p_key);
if (update) {
update->clear = 0;
schedule_store(BT_MESH_KEYS_PENDING);
return;
}
if (!free_slot) {
store_app_key(key, p_key);
return;
}
free_slot->valid = 1;
free_slot->key_idx = key->app_idx;
free_slot->app_key = 1;
free_slot->clear = 0;
free_slot->p_key = p_key;
schedule_store(BT_MESH_KEYS_PENDING);
}
void bt_mesh_store_hb_pub(void)
{
schedule_store(BT_MESH_HB_PUB_PENDING);
}
void bt_mesh_store_cfg(void)
{
schedule_store(BT_MESH_CFG_PENDING);
}
void bt_mesh_clear_net(void)
{
schedule_store(BT_MESH_NET_PENDING);
schedule_store(BT_MESH_IV_PENDING);
schedule_store(BT_MESH_CFG_PENDING);
}
void bt_mesh_clear_subnet(struct bt_mesh_subnet *sub, bool p_key)
{
struct key_update *update, *free_slot;
BT_DBG("NetKeyIndex 0x%03x", sub->net_idx);
update = key_update_find(false, sub->net_idx, &free_slot, p_key);
if (update) {
update->clear = 1;
schedule_store(BT_MESH_KEYS_PENDING);
return;
}
if (!free_slot) {
clear_net_key(sub->net_idx, p_key);
return;
}
free_slot->valid = 1;
free_slot->key_idx = sub->net_idx;
free_slot->app_key = 0;
free_slot->clear = 1;
free_slot->p_key = p_key;
schedule_store(BT_MESH_KEYS_PENDING);
}
void bt_mesh_clear_app_key(struct bt_mesh_app_key *key, bool p_key)
{
struct key_update *update, *free_slot;
BT_DBG("AppKeyIndex 0x%03x", key->app_idx);
update = key_update_find(true, key->app_idx, &free_slot, p_key);
if (update) {
update->clear = 1;
schedule_store(BT_MESH_KEYS_PENDING);
return;
}
if (!free_slot) {
clear_app_key(key->app_idx, p_key);
return;
}
free_slot->valid = 1;
free_slot->key_idx = key->app_idx;
free_slot->app_key = 1;
free_slot->clear = 1;
free_slot->p_key = p_key;
schedule_store(BT_MESH_KEYS_PENDING);
}
void bt_mesh_clear_rpl(void)
{
schedule_store(BT_MESH_RPL_PENDING);
}
void bt_mesh_store_mod_bind(struct bt_mesh_model *mod)
{
mod->flags |= BT_MESH_MOD_BIND_PENDING;
schedule_store(BT_MESH_MOD_PENDING);
}
void bt_mesh_store_mod_sub(struct bt_mesh_model *mod)
{
mod->flags |= BT_MESH_MOD_SUB_PENDING;
schedule_store(BT_MESH_MOD_PENDING);
}
void bt_mesh_store_mod_pub(struct bt_mesh_model *mod)
{
mod->flags |= BT_MESH_MOD_PUB_PENDING;
schedule_store(BT_MESH_MOD_PENDING);
}
static void store_pending_mod_check(struct bt_mesh_model *mod, struct bt_mesh_elem *elem, bool vnd, bool primary,
void *user_data)
{
uint8_t *is_pending = user_data;
if (!mod->flags) {
return;
}
if (mod->flags & BT_MESH_MOD_BIND_PENDING) {
*is_pending |= BT_MESH_MOD_BIND_PENDING;
}
if (mod->flags & BT_MESH_MOD_SUB_PENDING) {
*is_pending |= BT_MESH_MOD_SUB_PENDING;
}
if (mod->flags & BT_MESH_MOD_PUB_PENDING) {
*is_pending |= BT_MESH_MOD_PUB_PENDING;
}
return;
}
int bt_mesh_store_mod_pending_check()
{
uint8_t is_pending = 0;
bt_mesh_model_foreach(store_pending_mod_check, &is_pending);
return is_pending;
}
#ifdef CONFIG_BT_MESH_PROVISIONER
void bt_mesh_clear_mesh_node(int node_index)
{
clear_prov_nodes(node_index);
}
void bt_mesh_store_mesh_node(int node_index)
{
bt_mesh_provisioner_get_node_info_by_id(node_index)->flag = MESH_NODE_FLAG_STORE;
schedule_store(BT_MESH_PROV_NODE_PENDING);
}
#endif
void bt_mesh_settings_init(void)
{
k_delayed_work_init(&pending_store, store_pending);
SETTINGS_HANDLER_DEFINE(bt_mesh, "bt/mesh", NULL, mesh_set, mesh_commit, NULL);
}
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/settings.c | C | apache-2.0 | 47,462 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <bt_errno.h>
#include <bluetooth/mesh.h>
#include "common/log.h"
#include "mesh.h"
#include "test.h"
int bt_mesh_test(void)
{
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/test.c | C | apache-2.0 | 285 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <ble_os.h>
#include <bt_errno.h>
#include <string.h>
#include <sys/types.h>
#include <misc/util.h>
#include <misc/byteorder.h>
#include <net/buf.h>
#include <bluetooth/hci.h>
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_TRANS)
#include "common/log.h"
#include "host/testing.h"
#include "crypto.h"
#include "adv.h"
#include "mesh.h"
#include "net.h"
#include "lpn.h"
#include "friend.h"
#include "access.h"
#include "foundation.h"
#include "settings.h"
#include "ble_transport.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "provisioner_proxy.h"
#endif
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
#include "mesh_event_port.h"
#endif
/* The transport layer needs at least three buffers for itself to avoid
* deadlocks. Ensure that there are a sufficient number of advertising
* buffers available compared to the maximum supported outgoing segment
* count.
*/
BUILD_ASSERT(CONFIG_BT_MESH_ADV_BUF_COUNT >= (CONFIG_BT_MESH_TX_SEG_MAX + 3));
#define AID_MASK ((u8_t)(BIT_MASK(6)))
#define SEG(data) ((data)[0] >> 7)
#define AKF(data) (((data)[0] >> 6) & 0x01)
#define AID(data) ((data)[0] & AID_MASK)
#define ASZMIC(data) (((data)[1] >> 7) & 1)
#define APP_MIC_LEN(aszmic) ((aszmic) ? 8 : 4)
#define UNSEG_HDR(akf, aid) ((akf << 6) | (aid & AID_MASK))
#define SEG_HDR(akf, aid) (UNSEG_HDR(akf, aid) | 0x80)
#define BLOCK_COMPLETE(seg_n) (bt_u32_t)(((u64_t)1 << (seg_n + 1)) - 1)
#define SEQ_AUTH(iv_index, seq) (((u64_t)iv_index) << 24 | (u64_t)seq)
#ifndef CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS
#define CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS 4
#endif
/* Number of retransmit attempts (after the initial transmit) per segment */
#define SEG_RETRANSMIT_ATTEMPTS CONFIG_BT_MESH_SEG_RETRANSMIT_ATTEMPTS
#ifndef CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT
#define CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT 400
/* "This timer shall be set to a minimum of 200 + 50 * TTL milliseconds.".
* We use 400 since 300 is a common send duration for standard HCI, and we
* need to have a timeout that's bigger than that.
*/
#define SEG_RETRANSMIT_TIMEOUT(tx) (K_MSEC(CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT) + 50 * (tx)->ttl)
#else
#define SEG_RETRANSMIT_TIMEOUT(tx) K_MSEC(CONFIG_BT_MESH_SEG_RETRANSMIT_TIMEOUT)
#endif
/* How long to wait for available buffers before giving up */
#define BUF_TIMEOUT K_NO_WAIT
static struct seg_tx {
struct bt_mesh_subnet *sub;
struct net_buf *seg[CONFIG_BT_MESH_TX_SEG_MAX];
u64_t seq_auth;
u16_t dst;
u8_t seg_n:5, /* Last segment index */
new_key:1; /* New/old key */
u8_t nack_count; /* Number of unacked segs */
u8_t ttl;
const struct bt_mesh_send_cb *cb;
void *cb_data;
struct k_delayed_work retransmit; /* Retransmit timer */
} seg_tx[CONFIG_BT_MESH_TX_SEG_MSG_COUNT];
static struct seg_rx {
struct bt_mesh_subnet *sub;
u64_t seq_auth;
u8_t seg_n:5, ctl:1, in_use:1, obo:1;
u8_t hdr;
u8_t ttl;
u16_t src;
u16_t dst;
bt_u32_t block;
bt_u32_t last;
struct k_delayed_work ack;
struct net_buf_simple buf;
} seg_rx[CONFIG_BT_MESH_RX_SEG_MSG_COUNT] = {
[0 ... (CONFIG_BT_MESH_RX_SEG_MSG_COUNT - 1)] = {
.buf.size = CONFIG_BT_MESH_RX_SDU_MAX,
},
};
static u8_t __noinit seg_rx_buf_data[(CONFIG_BT_MESH_RX_SEG_MSG_COUNT * CONFIG_BT_MESH_RX_SDU_MAX)];
static u16_t hb_sub_dst = BT_MESH_ADDR_UNASSIGNED;
void bt_mesh_set_hb_sub_dst(u16_t addr)
{
hb_sub_dst = addr;
}
static int send_unseg(struct bt_mesh_net_tx *tx, struct net_buf_simple *sdu, const struct bt_mesh_send_cb *cb,
void *cb_data)
{
struct net_buf *buf;
BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x sdu_len %u", tx->src, tx->ctx->addr, tx->ctx->app_idx, sdu->len);
buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
if (!buf) {
BT_ERR("Out of network buffers");
return -ENOBUFS;
}
net_buf_reserve(buf, BT_MESH_NET_HDR_LEN);
if (tx->ctx->app_idx == BT_MESH_KEY_DEV) {
net_buf_add_u8(buf, UNSEG_HDR(0, 0));
} else {
net_buf_add_u8(buf, UNSEG_HDR(1, tx->aid));
}
net_buf_add_mem(buf, sdu->data, sdu->len);
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, NULL, &buf->b) &&
BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
/* PDUs for a specific Friend should only go
* out through the Friend Queue.
*/
net_buf_unref(buf);
return 0;
}
}
return bt_mesh_net_send(tx, buf, cb, cb_data);
}
bool bt_mesh_tx_in_progress(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
if (seg_tx[i].nack_count) {
return true;
}
}
return false;
}
static void seg_tx_reset(struct seg_tx *tx)
{
int i;
k_delayed_work_cancel(&tx->retransmit);
tx->cb = NULL;
tx->cb_data = NULL;
tx->seq_auth = 0;
tx->sub = NULL;
tx->dst = BT_MESH_ADDR_UNASSIGNED;
if (!tx->nack_count) {
return;
}
for (i = 0; i <= tx->seg_n; i++) {
if (!tx->seg[i]) {
continue;
}
net_buf_unref(tx->seg[i]);
tx->seg[i] = NULL;
}
tx->nack_count = 0;
if (atomic_test_and_clear_bit(bt_mesh.flags, BT_MESH_IVU_PENDING)) {
BT_DBG("Proceding with pending IV Update");
/* bt_mesh_net_iv_update() will re-enable the flag if this
* wasn't the only transfer.
*/
if (bt_mesh_net_iv_update(bt_mesh.iv_index, false)) {
bt_mesh_net_sec_update(NULL);
}
}
}
static inline void seg_tx_complete(struct seg_tx *tx, int err)
{
if (tx->cb && tx->cb->end) {
tx->cb->end(err, tx->cb_data);
}
seg_tx_reset(tx);
}
static void seg_first_send_start(u16_t duration, int err, void *user_data)
{
struct seg_tx *tx = user_data;
if (tx->cb && tx->cb->start) {
tx->cb->start(duration, err, tx->cb_data);
}
}
static void seg_send_start(u16_t duration, int err, void *user_data)
{
struct seg_tx *tx = user_data;
/* If there's an error in transmitting the 'sent' callback will never
* be called. Make sure that we kick the retransmit timer also in this
* case since otherwise we risk the transmission of becoming stale.
*/
if (err && BT_MESH_ADDR_IS_UNICAST(tx->dst)) {
k_delayed_work_submit(&tx->retransmit, SEG_RETRANSMIT_TIMEOUT(tx));
}
}
static void seg_sent(int err, void *user_data)
{
struct seg_tx *tx = user_data;
/*[Genie begin] add by lgy at 2020-09-14*/
/*Don't retransmit if dst addr is not unicast*/
if (!BT_MESH_ADDR_IS_UNICAST(tx->dst)) {
seg_tx_complete(tx, -ENOPROTOOPT);
} else {
k_delayed_work_submit(&tx->retransmit, SEG_RETRANSMIT_TIMEOUT(tx));
}
/*[Genie end]*/
}
static const struct bt_mesh_send_cb first_sent_cb = {
.start = seg_first_send_start,
.end = seg_sent,
};
static const struct bt_mesh_send_cb seg_sent_cb = {
.start = seg_send_start,
.end = seg_sent,
};
static void seg_tx_send_unacked(struct seg_tx *tx)
{
int i, err;
for (i = 0; i <= tx->seg_n; i++) {
struct net_buf *seg = tx->seg[i];
if (!seg) {
continue;
}
if (BT_MESH_ADV(seg)->busy) {
BT_DBG("Skipping segment that's still advertising");
continue;
}
if (!(BT_MESH_ADV(seg)->seg.attempts--)) {
BT_WARN("Ran out of retransmit attempts");
seg_tx_complete(tx, -ETIMEDOUT);
return;
}
if (!tx->nack_count) {
return;
}
BT_DBG("resending %u/%u", i, tx->seg_n);
err = bt_mesh_net_resend(tx->sub, seg, tx->new_key, &seg_sent_cb, tx);
if (err) {
BT_WARN("ReSending segment failed");
seg_tx_complete(tx, -EIO);
return;
}
}
}
static void seg_retransmit(struct k_work *work)
{
struct seg_tx *tx = CONTAINER_OF(work, struct seg_tx, retransmit);
seg_tx_send_unacked(tx);
}
static int send_seg(struct bt_mesh_net_tx *net_tx, struct net_buf_simple *sdu, const struct bt_mesh_send_cb *cb,
void *cb_data)
{
u8_t seg_hdr, seg_o;
u16_t seq_zero;
struct seg_tx *tx;
int i;
BT_DBG("src 0x%04x dst 0x%04x app_idx 0x%04x aszmic %u sdu_len %u", net_tx->src, net_tx->ctx->addr,
net_tx->ctx->app_idx, net_tx->aszmic, sdu->len);
if (sdu->len < 1) {
BT_ERR("Zero-length SDU not allowed");
return -EINVAL;
}
if (((sdu->len + 11) / 12) > CONFIG_BT_MESH_TX_SEG_MAX) {
BT_ERR("Not enough segment buffers for length %u", sdu->len);
return -EMSGSIZE;
}
for (tx = NULL, i = 0; i < ARRAY_SIZE(seg_tx); i++) {
if (!seg_tx[i].nack_count) {
tx = &seg_tx[i];
break;
}
}
if (!tx) {
BT_ERR("No multi-segment message contexts available");
return -EBUSY;
}
if (net_tx->ctx->app_idx == BT_MESH_KEY_DEV) {
seg_hdr = SEG_HDR(0, 0);
} else {
seg_hdr = SEG_HDR(1, net_tx->aid);
}
seg_o = 0;
tx->dst = net_tx->ctx->addr;
tx->seg_n = (sdu->len - 1) / 12;
tx->nack_count = tx->seg_n + 1;
tx->seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_TX, bt_mesh.seq);
tx->sub = net_tx->sub;
tx->new_key = net_tx->sub->kr_flag;
tx->cb = cb;
tx->cb_data = cb_data;
if (net_tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) {
tx->ttl = bt_mesh_default_ttl_get();
} else {
tx->ttl = net_tx->ctx->send_ttl;
}
seq_zero = tx->seq_auth & 0x1fff;
BT_DBG("SeqZero 0x%04x", seq_zero);
for (seg_o = 0; sdu->len; seg_o++) {
struct net_buf *seg;
u16_t len;
int err;
seg = bt_mesh_adv_create(BT_MESH_ADV_DATA, net_tx->xmit, BUF_TIMEOUT);
if (!seg) {
BT_ERR("Out of segment buffers");
seg_tx_reset(tx);
return -ENOBUFS;
}
BT_MESH_ADV(seg)->seg.attempts = SEG_RETRANSMIT_ATTEMPTS;
net_buf_reserve(seg, BT_MESH_NET_HDR_LEN);
net_buf_add_u8(seg, seg_hdr);
net_buf_add_u8(seg, (net_tx->aszmic << 7) | seq_zero >> 6);
net_buf_add_u8(seg, (((seq_zero & 0x3f) << 2) | (seg_o >> 3)));
net_buf_add_u8(seg, ((seg_o & 0x07) << 5) | tx->seg_n);
len = MIN(sdu->len, 12);
net_buf_add_mem(seg, sdu->data, len);
net_buf_simple_pull(sdu, len);
tx->seg[seg_o] = net_buf_ref(seg);
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
enum bt_mesh_friend_pdu_type type;
if (seg_o == tx->seg_n) {
type = BT_MESH_FRIEND_PDU_COMPLETE;
} else {
type = BT_MESH_FRIEND_PDU_PARTIAL;
}
if (bt_mesh_friend_enqueue_tx(net_tx, type, &tx->seq_auth, &seg->b) &&
BT_MESH_ADDR_IS_UNICAST(net_tx->ctx->addr)) {
/* PDUs for a specific Friend should only go
* out through the Friend Queue.
*/
net_buf_unref(seg);
return 0;
}
}
BT_DBG("Sending %u/%u", seg_o, tx->seg_n);
err = bt_mesh_net_send(net_tx, seg, seg_o ? &seg_sent_cb : &first_sent_cb, tx);
if (err) {
BT_ERR("Sending segment failed");
seg_tx_reset(tx);
return err;
}
}
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && bt_mesh_lpn_established()) {
bt_mesh_lpn_poll();
}
return 0;
}
struct bt_mesh_app_key *bt_mesh_app_key_find(u16_t app_idx)
{
int i;
for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
if (key->net_idx != BT_MESH_KEY_UNUSED && key->app_idx == app_idx) {
return key;
}
}
return NULL;
}
int bt_mesh_trans_send(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, const struct bt_mesh_send_cb *cb,
void *cb_data)
{
const u8_t *key;
u8_t *ad;
int err;
if (net_buf_simple_tailroom(msg) < 4) {
BT_ERR("Insufficient tailroom for Transport MIC");
return -EINVAL;
}
if (msg->len > 11) {
tx->ctx->send_rel = 1;
/*reduce packect when send large packet to unicast addr to avoid network storm*/
if (BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
tx->xmit = 0;
}
}
BT_DBG("net_idx 0x%04x app_idx 0x%04x dst 0x%04x", tx->sub->net_idx, tx->ctx->app_idx, tx->ctx->addr);
BT_DBG("len %u: %s", msg->len, bt_hex(msg->data, msg->len));
if (tx->ctx->app_idx == BT_MESH_KEY_DEV) {
#ifdef CONFIG_BT_MESH_PROVISIONER
// if (bt_mesh_is_provisioner_en() && tx->ctx->addr != bt_mesh_primary_addr()) {
key = provisioner_get_device_key(tx->ctx->addr);
// } else {
if (!key) {
key = bt_mesh.dev_key;
}
// }
#else
key = bt_mesh.dev_key;
#endif
tx->aid = 0;
} else {
struct bt_mesh_app_key *app_key = NULL;
// #ifdef CONFIG_BT_MESH_PROVISIONER
// if (bt_mesh_is_provisioner_en()) {
// app_key = provisioner_app_key_find(tx->ctx->app_idx);
// }
// #else
app_key = bt_mesh_app_key_find(tx->ctx->app_idx);
// #endif
if (!app_key) {
return -EINVAL;
}
if (tx->sub->kr_phase == BT_MESH_KR_PHASE_2 && app_key->updated) {
key = app_key->keys[1].val;
tx->aid = app_key->keys[1].id;
} else {
key = app_key->keys[0].val;
tx->aid = app_key->keys[0].id;
}
}
if (!tx->ctx->send_rel || net_buf_simple_tailroom(msg) < 8) {
tx->aszmic = 0;
} else {
tx->aszmic = 1;
}
if (BT_MESH_ADDR_IS_VIRTUAL(tx->ctx->addr)) {
ad = bt_mesh_label_uuid_get(tx->ctx->addr);
} else {
ad = NULL;
}
err = bt_mesh_app_encrypt(key, tx->ctx->app_idx == BT_MESH_KEY_DEV, tx->aszmic, msg, ad, tx->src, tx->ctx->addr,
bt_mesh.seq, BT_MESH_NET_IVI_TX);
if (err) {
return err;
}
if (tx->ctx->send_rel) {
err = send_seg(tx, msg, cb, cb_data);
} else {
err = send_unseg(tx, msg, cb, cb_data);
}
return err;
}
int bt_mesh_trans_resend(struct bt_mesh_net_tx *tx, struct net_buf_simple *msg, const struct bt_mesh_send_cb *cb,
void *cb_data)
{
struct net_buf_simple_state state;
int err;
net_buf_simple_save(msg, &state);
if (tx->ctx->send_rel || msg->len > 15) {
err = send_seg(tx, msg, cb, cb_data);
} else {
err = send_unseg(tx, msg, cb, cb_data);
}
net_buf_simple_restore(msg, &state);
return err;
}
static bool is_replay(struct bt_mesh_net_rx *rx)
{
static uint8_t index = 0;
int i = 0;
struct bt_mesh_rpl *rpl = NULL;
/* Don't bother checking messages from ourselves */
if (rx->net_if == BT_MESH_NET_IF_LOCAL) {
return false;
}
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
rpl = &bt_mesh.rpl[i];
/* Empty slot */
if (!rpl->src) {
rpl->src = rx->ctx.addr;
rpl->seq = rx->seq;
rpl->old_iv = rx->old_iv;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_rpl(rpl);
}
return false;
}
/* Existing slot for given address */
if (rpl->src == rx->ctx.addr) {
if (rx->old_iv && !rpl->old_iv) {
return true;
}
if ((!rx->old_iv && rpl->old_iv) || rpl->seq < rx->seq) {
rpl->seq = rx->seq;
rpl->old_iv = rx->old_iv;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_rpl(rpl);
}
return false;
} else {
return true;
}
}
}
/*[genie begin] changed by lgy at 2020-12-09*/
// overlap rpl when it is full
BT_WARN("RPL is full:%d", index);
rpl = &bt_mesh.rpl[index];
rpl->src = rx->ctx.addr;
rpl->seq = rx->seq;
rpl->old_iv = rx->old_iv;
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_store_rpl(rpl);
}
index++;
index = index % CONFIG_BT_MESH_CRPL;
#ifdef CONFIG_BT_MESH_EVENT_CALLBACK
mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
if (event_cb) {
event_cb(BT_MESH_MODEL_EVT_RPL_IS_FULL, NULL);
}
#endif
return false;
/*[genie end] changed by lgy at 2020-12-09*/
}
static int sdu_recv(struct bt_mesh_net_rx *rx, bt_u32_t seq, u8_t hdr, u8_t aszmic, struct net_buf_simple *buf)
{
NET_BUF_SIMPLE_DEFINE(sdu, CONFIG_BT_MESH_RX_SDU_MAX - 4);
u8_t *ad;
u16_t i;
int err;
BT_DBG("ASZMIC %u AKF %u AID 0x%02x", aszmic, AKF(&hdr), AID(&hdr));
BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
if (buf->len < 1 + APP_MIC_LEN(aszmic)) {
BT_ERR("Too short SDU + MIC");
return -EINVAL;
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !rx->local_match) {
BT_DBG("Ignoring PDU for LPN 0x%04x of this Friend", rx->ctx.recv_dst);
return 0;
}
if (BT_MESH_ADDR_IS_VIRTUAL(rx->ctx.recv_dst)) {
ad = bt_mesh_label_uuid_get(rx->ctx.recv_dst);
} else {
ad = NULL;
}
/* Adjust the length to not contain the MIC at the end */
buf->len -= APP_MIC_LEN(aszmic);
if (!AKF(&hdr)) {
const u8_t *dev_key = NULL;
#ifdef CONFIG_BT_MESH_PROVISIONER
dev_key = provisioner_get_device_key(rx->ctx.addr);
if (!dev_key) {
dev_key = bt_mesh.dev_key;
}
#else
dev_key = bt_mesh.dev_key;
#endif
if (!dev_key) {
BT_DBG("%s: get NULL dev_key", __func__);
return -EINVAL;
}
err = bt_mesh_app_decrypt(dev_key, true, aszmic, buf, &sdu, ad, rx->ctx.addr, rx->ctx.recv_dst, seq,
BT_MESH_NET_IVI_RX(rx));
if (err) {
BT_ERR("Unable to decrypt with DevKey %d", err);
return -EINVAL;
}
rx->ctx.app_idx = BT_MESH_KEY_DEV;
bt_mesh_model_recv(rx, &sdu);
return 0;
}
bt_u32_t array_size = 0;
array_size = ARRAY_SIZE(bt_mesh.app_keys);
for (i = 0; i < array_size; i++) {
struct bt_mesh_app_key *key;
struct bt_mesh_app_keys *keys;
key = &bt_mesh.app_keys[i];
/* Check that this AppKey matches received net_idx */
if (key->net_idx != rx->sub->net_idx) {
continue;
}
if (rx->new_key && key->updated) {
keys = &key->keys[1];
} else {
keys = &key->keys[0];
}
/* Check that the AppKey ID matches */
if (AID(&hdr) != keys->id) {
continue;
}
net_buf_simple_reset(&sdu);
err = bt_mesh_app_decrypt(keys->val, false, aszmic, buf, &sdu, ad, rx->ctx.addr, rx->ctx.recv_dst, seq,
BT_MESH_NET_IVI_RX(rx));
if (err) {
BT_WARN("Unable to decrypt with AppKey 0x%03x", key->app_idx);
continue;
}
rx->ctx.app_idx = key->app_idx;
bt_mesh_model_recv(rx, &sdu);
return 0;
}
BT_WARN("No matching AppKey");
return -EINVAL;
}
static struct seg_tx *seg_tx_lookup(u16_t seq_zero, u8_t obo, u16_t addr)
{
struct seg_tx *tx;
int i;
for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
tx = &seg_tx[i];
if ((tx->seq_auth & 0x1fff) != seq_zero) {
continue;
}
if (tx->dst == addr) {
return tx;
}
/* If the expected remote address doesn't match,
* but the OBO flag is set and this is the first
* acknowledgement, assume it's a Friend that's
* responding and therefore accept the message.
*/
if (obo && tx->nack_count == tx->seg_n + 1) {
tx->dst = addr;
return tx;
}
}
return NULL;
}
static int trans_ack(struct bt_mesh_net_rx *rx, u8_t hdr, struct net_buf_simple *buf, u64_t *seq_auth)
{
struct seg_tx *tx;
unsigned int bit;
bt_u32_t ack;
u16_t seq_zero;
u8_t obo;
if (buf->len < 6) {
BT_ERR("Too short ack message");
return -EINVAL;
}
seq_zero = net_buf_simple_pull_be16(buf);
obo = seq_zero >> 15;
seq_zero = (seq_zero >> 2) & 0x1fff;
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match) {
BT_DBG("Ack for LPN 0x%04x of this Friend", rx->ctx.recv_dst);
/* Best effort - we don't have enough info for true SeqAuth */
*seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(rx), seq_zero);
return 0;
}
ack = net_buf_simple_pull_be32(buf);
BT_DBG("OBO %u seq_zero 0x%04x ack 0x%08x", obo, seq_zero, ack);
tx = seg_tx_lookup(seq_zero, obo, rx->ctx.addr);
if (!tx) {
BT_WARN("No matching TX context for ack");
return -EINVAL;
}
*seq_auth = tx->seq_auth;
if (!ack) {
BT_WARN("SDU canceled");
seg_tx_complete(tx, -ECANCELED);
return 0;
}
if (find_msb_set(ack) - 1 > tx->seg_n) {
BT_ERR("Too large segment number in ack");
return -EINVAL;
}
k_delayed_work_cancel(&tx->retransmit);
while ((bit = find_lsb_set(ack))) {
if (tx->seg[bit - 1]) {
BT_DBG("seg %u/%u acked", bit - 1, tx->seg_n);
net_buf_unref(tx->seg[bit - 1]);
tx->seg[bit - 1] = NULL;
tx->nack_count--;
}
ack &= ~BIT(bit - 1);
}
if (tx->nack_count) {
// seg_tx_send_unacked(tx);
k_delayed_work_submit(&tx->retransmit, 0);
} else {
BT_DBG("SDU TX complete");
seg_tx_complete(tx, 0);
}
return 0;
}
static int trans_heartbeat(struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
{
u8_t init_ttl, hops;
u16_t feat;
if (buf->len < 3) {
BT_ERR("Too short heartbeat message");
return -EINVAL;
}
if (rx->ctx.recv_dst != hb_sub_dst) {
BT_WARN("Ignoring heartbeat to non-subscribed destination");
return 0;
}
init_ttl = (net_buf_simple_pull_u8(buf) & 0x7f);
feat = net_buf_simple_pull_be16(buf);
hops = (init_ttl - rx->ctx.recv_ttl + 1);
BT_DBG("src 0x%04x TTL %u InitTTL %u (%u hop%s) feat 0x%04x", rx->ctx.addr, rx->ctx.recv_ttl, init_ttl, hops,
(hops == 1) ? "" : "s", feat);
bt_mesh_heartbeat(rx->ctx.addr, rx->ctx.recv_dst, hops, feat);
return 0;
}
static int ctl_recv(struct bt_mesh_net_rx *rx, u8_t hdr, struct net_buf_simple *buf, u64_t *seq_auth)
{
u8_t ctl_op = TRANS_CTL_OP(&hdr);
BT_DBG("OpCode 0x%02x len %u", ctl_op, buf->len);
switch (ctl_op) {
case TRANS_CTL_OP_ACK:
return trans_ack(rx, hdr, buf, seq_auth);
case TRANS_CTL_OP_HEARTBEAT:
return trans_heartbeat(rx, buf);
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
case TRANS_CTL_OP_CTRL_RELAY_STATUS:
case TRANS_CTL_OP_CTRL_RELAY_REQ:
case TRANS_CTL_OP_CTRL_RELAY_OPEN:
return ctrl_relay_msg_recv(ctl_op, rx, buf);
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
}
/* Only acks and heartbeats may need processing without local_match */
if (!rx->local_match) {
return 0;
}
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && !bt_mesh_lpn_established()) {
switch (ctl_op) {
case TRANS_CTL_OP_FRIEND_POLL:
return bt_mesh_friend_poll(rx, buf);
case TRANS_CTL_OP_FRIEND_REQ:
return bt_mesh_friend_req(rx, buf);
case TRANS_CTL_OP_FRIEND_CLEAR:
return bt_mesh_friend_clear(rx, buf);
case TRANS_CTL_OP_FRIEND_CLEAR_CFM:
return bt_mesh_friend_clear_cfm(rx, buf);
case TRANS_CTL_OP_FRIEND_SUB_ADD:
return bt_mesh_friend_sub_add(rx, buf);
case TRANS_CTL_OP_FRIEND_SUB_REM:
return bt_mesh_friend_sub_rem(rx, buf);
}
}
#if defined(CONFIG_BT_MESH_LOW_POWER)
if (ctl_op == TRANS_CTL_OP_FRIEND_OFFER) {
return bt_mesh_lpn_friend_offer(rx, buf);
}
if (rx->ctx.addr == bt_mesh.lpn.frnd) {
if (ctl_op == TRANS_CTL_OP_FRIEND_CLEAR_CFM) {
return bt_mesh_lpn_friend_clear_cfm(rx, buf);
}
if (!rx->friend_cred) {
BT_WARN("Message from friend with wrong credentials");
return -EINVAL;
}
switch (ctl_op) {
case TRANS_CTL_OP_FRIEND_UPDATE:
return bt_mesh_lpn_friend_update(rx, buf);
case TRANS_CTL_OP_FRIEND_SUB_CFM:
return bt_mesh_lpn_friend_sub_cfm(rx, buf);
}
}
#endif /* CONFIG_BT_MESH_LOW_POWER */
BT_WARN("Unhandled TransOpCode 0x%02x", ctl_op);
return -ENOENT;
}
static int trans_unseg(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx, u64_t *seq_auth)
{
u8_t hdr;
BT_DBG("AFK %u AID 0x%02x", AKF(buf->data), AID(buf->data));
if (buf->len < 1) {
BT_ERR("Too small unsegmented PDU");
return -EINVAL;
}
if (rx->local_match && is_replay(rx)) {
BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", rx->ctx.addr, rx->ctx.recv_dst, rx->seq);
return -EINVAL;
}
hdr = net_buf_simple_pull_u8(buf);
if (rx->ctl) {
return ctl_recv(rx, hdr, buf, seq_auth);
} else {
/* SDUs must match a local element or an LPN of this Friend. */
if (!rx->local_match && !rx->friend_match) {
return 0;
}
return sdu_recv(rx, rx->seq, hdr, 0, buf);
}
}
static inline bt_s32_t ack_timeout(struct seg_rx *rx)
{
bt_s32_t to;
u8_t ttl;
if (rx->ttl == BT_MESH_TTL_DEFAULT) {
ttl = bt_mesh_default_ttl_get();
} else {
ttl = rx->ttl;
}
/* The acknowledgment timer shall be set to a minimum of
* 150 + 50 * TTL milliseconds.
*/
to = K_MSEC(150 + (50 * ttl));
/* 100 ms for every not yet received segment */
to += K_MSEC(((rx->seg_n + 1) - popcount(rx->block)) * 100);
/* Make sure we don't send more frequently than the duration for
* each packet (default is 300ms).
*/
return MAX(to, K_MSEC(400));
}
int bt_mesh_ctl_send(struct bt_mesh_net_tx *tx, u8_t ctl_op, void *data, size_t data_len, u64_t *seq_auth,
const struct bt_mesh_send_cb *cb, void *cb_data)
{
struct net_buf *buf;
BT_DBG("src 0x%04x dst 0x%04x ttl 0x%02x ctl 0x%02x", tx->src, tx->ctx->addr, tx->ctx->send_ttl, ctl_op);
BT_DBG("len %zu: %s", data_len, bt_hex(data, data_len));
buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, tx->xmit, BUF_TIMEOUT);
if (!buf) {
BT_ERR("Out of transport buffers");
return -ENOBUFS;
}
net_buf_reserve(buf, BT_MESH_NET_HDR_LEN);
net_buf_add_u8(buf, TRANS_CTL_HDR(ctl_op, 0));
net_buf_add_mem(buf, data, data_len);
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
if (bt_mesh_friend_enqueue_tx(tx, BT_MESH_FRIEND_PDU_SINGLE, seq_auth, &buf->b) &&
BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
/* PDUs for a specific Friend should only go
* out through the Friend Queue.
*/
net_buf_unref(buf);
return 0;
}
}
return bt_mesh_net_send(tx, buf, cb, cb_data);
}
static int send_ack(struct bt_mesh_subnet *sub, u16_t src, u16_t dst, u8_t ttl, u64_t *seq_auth, bt_u32_t block,
u8_t obo)
{
struct bt_mesh_msg_ctx ctx = {
.net_idx = sub->net_idx,
.app_idx = BT_MESH_KEY_UNUSED,
.addr = dst,
.send_ttl = ttl,
};
struct bt_mesh_net_tx tx = {
.sub = sub,
.ctx = &ctx,
.src = obo ? bt_mesh_primary_addr() : src,
.xmit = bt_mesh_net_transmit_get(),
};
u16_t seq_zero = *seq_auth & 0x1fff;
u8_t buf[6];
BT_DBG("SeqZero 0x%04x Block 0x%08x OBO %u", seq_zero, block, obo);
if (bt_mesh_lpn_established()) {
BT_WARN("Not sending ack when LPN is enabled");
return 0;
}
/* This can happen if the segmented message was destined for a group
* or virtual address.
*/
if (!BT_MESH_ADDR_IS_UNICAST(src)) {
BT_WARN("Not sending ack for non-unicast address");
return 0;
}
sys_put_be16(((seq_zero << 2) & 0x7ffc) | (obo << 15), buf);
sys_put_be32(block, &buf[2]);
return bt_mesh_ctl_send(&tx, TRANS_CTL_OP_ACK, buf, sizeof(buf), NULL, NULL, NULL);
}
static void seg_rx_reset(struct seg_rx *rx, bool full_reset)
{
BT_DBG("rx %p", rx);
k_delayed_work_cancel(&rx->ack);
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->obo && rx->block != BLOCK_COMPLETE(rx->seg_n)) {
BT_WARN("Clearing incomplete buffers from Friend queue");
bt_mesh_friend_clear_incomplete(rx->sub, rx->src, rx->dst, &rx->seq_auth);
}
rx->in_use = 0;
/* We don't always reset these values since we need to be able to
* send an ack if we receive a segment after we've already received
* the full SDU.
*/
if (full_reset) {
rx->seq_auth = 0;
rx->sub = NULL;
rx->src = BT_MESH_ADDR_UNASSIGNED;
rx->dst = BT_MESH_ADDR_UNASSIGNED;
}
}
static void seg_ack(struct k_work *work)
{
struct seg_rx *rx = CONTAINER_OF(work, struct seg_rx, ack);
BT_DBG("rx %p", rx);
if (k_uptime_get_32() - rx->last > K_SECONDS(60)) {
BT_WARN("Incomplete timer expired");
seg_rx_reset(rx, false);
if (IS_ENABLED(CONFIG_BT_TESTING)) {
bt_test_mesh_trans_incomp_timer_exp();
}
return;
}
send_ack(rx->sub, rx->dst, rx->src, rx->ttl, &rx->seq_auth, rx->block, rx->obo);
k_delayed_work_submit(&rx->ack, ack_timeout(rx));
}
static inline u8_t seg_len(bool ctl)
{
if (ctl) {
return 8;
} else {
return 12;
}
}
static inline bool sdu_len_is_ok(bool ctl, u8_t seg_n)
{
return ((seg_n * seg_len(ctl) + 1) <= CONFIG_BT_MESH_RX_SDU_MAX);
}
static struct seg_rx *seg_rx_find(struct bt_mesh_net_rx *net_rx, const u64_t *seq_auth)
{
int i;
for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
struct seg_rx *rx = &seg_rx[i];
if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) {
continue;
}
/* Return newer RX context in addition to an exact match, so
* the calling function can properly discard an old SeqAuth.
*/
if (rx->seq_auth >= *seq_auth) {
return rx;
}
if (rx->in_use) {
BT_WARN("Duplicate SDU from src 0x%04x", net_rx->ctx.addr);
/* Clear out the old context since the sender
* has apparently started sending a new SDU.
*/
seg_rx_reset(rx, true);
/* Return non-match so caller can re-allocate */
return NULL;
}
}
return NULL;
}
static bool seg_rx_is_valid(struct seg_rx *rx, struct bt_mesh_net_rx *net_rx, const u8_t *hdr, u8_t seg_n)
{
if (rx->hdr != *hdr || rx->seg_n != seg_n) {
BT_ERR("Invalid segment for ongoing session");
return false;
}
if (rx->src != net_rx->ctx.addr || rx->dst != net_rx->ctx.recv_dst) {
BT_ERR("Invalid source or destination for segment");
return false;
}
if (rx->ctl != net_rx->ctl) {
BT_ERR("Inconsistent CTL in segment");
return false;
}
return true;
}
static struct seg_rx *seg_rx_alloc(struct bt_mesh_net_rx *net_rx, const u8_t *hdr, const u64_t *seq_auth, u8_t seg_n)
{
int i;
for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
struct seg_rx *rx = &seg_rx[i];
if (rx->in_use) {
continue;
}
rx->in_use = 1;
net_buf_simple_reset(&rx->buf);
rx->sub = net_rx->sub;
rx->ctl = net_rx->ctl;
rx->seq_auth = *seq_auth;
rx->seg_n = seg_n;
rx->hdr = *hdr;
rx->ttl = net_rx->ctx.send_ttl;
rx->src = net_rx->ctx.addr;
rx->dst = net_rx->ctx.recv_dst;
rx->block = 0;
BT_DBG("New RX context. Block Complete 0x%08x", BLOCK_COMPLETE(seg_n));
return rx;
}
return NULL;
}
static int trans_seg(struct net_buf_simple *buf, struct bt_mesh_net_rx *net_rx, enum bt_mesh_friend_pdu_type *pdu_type,
u64_t *seq_auth)
{
struct seg_rx *rx;
u8_t *hdr = buf->data;
u16_t seq_zero;
u8_t seg_n;
u8_t seg_o;
int err;
if (buf->len < 5) {
BT_ERR("Too short segmented message (len %u)", buf->len);
return -EINVAL;
}
BT_DBG("ASZMIC %u AKF %u AID 0x%02x", ASZMIC(hdr), AKF(hdr), AID(hdr));
net_buf_simple_pull(buf, 1);
seq_zero = net_buf_simple_pull_be16(buf);
seg_o = (seq_zero & 0x03) << 3;
seq_zero = (seq_zero >> 2) & 0x1fff;
seg_n = net_buf_simple_pull_u8(buf);
seg_o |= seg_n >> 5;
seg_n &= 0x1f;
BT_DBG("SeqZero 0x%04x SegO %u SegN %u", seq_zero, seg_o, seg_n);
if (seg_o > seg_n) {
BT_ERR("SegO greater than SegN (%u > %u)", seg_o, seg_n);
return -EINVAL;
}
/* According to Mesh 1.0 specification:
* "The SeqAuth is composed of the IV Index and the sequence number
* (SEQ) of the first segment"
*
* Therefore we need to calculate very first SEQ in order to find
* seqAuth. We can calculate as below:
*
* SEQ(0) = SEQ(n) - (delta between seqZero and SEQ(n) by looking into
* 14 least significant bits of SEQ(n))
*
* Mentioned delta shall be >= 0, if it is not then seq_auth will
* be broken and it will be verified by the code below.
*/
*seq_auth = SEQ_AUTH(BT_MESH_NET_IVI_RX(net_rx),
(net_rx->seq - ((((net_rx->seq & BIT_MASK(14)) - seq_zero)) & BIT_MASK(13))));
/* Look for old RX sessions */
rx = seg_rx_find(net_rx, seq_auth);
if (rx) {
/* Discard old SeqAuth packet */
if (rx->seq_auth > *seq_auth) {
BT_WARN("Ignoring old SeqAuth");
return -EINVAL;
}
if (!seg_rx_is_valid(rx, net_rx, hdr, seg_n)) {
return -EINVAL;
}
if (rx->in_use) {
BT_DBG("Existing RX context. Block 0x%08x", rx->block);
goto found_rx;
}
if (rx->block == BLOCK_COMPLETE(rx->seg_n)) {
BT_WARN("Got segment for already complete SDU");
send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, rx->block,
rx->obo);
return -EALREADY;
}
/* We ignore instead of sending block ack 0 since the
* ack timer is always smaller than the incomplete
* timer, i.e. the sender is misbehaving.
*/
BT_WARN("Got segment for canceled SDU");
return -EINVAL;
}
/* Bail out early if we're not ready to receive such a large SDU */
if (!sdu_len_is_ok(net_rx->ctl, seg_n)) {
BT_ERR("Too big incoming SDU length");
send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, 0,
net_rx->friend_match);
return -EMSGSIZE;
}
/* Look for free slot for a new RX session */
rx = seg_rx_alloc(net_rx, hdr, seq_auth, seg_n);
if (!rx) {
/* Warn but don't cancel since the existing slots willl
* eventually be freed up and we'll be able to process
* this one.
*/
BT_WARN("No free slots for new incoming segmented messages");
return -ENOMEM;
}
rx->obo = net_rx->friend_match;
found_rx:
if (BIT(seg_o) & rx->block) {
BT_DBG("Received already received fragment");
return -EALREADY;
}
/* All segments, except the last one, must either have 8 bytes of
* payload (for 64bit Net MIC) or 12 bytes of payload (for 32bit
* Net MIC).
*/
if (seg_o == seg_n) {
/* Set the expected final buffer length */
rx->buf.len = seg_n * seg_len(rx->ctl) + buf->len;
BT_DBG("Target len %u * %u + %u = %u", seg_n, seg_len(rx->ctl), buf->len, rx->buf.len);
if (rx->buf.len > CONFIG_BT_MESH_RX_SDU_MAX) {
BT_ERR("Too large SDU len");
send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, 0, rx->obo);
seg_rx_reset(rx, true);
return -EMSGSIZE;
}
} else {
if (buf->len != seg_len(rx->ctl)) {
BT_ERR("Incorrect segment size for message type");
return -EINVAL;
}
}
/* Reset the Incomplete Timer */
rx->last = k_uptime_get_32();
if (!k_delayed_work_remaining_get(&rx->ack) && !bt_mesh_lpn_established()) {
k_delayed_work_submit(&rx->ack, ack_timeout(rx));
}
/* Location in buffer can be calculated based on seg_o & rx->ctl */
memcpy(rx->buf.data + (seg_o * seg_len(rx->ctl)), buf->data, buf->len);
BT_DBG("Received %u/%u", seg_o, seg_n);
/* Mark segment as received */
rx->block |= BIT(seg_o);
if (rx->block != BLOCK_COMPLETE(seg_n)) {
*pdu_type = BT_MESH_FRIEND_PDU_PARTIAL;
return 0;
}
BT_DBG("Complete SDU");
if (net_rx->local_match && is_replay(net_rx)) {
BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x", net_rx->ctx.addr, net_rx->ctx.recv_dst, net_rx->seq);
/* Clear the segment's bit */
rx->block &= ~BIT(seg_o);
return -EINVAL;
}
*pdu_type = BT_MESH_FRIEND_PDU_COMPLETE;
k_delayed_work_cancel(&rx->ack);
send_ack(net_rx->sub, net_rx->ctx.recv_dst, net_rx->ctx.addr, net_rx->ctx.send_ttl, seq_auth, rx->block, rx->obo);
if (net_rx->ctl) {
err = ctl_recv(net_rx, *hdr, &rx->buf, seq_auth);
} else {
err = sdu_recv(net_rx, (rx->seq_auth & 0xffffff), *hdr, ASZMIC(hdr), &rx->buf);
}
seg_rx_reset(rx, false);
return err;
}
int bt_mesh_trans_recv(struct net_buf_simple *buf, struct bt_mesh_net_rx *rx)
{
u64_t seq_auth = TRANS_SEQ_AUTH_NVAL;
enum bt_mesh_friend_pdu_type pdu_type = BT_MESH_FRIEND_PDU_SINGLE;
struct net_buf_simple_state state;
int err;
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
rx->friend_match = bt_mesh_friend_match(rx->sub->net_idx, rx->ctx.recv_dst);
} else {
rx->friend_match = false;
}
BT_DBG("src 0x%04x dst 0x%04x seq 0x%08x friend_match %u", rx->ctx.addr, rx->ctx.recv_dst, rx->seq,
rx->friend_match);
/* Remove network headers */
net_buf_simple_pull(buf, BT_MESH_NET_HDR_LEN);
BT_DBG("Payload %s", bt_hex(buf->data, buf->len));
if (IS_ENABLED(CONFIG_BT_TESTING)) {
bt_test_mesh_net_recv(rx->ctx.recv_ttl, rx->ctl, rx->ctx.addr, rx->ctx.recv_dst, buf->data, buf->len);
}
/* If LPN mode is enabled messages are only accepted when we've
* requested the Friend to send them. The messages must also
* be encrypted using the Friend Credentials.
*/
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && bt_mesh_lpn_established() && rx->net_if == BT_MESH_NET_IF_ADV &&
(!bt_mesh_lpn_waiting_update() || !rx->friend_cred)) {
BT_WARN("Ignoring unexpected message in Low Power mode");
return -EAGAIN;
}
/* Save the app-level state so the buffer can later be placed in
* the Friend Queue.
*/
net_buf_simple_save(buf, &state);
if (SEG(buf->data)) {
/* Segmented messages must match a local element or an
* LPN of this Friend.
*/
if (!rx->local_match && !rx->friend_match) {
return 0;
}
err = trans_seg(buf, rx, &pdu_type, &seq_auth);
} else {
err = trans_unseg(buf, rx, &seq_auth);
}
/* Notify LPN state machine so a Friend Poll will be sent. If the
* message was a Friend Update it's possible that a Poll was already
* queued for sending, however that's fine since then the
* bt_mesh_lpn_waiting_update() function will return false:
* we still need to go through the actual sending to the bearer and
* wait for ReceiveDelay before transitioning to WAIT_UPDATE state.
* Another situation where we want to notify the LPN state machine
* is if it's configured to use an automatic Friendship establishment
* timer, in which case we want to reset the timer at this point.
*
*/
if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) &&
(bt_mesh_lpn_timer() || (bt_mesh_lpn_established() && bt_mesh_lpn_waiting_update()))) {
bt_mesh_lpn_msg_received(rx);
}
net_buf_simple_restore(buf, &state);
if (IS_ENABLED(CONFIG_BT_MESH_FRIEND) && rx->friend_match && !err) {
if (seq_auth == TRANS_SEQ_AUTH_NVAL) {
bt_mesh_friend_enqueue_rx(rx, pdu_type, NULL, buf);
} else {
bt_mesh_friend_enqueue_rx(rx, pdu_type, &seq_auth, buf);
}
}
return err;
}
void bt_mesh_rx_reset(void)
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
seg_rx_reset(&seg_rx[i], true);
}
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_rpl();
} else {
memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
}
}
void bt_mesh_tx_reset(void)
{
int i;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
seg_tx_reset(&seg_tx[i]);
}
}
void bt_mesh_trans_init(void)
{
int i;
BT_INFO("enter %s\n", __func__);
for (i = 0; i < ARRAY_SIZE(seg_tx); i++) {
k_delayed_work_init(&seg_tx[i].retransmit, seg_retransmit);
}
for (i = 0; i < ARRAY_SIZE(seg_rx); i++) {
k_delayed_work_init(&seg_rx[i].ack, seg_ack);
seg_rx[i].buf.__buf = (seg_rx_buf_data + (i * CONFIG_BT_MESH_RX_SDU_MAX));
seg_rx[i].buf.data = seg_rx[i].buf.__buf;
}
}
void bt_mesh_rpl_clear(void)
{
BT_DBG("");
memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
}
void bt_mesh_rpl_clear_all(void)
{
BT_DBG("");
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_all_node_rpl();
}
memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
}
void bt_mesh_rpl_clear_node(uint16_t unicast_addr, uint8_t elem_num)
{
int i = 0;
struct bt_mesh_rpl *rpl = NULL;
BT_DBG("");
for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
rpl = &bt_mesh.rpl[i];
if (rpl->src >= unicast_addr && rpl->src < unicast_addr + elem_num) {
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
bt_mesh_clear_node_rpl(rpl->src);
}
memset(rpl, 0, sizeof(struct bt_mesh_rpl));
}
}
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/core/src/transport.c | C | apache-2.0 | 42,727 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef _MESH_MODEL_H__
#define _MESH_MODEL_H__
#include "api/mesh.h"
#include "api/mesh/main.h"
#if defined(CONFIG_BT_MESH_MODEL_GEN_ONOFF_SRV)
#include "sig_model/generic_onoff_srv.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_GEN_LEVEL_SRV)
#include "sig_model/generic_level_srv.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_LIGHTNESS_SRV)
#include "sig_model/light_lightness_srv.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_CTL_SRV)
#include "sig_model/light_ctl_srv.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_GEN_ONOFF_CLI)
#include "sig_model/generic_onoff_cli.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_GEN_LEVEL_CLI)
#include "sig_model/generic_level_cli.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_LIGHTNESS_CLI)
#include "sig_model/light_lightness_cli.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_CTL_CLI)
#include "sig_model/light_ctl_cli.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_VENDOR_SRV)
#include "vendor/vendor_model_srv.h"
#endif
#if defined(CONFIG_BT_MESH_MODEL_VENDOR_CLI)
#include "vendor/vendor_model_cli.h"
#endif
#include "model_bind_ops.h"
#include <api/mesh/access.h>
typedef enum {
T_CUR = 0,
T_TAR,
TYPE_NUM,
} _VALUE_TYPE;
typedef enum {
SUCCESS = 0,
SET_MIN_FAIL,
SET_MAX_FAIL,
RFU,
} _STATUS_CODES;
typedef struct _RANGE {
_STATUS_CODES code;
u16_t range_min;
u16_t range_max;
} RANGE_STATUS;
typedef struct {
#ifdef CONFIG_BT_MESH_MODEL_GEN_ONOFF_SRV
u8_t onoff[TYPE_NUM];
#endif
#ifdef CONFIG_BT_MESH_MODEL_GEN_LEVEL_SRV
s16_t level[TYPE_NUM];
#endif
#ifdef CONFIG_BT_MESH_MODEL_LIGHT_LIGHTNESS_SRV
u16_t lightness_linear[TYPE_NUM];
u16_t lightness_actual[TYPE_NUM];
#endif
#ifdef CONFIG_BT_MESH_MODEL_LIGHT_CTL_SRV
u16_t lightness[TYPE_NUM];
u16_t temp[TYPE_NUM];
u16_t UV[TYPE_NUM];
#endif
u8_t delay; // unit:5ms
u8_t trans; // unit:100ms
bt_u32_t trans_start_time;
bt_u32_t trans_end_time;
s16_t trans_step;
struct k_timer delay_timer;
struct k_timer trans_timer;
bool timerInitFlag;
} S_MESH_STATE;
typedef struct {
#ifdef CONFIG_BT_MESH_MODEL_LIGHT_LIGHTNESS_SRV
u16_t lightness_actual_default;
u16_t lightness_last;
RANGE_STATUS lightness_range;
#endif
#ifdef CONFIG_BT_MESH_MODEL_LIGHT_CTL_SRV
uint16_t lightness_default;
uint16_t temp_default;
uint16_t UV_default;
RANGE_STATUS ctl_temp_range;
#endif
} S_MESH_POWERUP;
typedef struct {
S_MESH_STATE state;
S_MESH_POWERUP powerup;
} S_ELEM_STATE;
typedef enum {
MESH_SUCCESS = 0,
MESH_TID_REPEAT,
MESH_ANALYZE_SIZE_ERROR,
MESH_ANALYZE_ARGS_ERROR,
MESH_SET_TRANSTION_ERROR,
} E_MESH_ERROR_TYPE;
typedef enum {
BT_MESH_MODEL_CFG_APP_KEY_ADD = 0x00,
BT_MESH_MODEL_CFG_COMP_DATA_STATUS = 0x02,
BT_MESH_MODEL_CFG_HEARTBEAT_PUB_STATUS = 0x06,
BT_MESH_MODEL_CFG_APPKEY_STATUS = 0x8003,
BT_MESH_MODEL_CFG_BEACON_STATUS = 0x800b,
BT_MESH_MODEL_CFG_TTL_STATUS = 0x800e,
BT_MESH_MODEL_CFG_FRIEND_STATUS = 0x8011,
BT_MESH_MODEL_CFG_PROXY_STATUS = 0x8014,
BT_MESH_MODEL_CFG_NET_KRP_STATUS = 0x8017,
BT_MESH_MODEL_CFG_PUB_STATUS = 0x8019,
BT_MESH_MODEL_CFG_SUB_STATUS = 0x801f,
BT_MESH_MODEL_CFG_SUB_LIST = 0x802a,
BT_MESH_MODEL_CFG_SUB_LIST_VND = 0x802c,
BT_MESH_MODEL_CFG_RELAY_STATUS = 0x8028,
BT_MESH_MODEL_CFG_HEARTBEAT_SUB_STATUS = 0x803c,
BT_MESH_MODEL_CFG_APPKEY_BIND_STATUS = 0x803e,
BT_MESH_MODEL_CFG_RST_STATUS = 0x804a,
BT_MESH_MODEL_CFG_NET_KEY_STATUS = 0x8044,
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
BT_MESH_MODEL_CFG_CTRL_RELAY_STATUS = 0x8072,
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
BT_MESH_MODEL_ONOFF_SET = 0x8202,
BT_MESH_MODEL_ONOFF_STATUS = 0x8204,
BT_MESH_MODEL_LEVEL_SET = 0x8206,
BT_MESH_MODEL_LEVEL_MOVE_SET = 0x820B,
BT_MESH_MODEL_LEVEL_STATUS = 0x8208,
BT_MESH_MODEL_LEVEL_DELTA_SET = 0x8209,
BT_MESH_MODEL_LIGHTNESS_SET = 0x824c,
BT_MESH_MODEL_LIGHTNESS_STATUS = 0x824e,
BT_MESH_MODEL_LIGHTNESS_LINEAR_SET = 0x8250,
BT_MESH_MODEL_LIGHTNESS_LINEAR_STATUS = 0x8252,
BT_MESH_MODEL_LIGHTNESS_LAST_STATUS = 0x8254,
BT_MESH_MODEL_LIGHTNESS_DEF_STATUS = 0x8256,
BT_MESH_MODEL_LIGHTNESS_RANGE_STATUS = 0x8258,
BT_MESH_MODEL_LIGHTNESS_DEF_SET = 0x8259,
BT_MESH_MODEL_LIGHTNESS_RANGE_SET = 0x825b,
BT_MESH_MODEL_LIGHT_CTL_SET = 0x825e,
BT_MESH_MODEL_LIGHT_CTL_STATUS = 0x8260,
BT_MESH_MODEL_LIGHT_CTL_TEMP_RANGE_STATUS = 0x8263,
BT_MESH_MODEL_LIGHT_CTL_TEMP_SET = 0x8264,
BT_MESH_MODEL_LIGHT_CTL_TEMP_STATUS = 0x8266,
BT_MESH_MODEL_LIGHT_CTL_DEF_STATUS = 0x8268,
BT_MESH_MODEL_LIGHT_CTL_DEF_SET = 0x8269,
BT_MESH_MODEL_LIGHT_CTL_RANGE_SET = 0x826b,
BT_MESH_MODEL_VENDOR_MESSAGES = 0xcf01a8,
BT_MESH_MODEL_VENDOR_MESH_AUTOCONFIG = 0xd601a8,
BT_MESH_MODEL_VENDOR_MESH_AUTOCONFIG_GET = 0xd701a8,
BT_MESH_MODEL_VENDOR_MESH_AUTOCONFIG_STATUS = 0xd801a8,
} mesh_model_event_en;
typedef void (*model_event_cb)(mesh_model_event_en event, void *p_arg);
typedef struct {
void *user_data;
uint16_t data_len;
} vendor_data;
typedef struct {
uint16_t source_addr;
uint16_t dst_addr;
struct net_buf_simple *status_data;
void *user_data;
vendor_data ven_data;
} model_message;
int ble_mesh_model_init(const struct bt_mesh_comp *comp);
const struct bt_mesh_comp *ble_mesh_model_get_comp_data();
int ble_mesh_model_set_cb(model_event_cb event_cb);
struct bt_mesh_model *ble_mesh_model_find(uint16_t elem_idx, uint16_t mod_idx, uint16_t CID);
int ble_mesh_model_status_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr,
struct bt_mesh_model *model, uint32_t op_code);
void model_event(mesh_model_event_en event, void *p_arg);
#endif // _MESH_MODEL_H_
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/common/include/mesh_model/mesh_model.h | C | apache-2.0 | 5,916 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef _MODEL_BOUND_OPERATION_H
#define _MODEL_BOUND_OPERATION_H
#include "mesh_model.h"
typedef enum _BIND_OPERATION_ID_ {
/* !!!START!!! --- Don't add new ID before this ID */
B_OPS_START_ID = -1,
/* Generic OnOff */
B_GEN_ONOFF_ID = 0,
/* Generic Level */
B_GEN_LEVEL_ID,
B_GEN_DELTA_ID,
B_GEN_MOVE_ID,
/* Generic Default Transition Time */
B_GEN_DFT_TRANS_TIME_ID,
/* Generic Power OnOff */
B_GEN_ON_PWR_UP_ID,
/* Generic Power Level */
B_GEN_PWR_ACTUAL_ID,
B_GEN_PWR_LAST_ID,
B_GEN_PWR_DFT_ID,
B_GEN_PWR_RANGE_ID,
/* Lightness sev model*/
B_GEN_LIGHTNESS_LINEAR_ID,
B_GEN_LIGHTNESS_ACTUAL_ID,
/* !!!END!!! --- Don't add new ID after this ID */
B_OPS_END_ID
} BIND_OPERATION_ID;
#endif //_MODEL_BOUND_OPERATION_H
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/common/include/mesh_model/model_bind_ops.h | C | apache-2.0 | 884 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include <bt_errno.h>
#include "mesh_model/mesh_model.h"
#ifdef CONFIG_BT_MESH_PROVISIONER
#include "provisioner_main.h"
#endif
extern u8_t bt_mesh_default_ttl_get(void);
#define TAG "BT_MESH_MODEL"
#define RECV_MSG_TID_QUEUE_SIZE 20
#define MESH_TRNSATION_CYCLE 100
#define CID_NVAL 0XFFFF
#define TIMEOUT 400
typedef struct _mesh_model {
uint8_t init_flag;
const struct bt_mesh_comp *mesh_comp;
model_event_cb user_model_event_cb;
S_ELEM_STATE *element_states;
} mesh_model;
mesh_model g_mesh_model;
typedef struct {
u8_t tid;
u16_t addr;
bt_u32_t time;
} _TID_QUEUE_S;
u16_t TRANS_TIMES[] = {1, 10, 100, 6000};
_TID_QUEUE_S tid_queue[RECV_MSG_TID_QUEUE_SIZE];
static void _mesh_timer_stop(S_MESH_STATE *p_state)
{
k_timer_stop(&p_state->delay_timer);
k_timer_stop(&p_state->trans_timer);
}
static void _mesh_delay_timer_cb(void *p_timer, void *args)
{
S_ELEM_STATE *p_elem = (S_ELEM_STATE *)args;
_mesh_timer_stop(&p_elem->state);
//model_event(GEN_EVT_SDK_DELAY_END, (void *)p_elem);
}
static void _mesh_trans_timer_cycle(void *p_timer, void *args)
{
S_ELEM_STATE *p_elem = (S_ELEM_STATE *)args;
bt_u32_t cur_time = k_uptime_get();
_mesh_timer_stop(&p_elem->state);
//LOGD(TAG, ">>>>>%d %d", (bt_u32_t)cur_time, (bt_u32_t)p_elem->state.trans_end_time);
if (cur_time >= p_elem->state.trans_end_time) {
//model_event(GEN_EVT_SDK_TRANS_END, (void *)p_elem);
} else {
//model_event(GEN_EVT_SDK_TRANS_CYCLE, (void *)p_elem);
k_timer_start(&p_elem->state.trans_timer, MESH_TRNSATION_CYCLE);
}
}
uint8_t elem_state_init(struct bt_mesh_elem *elem)
{
S_ELEM_STATE *elemState = (S_ELEM_STATE *)elem->models[2].user_data;
if (!elemState) {
return 0;
}
if (!elemState->state.timerInitFlag) {
k_timer_init(&elemState->state.delay_timer, _mesh_delay_timer_cb, elemState);
k_timer_init(&elemState->state.trans_timer, _mesh_trans_timer_cycle, elemState);
}
elemState->state.timerInitFlag = true;
return 0;
}
bt_u32_t get_transition_time(u8_t byte)
{
if ((byte & 0x3F) == 0x3F) {
//MODEL_E("%s ERROR, invalid 0x%02X!!!\n", __func__, byte);
return 0xFFFFFFFF;
}
return (byte & 0x3F) * TRANS_TIMES[byte >> 6] * 100;
}
static u8_t _get_transition_byte(bt_u32_t time)
{
//LOGD(TAG, "time(%d)", time);
time /= 100;
if (time > TRANS_TIMES[3] * 62) {
return 0;
} else if (time > TRANS_TIMES[2] * 62) {
return (time / TRANS_TIMES[3]) | 0xC0;
} else if (time > TRANS_TIMES[1] * 62) {
return (time / TRANS_TIMES[2]) | 0x80;
} else if (time > TRANS_TIMES[0] * 62) {
return (time / TRANS_TIMES[1]) | 0x40;
} else {
return (time / TRANS_TIMES[0]);
}
}
u8_t get_remain_byte(S_MESH_STATE *p_state, bool is_ack)
{
u8_t remain_byte = p_state->trans;
bt_u32_t cur_time = k_uptime_get();
if (!is_ack && p_state->trans_start_time < cur_time) {
cur_time -= p_state->trans_start_time;
bt_u32_t l_trans = get_transition_time(p_state->trans);
if (l_trans == 0xFFFFFFFF) {
remain_byte = 0x3F;
} else if (l_trans > cur_time) {
remain_byte = _get_transition_byte(l_trans - cur_time);
} else {
remain_byte = 0;
}
}
//LOGD(TAG, "remain_byte(0x%02x)", remain_byte);
return remain_byte;
}
E_MESH_ERROR_TYPE mesh_check_tid(u16_t src_addr, u8_t tid)
{
static u8_t cur_index = 0;
u8_t i = cur_index;
u8_t ri = 0;
bt_u32_t cur_time = k_uptime_get();
bt_u32_t end_time = 0;
while (i < cur_index + RECV_MSG_TID_QUEUE_SIZE) {
ri = i % RECV_MSG_TID_QUEUE_SIZE;
if (tid_queue[ri].tid == tid && tid_queue[ri].addr == src_addr) {
end_time = tid_queue[ri].time + 6000;
if (cur_time < end_time) {
break;
}
}
i++;
}
if (i < cur_index + RECV_MSG_TID_QUEUE_SIZE) {
return MESH_TID_REPEAT;
} else {
tid_queue[cur_index].tid = tid;
tid_queue[cur_index].addr = src_addr;
tid_queue[cur_index].time = cur_time;
cur_index++;
cur_index %= RECV_MSG_TID_QUEUE_SIZE;
return MESH_SUCCESS;
}
}
void model_message_process(uint8_t event, void *p_arg)
{
switch (event) {
default:
break;
}
return;
}
void model_event(mesh_model_event_en event, void *p_arg)
{
if (g_mesh_model.user_model_event_cb) {
g_mesh_model.user_model_event_cb(event, p_arg);
}
}
static int mesh_model_bind_map_get(const struct bt_mesh_comp *mesh_comp)
{
if (!mesh_comp) {
return -1;
}
return 0;
}
static int mesh_model_set_user_data(const struct bt_mesh_comp *comp, S_ELEM_STATE *state)
{
uint8_t ele_num;
uint8_t model_num;
for (ele_num = 0 ; ele_num < comp->elem_count; ele_num++) {
for (model_num = 0; model_num < comp->elem[ele_num].model_count; model_num++) {
if (comp->elem[ele_num].models[model_num].id != BT_MESH_MODEL_ID_CFG_SRV && \
comp->elem[ele_num].models[model_num].id != BT_MESH_MODEL_ID_CFG_CLI && \
comp->elem[ele_num].models[model_num].id != BT_MESH_MODEL_ID_HEALTH_SRV && \
comp->elem[ele_num].models[model_num].id != BT_MESH_MODEL_ID_HEALTH_CLI) {
comp->elem[ele_num].models[model_num].user_data = &state[ele_num];
}
}
}
return 0;
}
int ble_mesh_model_init(const struct bt_mesh_comp *comp)
{
if (!comp) {
return -1;
}
int16_t ret;
ret = mesh_model_bind_map_get(comp);
if (ret) {
return -1;
}
if (g_mesh_model.element_states) {
free(g_mesh_model.element_states);
g_mesh_model.element_states = NULL;
}
g_mesh_model.element_states = (S_ELEM_STATE *)malloc(sizeof(S_ELEM_STATE) * comp->elem_count);
if (!g_mesh_model.element_states) {
return -1;
}
memset(g_mesh_model.element_states, 0, sizeof(S_ELEM_STATE) * comp->elem_count);
ret = mesh_model_set_user_data(comp, g_mesh_model.element_states);
if (ret) {
return -1;
}
g_mesh_model.mesh_comp = comp;
g_mesh_model.init_flag = 1;
return 0;
}
const struct bt_mesh_comp *ble_mesh_model_get_comp_data()
{
return g_mesh_model.mesh_comp;
}
int ble_mesh_model_set_cb(model_event_cb event_cb)
{
if (!g_mesh_model.init_flag || !event_cb) {
return -1;
}
g_mesh_model.user_model_event_cb = event_cb;
return 0;
}
struct bt_mesh_model *ble_mesh_model_find(uint16_t elem_idx, uint16_t mod_idx, uint16_t CID)
{
if (!g_mesh_model.init_flag) {
return NULL;
}
if (elem_idx > g_mesh_model.mesh_comp->elem_count) {
return NULL;
}
if (CID_NVAL != CID) {
extern struct bt_mesh_model *bt_mesh_model_find_vnd(struct bt_mesh_elem * elem, u16_t company, u16_t id);
return (struct bt_mesh_model *)bt_mesh_model_find_vnd(&g_mesh_model.mesh_comp->elem[elem_idx], CID, mod_idx);
} else {
extern struct bt_mesh_model *bt_mesh_model_find(struct bt_mesh_elem * elem, u16_t id);
return (struct bt_mesh_model *)bt_mesh_model_find(&g_mesh_model.mesh_comp->elem[elem_idx], mod_idx);
}
}
int ble_mesh_model_status_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr,struct bt_mesh_model *model,uint32_t op_code)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
if (!model) {
return -EINVAL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 6);
bt_mesh_model_msg_init(msg, op_code);
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "mesh model get status send fail %d", err);
return err;
}
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/common/mesh_model.c | C | apache-2.0 | 8,170 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include <mesh_model.h>
#define TAG "MESH BIND"
typedef u16_t (*BIND_OPS_HANDLER)(S_ELEM_STATE *p_elem, u8_t type);
u16_t model_bind_operation(BIND_OPERATION_ID id, S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_onoff_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_onpowerup_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_level_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_power_actual_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_lightness_linear_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_lightness_actual_operation(S_ELEM_STATE *p_elem, u8_t type);
static u16_t _gen_power_range_operation(S_ELEM_STATE *p_elem, u8_t type);
BIND_OPS_HANDLER bind_handler[B_OPS_END_ID] = {
/* !!!START!!! --- Don't add new ID before this one */
//B_OPS_START_ID = -1,
/* Generic OnOff */
_gen_onoff_operation,//B_GEN_ONOFF_ID = 0,
/* Generic Level */
NULL,//B_GEN_LEVEL_ID,
NULL,//B_GEN_DELTA_ID,
NULL,//B_GEN_MOVE_ID,
/* Generic Default Transition Time */
NULL,//B_GEN_DFT_TRANS_TIME_ID,
/* Generic Power OnOff */
_gen_onpowerup_operation,//B_GEN_ON_PWR_UP_ID,
/* Generic Power Level */
_gen_power_actual_operation,//B_GEN_PWR_ACTUAL_ID,
NULL,//B_GEN_PWR_LAST_ID,
NULL,//B_GEN_PWR_DFT_ID,
_gen_power_range_operation,//B_GEN_PWR_RANGE_ID,
/*lightness*/
_gen_lightness_linear_operation,//B_GEN_LIGHTNESS_LINEAR_ID
_gen_lightness_actual_operation,//B_GEN_LIGHTNESS_ACTUAL_ID
/* !!!END!!! --- Don't add new ID after this one */
NULL
};
u16_t model_bind_operation(BIND_OPERATION_ID id, S_ELEM_STATE *p_elem, u8_t type)
{
BIND_OPS_HANDLER p_func = NULL;
LOGD(TAG, "bind ops - id: %d, ele:%p\n", id, p_elem);
if (id <= B_OPS_START_ID || id >= B_OPS_END_ID || !p_elem) {
LOGE(TAG, "invalid args, ignore\n");
return -1;
}
#if 1
p_func = bind_handler[id];
LOGD(TAG, "p_func:%p\n", p_func);
return p_func ? p_func(p_elem, type) : -1;
#else
{
u8_t i = 0;
for (i = 0; i < sizeof(bind_handler) / sizeof(bind_handler[0]); i++) {
func = bind_handler[i];
if (func) {
func(i, p_elem, type);
} else {
LOGD(TAG, "id:%d, func is NULL\n", i);
}
}
return 0;
}
#endif
}
/*
static u16_t _constrain_actual(S_ELEM_STATE *p_elem, u16_t var)
{
S_MESH_STATE *p_state = &p_elem->state;
if (var > 0 && var < p_state->power_range.range_min) {
var = p_state->power_range.range_min;
} else if (var > p_state->power_range.range_max) {
var = p_state->power_range.range_max;
}
return var;
}*/
/*
static u16_t _constrain_lightness(S_ELEM_STATE *p_elem, u16_t var)
{
S_MESH_STATE *p_state = &p_elem->state;
S_MESH_POWERUP *p_powerup = &p_elem->powerup;
if (var > 0 && var < p_powerup->lightness_range.range_min) {
var = p_powerup->lightness_range.range_min;
} else if (var > p_powerup->lightness_range.range_max) {
var = p_powerup->lightness_range.range_max;
}
return var;
}
static u16_t _gen_onoff_operation(S_ELEM_STATE *p_elem, u8_t type) {
S_MESH_STATE *p_state = &p_elem->state;
S_MESH_POWERUP *p_power_up = &p_elem->powerup;
u16_t actual = 0;
if (p_state->onoff[T_CUR]){
if(!p_power_up->lightness_default){
p_state->lightness_actual[T_CUR] = p_power_up->lightness_last;
}else{
p_state->lightness_actual[T_CUR] = p_power_up->lightness_default;
}
}
else{
p_state->actual[T_CUR] = p_state->actual[T_TAR] = actual;
p_state->lightness_actual[T_CUR] = 0;
}
BT_INFO("onoff[T_TAR]:%d, onoff[T_CUR]:%d, actual[TAR]:0x%02x", p_state->onoff[T_TAR], p_state->onoff[T_CUR], p_state->actual[T_TAR]);
return 0;
}
static u16_t _gen_level_operation(S_ELEM_STATE *p_elem, u8_t type) {
LOGD(TAG, "");
S_MESH_STATE *p_state = &p_elem->state;
p_state->actual[T_TAR] = p_state->level[T_CUR] + 32768;
p_state->lightness_actual[T_TAR] = p_state->level[T_CUR] + 32768;
return 0;
}
/*
static u16_t _gen_onpowerup_operation(S_ELEM_STATE *p_elem, u8_t type) {
S_MESH_STATE *p_state = &p_elem->state;
S_MESH_POWERUP *p_powerUp = &p_elem->powerup;
//Ethan: not supported, give 1 for the moment, don't need to adjust target actual here, will only take affect when next power on cycle
if(p_state->powerUp_status == 0x00){
p_state->actual[T_CUR] = 0;
p_state->lightness_actual[T_CUR] = 0;
}else if(p_state->powerUp_status == 0x01 ){
if(p_state->power_default != 0x00){
p_state->actual[T_CUR] = p_state->power_default;
}else{
p_state->actual[T_CUR] = p_state->power_last;
}
if(p_powerUp->lightness_default != 0x00){
p_state->lightness_actual[T_CUR] = p_powerUp->lightness_default;
}else{
p_state->lightness_actual[T_CUR] = p_powerUp->lightness_last;
}
}else if(p_state->powerUp_status == 0x02){
p_state->actual[T_CUR] = p_state->power_last;
p_state->lightness_actual[T_CUR] = p_powerUp->lightness_last;
}
BT_INFO("onpowerup ops, actual[TAR]:0x%02x\n", p_state->actual[type]);
return 0;
}*/
/*
static u16_t _gen_power_actual_operation(S_ELEM_STATE *p_elem, u8_t type)
{
LOGD(TAG, "");
S_MESH_STATE *p_state = &p_elem->state;
p_state->actual[type] = _constrain_actual(p_elem , p_state->actual[type]);
p_state->level[T_CUR] = p_state->actual - 32768;
if(p_state->actual == 0X0000){
p_state->onoff[T_TAR] = 0X00;
}else{
p_state->onoff[T_TAR] = 0X01;
}
p_state->power_last = p_state->actual[type];
return 0;
}*/
/*
static u16_t _gen_power_range_operation(S_ELEM_STATE *p_elem, u8_t type)
{
LOGD(TAG, "");
}
static u16_t _gen_lightness_linear_operation(S_ELEM_STATE *p_elem, u8_t type)
{
LOGD(TAG, "");
S_MESH_STATE *p_state = &p_elem->state;
p_state->lightness_actual[type] = (uint16_t)(sqrt(p_state->lightness_linear / 65535) * 65535);
}
static u16_t _gen_lightness_actual_operation(S_ELEM_STATE *p_elem, u8_t type)
{
LOGD(TAG, "");
S_MESH_STATE *p_state = &p_elem->state;
p_state->lightness_linear = p_state->lightness_actual[type] * p_state->lightness_actual[type] / 65535;
p_state->level = p_state->lightness_actual[type] - 32768;
if(!p_state->lightness_actual[T_CUR]){
p_state->onoff[type]= 0x00;
}else{
p_state->onoff[type]= 0x01;
}
}*/
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/common/model_bind_ops.c | C | apache-2.0 | 6,642 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include "mesh_model/mesh_model.h"
#include "port/mesh_event_port.h"
void mesh_model_event_cb(mesh_model_event_e event, void *p_arg)
{
mesh_model_event_en mesh_model_evt;
model_message message;
switch (event) {
case BT_MESH_MODEL_EVT_APPKEY_ADD: {
mesh_model_evt = BT_MESH_MODEL_CFG_APP_KEY_ADD;
model_event(mesh_model_evt, p_arg);
}
break;
case BT_MESH_MODEL_EVT_COMP_DATA_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_COMP_DATA_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_BEACON_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_BEACON_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_TTL_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_TTL_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_FRIEND_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_FRIEND_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_PROXY_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_PROXY_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_RELAY_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_RELAY_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_NETKEY_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_NET_KEY_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_NET_KRP_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_NET_KRP_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_APPKEY_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_APPKEY_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_APPKEY_BIND_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_APPKEY_BIND_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_PUB_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_PUB_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_SUB_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_SUB_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_SUB_LIST: {
mesh_model_evt = BT_MESH_MODEL_CFG_SUB_LIST;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_SUB_LIST_VND: {
mesh_model_evt = BT_MESH_MODEL_CFG_SUB_LIST_VND;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_HB_SUB_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_HEARTBEAT_SUB_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_HB_PUB_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_HEARTBEAT_PUB_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
/*[Genie begin] add by wenbing.cwb at 2021-01-21*/
#ifdef CONFIG_BT_MESH_CTRL_RELAY
case BT_MESH_MODEL_EVT_CTRL_RELAY_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_CTRL_RELAY_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
#endif
/*[Genie end] add by wenbing.cwb at 2021-01-21*/
case BT_MESH_MODEL_EVT_NODE_RESET_STATUS: {
mesh_model_evt = BT_MESH_MODEL_CFG_RST_STATUS;
bt_mesh_model_evt_t *evt_data = (bt_mesh_model_evt_t *)p_arg;
if (evt_data) {
message.source_addr = evt_data->source_addr;
message.status_data = evt_data->user_data;
}
model_event(mesh_model_evt, &message);
}
break;
case BT_MESH_MODEL_EVT_RPL_IS_FULL: {
//rpl is full,do something
}
break;
default:
return;
}
return;
}
int mesh_event_port_init(void)
{
bt_mesh_event_register(mesh_model_event_cb);
return 0;
}
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/mesh_port/bt_mesh_event_port.c | C | apache-2.0 | 8,568 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef _BT_MESH_EVENT_PORT_H_
#define _BT_MESH_EVENT_PORT_H_
int genie_mesh_port_init(void);
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/mesh_port/bt_mesh_event_port.h | C | apache-2.0 | 168 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "bt_errno.h"
#include "mesh_model/mesh_model.h"
#define TAG "GEN_LEVEL_CLI"
#if defined(CONFIG_BT_MESH_MODEL_GEN_LEVEL_CLI)
extern u8_t bt_mesh_default_ttl_get(void);
struct bt_mesh_model_pub g_generic_level_cli_pub = {
.msg = NET_BUF_SIMPLE(2 + 5 + 4),
};
/*
static void _generic_level_cli_prepear_buf(struct bt_mesh_model *model, struct net_buf_simple *msg, bool is_ack)
{
return;
}*/
static void _generic_level_cli_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LEVEL_STATUS, &message);
return;
}
int ble_mesh_generic_level_get(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x05));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic level get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_generic_level_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_level_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 5 : 3;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 5 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x06));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x07));
}
net_buf_simple_add_le16(msg, send_arg->level);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic level send fail %d", err);
return err;
}
LOGI(TAG, "SEND level %x, TID %d", send_arg->level, send_arg->tid);
send_arg->tid++;
return 0;
}
int ble_mesh_generic_level_delta_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_level_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 7 : 5;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 7 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x09));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x0a));
}
net_buf_simple_add_le32(msg, send_arg->delta);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic level delta send fail %d", err);
return err;
}
LOGI(TAG, "SEND level delta %x, TID %d", send_arg->delta, send_arg->tid);
send_arg->tid++;
return 0;
}
int ble_mesh_generic_level_move_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model,set_level_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 5 : 3;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 5 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x0b));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x0c));
}
net_buf_simple_add_le16(msg, send_arg->move);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic level move send fail %d", err);
return err;
}
LOGI(TAG, "SEND level move %x, TID %d", send_arg->move, send_arg->tid);
send_arg->tid++;
return 0;
}
const struct bt_mesh_model_op g_generic_level_cli_op[GEN_LEVEL_CLI_OPC_NUM] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x08), 2, _generic_level_cli_status},
BT_MESH_MODEL_OP_END,
};
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/sig_model/cli/generic_level_cli.c | C | apache-2.0 | 5,784 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include "bt_errno.h"
#include "mesh_model/mesh_model.h"
#define TAG "GEN_ONOFF_CLI"
#if defined(CONFIG_BT_MESH_MODEL_GEN_ONOFF_CLI)
extern u8_t bt_mesh_default_ttl_get(void);
struct bt_mesh_model_pub g_generic_onoff_cli_pub = {
.msg = NET_BUF_SIMPLE(2 + 3 + 4),
};
static void _generic_onoff_cli_prepear_buf(struct bt_mesh_model *model, struct net_buf_simple *msg, bool is_ack)
{
if (is_ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x02));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x03));
}
}
static void _generic_onoff_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_ONOFF_STATUS, &message);
}
int ble_mesh_generic_onoff_get(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x01));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic onoff get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_generic_onoff_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_onoff_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 4 : 2;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 4 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x02));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x03));
}
net_buf_simple_add_u8(msg, send_arg->onoff);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "generic off send fail %d", err);
return err;
}
LOGD(TAG, TAG, "SEND LED %s, TID %d", send_arg->onoff ? "ON" : "OFF", send_arg->tid);
send_arg->tid++;
return 0;
}
int ble_mesh_generic_onoff_cli_publish(struct bt_mesh_model *model, set_onoff_arg *send_arg, bool ack)
{
struct net_buf_simple *msg;
int err;
if (!model || !send_arg || !model->pub || model->pub->addr == BT_MESH_ADDR_UNASSIGNED) {
return -1;
}
msg = model->pub->msg;
LOGD(TAG, "addr(0x%04x)", model->pub->addr);
if (model->pub->addr != BT_MESH_ADDR_UNASSIGNED) {
_generic_onoff_cli_prepear_buf(model, msg, ack);
net_buf_simple_add_u8(msg, send_arg->onoff);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
err = bt_mesh_model_publish(model);
if (err) {
LOGE(TAG, "bt_mesh_model_publish err %d\n", err);
return -1;
}
send_arg->tid++;
LOGD(TAG, "Success!!!");
}
return 0;
}
const struct bt_mesh_model_op g_generic_onoff_cli_op[GEN_ONOFF_CLI_OPC_NUM] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x04), 0, _generic_onoff_status},
BT_MESH_MODEL_OP_END,
};
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/sig_model/cli/generic_onoff_cli.c | C | apache-2.0 | 4,223 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include "bt_errno.h"
#include "mesh_model/mesh_model.h"
#define TAG "LIGHT_CTL_CLI"
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_CTL_CLI)
struct bt_mesh_model_pub g_ctl_cli_pub = {
.msg = NET_BUF_SIMPLE(2 + 9 + 4),
};
extern u8_t bt_mesh_default_ttl_get(void);
static void _light_ctl_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHT_CTL_STATUS, &message);
return;
}
static void _light_ctl_temp_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHT_CTL_TEMP_STATUS, &message);
return;
}
static void _light_ctl_default_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHT_CTL_DEF_STATUS, &message);
return;
}
static void _light_ctl_range_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHT_CTL_TEMP_RANGE_STATUS, &message);
return;
}
int ble_mesh_light_ctl_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_light_ctl_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 9 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5e));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5f));
}
net_buf_simple_add_le16(msg, send_arg->lightness);
net_buf_simple_add_le16(msg, send_arg->temperature);
net_buf_simple_add_le16(msg, send_arg->delta_uv);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness range set send fail %d", err);
return err;
}
LOGI(TAG, "light ctl lightness %x,temp %x, delta uv %x, TID %x,trans %x,delay %x", send_arg->lightness, send_arg->temperature, \
send_arg->delta_uv, send_arg->tid, send_arg->trans, send_arg->delay);
return 0;
}
int ble_mesh_light_ctl_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5D));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_ctl_temp_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_light_ctl_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 7 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x64));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x65));
}
net_buf_simple_add_le16(msg, send_arg->temperature);
net_buf_simple_add_le16(msg, send_arg->delta_uv);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl set send fail %d", err);
return err;
}
LOGI(TAG, "light ctl set temp %x, delta uv %x, TID %x,trans %x,delay %x", send_arg->temperature, \
send_arg->delta_uv, send_arg->tid, send_arg->trans, send_arg->delay);
return 0;
}
int ble_mesh_light_ctl_temp_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x61));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl temp get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_ctl_def_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_light_ctl_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 6 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x69));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x6A));
}
net_buf_simple_add_le16(msg, send_arg->lightness);
net_buf_simple_add_le16(msg, send_arg->temperature);
net_buf_simple_add_le16(msg, send_arg->delta_uv);
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl def set send fail %d", err);
return err;
}
LOGI(TAG, "light ctl def set set lightness %x, temperature %x, delta_uv %x", send_arg->lightness, send_arg->temperature, send_arg->delta_uv);
return 0;
}
int ble_mesh_light_ctl_def_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x67));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl def get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_ctl_temp_range_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_light_ctl_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 4 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x6b));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x6c));
}
net_buf_simple_add_le16(msg, send_arg->range_min);
net_buf_simple_add_le16(msg, send_arg->range_max);
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl temp range set send fail %d", err);
return err;
}
LOGI(TAG, "light ctl temp range set min %x, max %x", send_arg->range_min, send_arg->range_max);
return 0;
}
int ble_mesh_light_ctl_temp_range_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x62));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "light ctl temp range get send fail %d", err);
return err;
}
return 0;
}
const struct bt_mesh_model_op light_ctl_cli_op[LIGHT_CTL_CLI_OPC_NUM] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x60), 2, _light_ctl_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x66), 2, _light_ctl_temp_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x68), 2, _light_ctl_default_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x63), 2, _light_ctl_range_status},
BT_MESH_MODEL_OP_END,
};
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/sig_model/cli/light_ctl_cli.c | C | apache-2.0 | 10,531 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include "bt_errno.h"
#include "mesh_model/mesh_model.h"
#define TAG "LIGHT_LIGHTNESS_CLI"
#if defined(CONFIG_BT_MESH_MODEL_LIGHT_LIGHTNESS_CLI)
extern u8_t bt_mesh_default_ttl_get(void);
int light_lightness_cli_publication(struct bt_mesh_model *model);
struct bt_mesh_model_pub g_light_lightness_cli_pub = {
.msg = NET_BUF_SIMPLE(2 + 5 + 4),
};
static void _light_lightness_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHTNESS_STATUS, &message);
return;
}
static void _light_lightness_linear_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHTNESS_LINEAR_STATUS, &message);
}
static void _light_lightness_last_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHTNESS_LAST_STATUS, &message);
return;
}
static void _light_lightness_default_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHTNESS_DEF_STATUS, &message);
return;
}
static void _light_lightness_range_status(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
LOGD(TAG, "");
model_message message;
message.source_addr = ctx->addr;
message.status_data = buf;
model_event(BT_MESH_MODEL_LIGHTNESS_RANGE_STATUS, &message);
return;
}
int ble_mesh_light_lightness_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x4b));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_lightness_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_lightness_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 5 : 3;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 5 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x4c));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x4d));
}
net_buf_simple_add_le16(msg, send_arg->lightness);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness send fail %d", err);
return err;
}
LOGI(TAG, "lightness level %x, TID %d", send_arg->lightness, send_arg->tid);
send_arg->tid++;
return 0;
}
int ble_mesh_light_lightness_linear_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x4f));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_lightness_linear_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_lightness_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
//uint8_t extra_size = send_arg->send_trans ? 5 : 3;
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 5 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x50));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x51));
}
net_buf_simple_add_le16(msg, send_arg->lightness_linear);
net_buf_simple_add_u8(msg, send_arg->tid);
if (send_arg->send_trans) {
net_buf_simple_add_u8(msg, send_arg->trans);
net_buf_simple_add_u8(msg, send_arg->delay);
}
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness linear send fail %d", err);
return err;
}
LOGI(TAG, "lightness linear level %x, TID %d", send_arg->lightness_linear, send_arg->tid);
send_arg->tid++;
return 0;
}
int ble_mesh_light_lightness_last_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x53));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_lightness_def_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x55));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_lightness_def_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_lightness_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 2 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x59));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5a));
}
net_buf_simple_add_le16(msg, send_arg->def);
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness def set send fail %d", err);
return err;
}
LOGI(TAG, "lightness def %x", send_arg->def);
return 0;
}
int ble_mesh_light_lightness_range_get(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 0 + 4);
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x57));
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness get send fail %d", err);
return err;
}
return 0;
}
int ble_mesh_light_lightness_range_set(uint16_t netkey_idx, uint16_t appkey_idx, uint16_t unicast_addr, struct bt_mesh_model *model, set_lightness_arg *send_arg, bool ack)
{
int err;
struct bt_mesh_msg_ctx ctx = {0};
if (model == NULL || send_arg == NULL) {
return -EINVAL;
}
if (0x0000 == unicast_addr) {
return -EADDRNOTAVAIL;
}
struct net_buf_simple *msg = NET_BUF_SIMPLE(2 + 4 + 4);
if (ack) {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5b));
} else {
bt_mesh_model_msg_init(msg, BT_MESH_MODEL_OP_2(0x82, 0x5c));
}
net_buf_simple_add_le16(msg, send_arg->range_min);
net_buf_simple_add_le16(msg, send_arg->range_max);
ctx.addr = unicast_addr;
ctx.net_idx = netkey_idx;
ctx.app_idx = appkey_idx;
ctx.send_ttl = bt_mesh_default_ttl_get();
err = bt_mesh_model_send(model, &ctx, msg, NULL, NULL);
if (err) {
LOGE(TAG, "lightness range set send fail %d", err);
return err;
}
LOGI(TAG, "lightness range set min %x, max %x", send_arg->range_min, send_arg->range_max);
return 0;
}
const struct bt_mesh_model_op g_light_lightness_cli_op[LIGHT_LIGHTNESS_CLI_OPC_NUM] = {
{ BT_MESH_MODEL_OP_2(0x82, 0x4E), 2, _light_lightness_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x52), 2, _light_lightness_linear_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x54), 2, _light_lightness_last_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x56), 2, _light_lightness_default_status},
{ BT_MESH_MODEL_OP_2(0x82, 0x58), 2, _light_lightness_range_status},
BT_MESH_MODEL_OP_END,
};
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/sig_model/cli/light_lightness_cli.c | C | apache-2.0 | 11,259 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef _GENERIC_LEVEL_CLI_H_
#define _GENERIC_LEVEL_CLI_H_
#define GEN_LEVEL_CLI_OPC_NUM 2
#define MESH_MODEL_GEN_LEVEL_CLI(_user_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_LEVEL_CLI, \
g_generic_level_cli_op, &g_generic_level_cli_pub,_user_data)
#define MESH_MODEL_GEN_LEVEL_CLI_NULL() MESH_MODEL_GEN_LEVEL_CLI(NULL)
typedef struct _set_level_arg {
uint16_t level;
uint16_t def;
uint16_t move;
uint8_t tid;
uint8_t trans;
uint8_t delay;
uint8_t send_trans: 1;
bt_s32_t delta;
} set_level_arg;
int ble_mesh_generic_level_get(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model);
int ble_mesh_generic_level_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_level_arg *send_arg, bool ack);
int ble_mesh_generic_level_move_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_level_arg *send_arg, bool ack);
int ble_mesh_generic_level_delta_set(uint16_t netkey_idx, uint16_t appkey_idx,uint16_t unicast_addr,struct bt_mesh_model *model, set_level_arg *send_arg, bool ack);
extern const struct bt_mesh_model_op g_generic_level_cli_op[GEN_LEVEL_CLI_OPC_NUM];
extern struct bt_mesh_model_pub g_generic_level_cli_pub;
#endif
| YifuLiu/AliOS-Things | components/ble_mesh/bt_mesh/mesh_models/sig_model/include/sig_model/generic_level_cli.h | C | apache-2.0 | 1,370 |