Merge branch 'master' into CAN_rxinterrupt_fix

pull/14688/head
Mohammed Mubeen 2021-06-29 18:32:48 +05:30 committed by GitHub
commit 5d861f895d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1515 changed files with 152061 additions and 28172 deletions

View File

@ -6,6 +6,7 @@
^connectivity/libraries/ppp
^connectivity/drivers/emac
^connectivity/drivers/mbedtls
^connectivity/drivers/wifi/COMPONENT_WHD
^connectivity/mbedtls
^features/frameworks
^connectivity/lwipstack/lwip

29
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,29 @@
on:
issues:
types: [ opened, reopened ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v2
- name: Install Python environment
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Checkout mbed-os-scripts repo (This repo is currently private)
uses: actions/checkout@v2
with:
repository: ARMmbed/mbed-os-ci-scripts
token: ${{ secrets.ISSUE_TRIAGING_PERMS }}
path: scripts
ref: master
- name: Run the script
run: |
python -m pip install pygithub
python ./scripts/issue_triaging/__init__.py -i ${{github.event.issue.number}} -r ${{ github.event.repository.name }} -t ${{ secrets.ISSUE_TRIAGING_PERMS }}

2
.gitignore vendored
View File

@ -102,3 +102,5 @@ DELIVERY/
CMakeCache.txt
cmake_install.cmake
CMakeFiles/
cmake_build/
Testing/

27
.lgtm.yml Normal file
View File

@ -0,0 +1,27 @@
path_classifiers:
docs:
- docs
test:
- "**/TESTS"
- "**/UNITTESTS"
tools:
- tools
extraction:
cpp:
prepare:
packages:
- ninja-build
- python-pip
after_prepare:
- pip install --user cmake
- ls ~/.local/bin
- export PATH=~/.local/bin:$PATH
- cmake --version
configure:
command:
- cmake -S . -B __build -GNinja -DBUILD_TESTING=ON -DCOVERAGE=OFF -DCMAKE_BUILD_TYPE=Debug
index:
build_command:
- cmake --build __build
- cmake --build __build --target test

View File

@ -39,9 +39,11 @@ addons:
- sourceline: 'deb https://apt.kitware.com/ubuntu/ focal main'
key_url: 'https://apt.kitware.com/keys/kitware-archive-latest.asc'
packages:
- cmake
- ninja-build
- libncursesw5
- cmake
- ninja-build
- gcovr
- libncursesw5
- g++-7
matrix:
include:
@ -66,9 +68,8 @@ matrix:
before_script:
- mkdir -p SCANCODE
- mkdir -p SCANCODE_NEW_FILES
# Fetch remaining information needed for branch comparison
- git fetch --all --unshallow --tags
- git fetch origin "${TRAVIS_BRANCH}"
# Fetch the base branch to compare against
- git fetch origin "${TRAVIS_BRANCH}" --depth=1
script:
# scancode does not support list of files, only one file or directory
# we use SCANCODE directory for all changed files (their copies with full tree)
@ -104,6 +105,12 @@ matrix:
false;
fi
- <<: *basic-vm
name: "UTF-8 Check"
script:
# Make sure we're not introducing any text which is not UTF-8 encoded
- git diff $TRAVIS_BRANCH...HEAD -U0 | ( grep -a '^+' || true ) | ( ! grep -axv '.*' )
- <<: *basic-vm
name: "include check"
env: NAME=include_check
@ -128,9 +135,8 @@ matrix:
export PATH="${PWD}/bin:${PATH}";
cd -
- astyle --version
# Fetch remaining information needed for branch comparison
- git fetch --all --unshallow --tags
- git fetch origin "${TRAVIS_BRANCH}"
# Fetch the base branch to compare against
- git fetch origin "${TRAVIS_BRANCH}" --depth=1
script:
- >-
git diff --name-only --diff-filter=d FETCH_HEAD..HEAD \
@ -189,35 +195,6 @@ matrix:
find -name "*.s" | tee BUILD/badasm |
sed -e "s/^/Bad Assembler file name found: /" && [ ! -s BUILD/badasm ]
- <<: *docs-vm
name: "Frozen tools check"
env: NAME=frozen_tools_check
script:
# Reject any changes to tools that would require a re-release of the
# tools for the online compiler.
- >-
frozen_files=`\
git diff --name-only --diff-filter=d FETCH_HEAD..HEAD \
| egrep \
-e "^tools/build_api*" \
-e "^tools/config*" \
-e "^tools/export*" \
-e "^tools/notifier*" \
-e "^tools/paths*" \
-e "^tools/resources*" \
-e "^tools/targets*" \
-e "^tools/toolchains*" \
-e "^tools/utils*" \
-e "^$"`
if [ -z "$frozen_files" ]; then
echo "Success!";
else
echo -e "Failure: Frozen files were modified\n$frozen_files";
echo -e "Please see https://os.mbed.com/blog/entry/Introducing-the-new-Mbed-Tools/" \
"\nfor why we've frozen the legacy tools.";
false;
fi
### Python Tests ###
- &pytools-vm
stage: "Pytest"
@ -273,9 +250,8 @@ matrix:
- python -m pip install --upgrade setuptools==40.4.3
- pip install tabulate argparse
- pip list --verbose
# Fetch remaining information needed for branch comparison
- git fetch --all --unshallow --tags
- git fetch origin "${TRAVIS_BRANCH}"
# Fetch the base branch to compare against
- git fetch origin "${TRAVIS_BRANCH}" --depth=1
script:
- >-
git diff --name-only --diff-filter=d FETCH_HEAD..HEAD \
@ -321,3 +297,57 @@ matrix:
- mbedtools configure -p ${ROOT} -t ${TOOLCHAIN} -m ${TARGET_NAME} --mbed-os-path .
- cmake -S ${ROOT} -B ${ROOT}/cmake_build/${TARGET_NAME}/${PROFILE}/${TOOLCHAIN}/ -GNinja -DCMAKE_BUILD_TYPE=${PROFILE}
- cmake --build ${ROOT}/cmake_build/${TARGET_NAME}/${PROFILE}/${TOOLCHAIN}/
### Mbed OS unittest ###
- &cmake-build-run-unittest
stage: "CMake"
name: "CMake unittest build"
env: NAME=cmake_unittest
install:
# Hide Travis-preinstalled CMake
# The Travis-preinstalled CMake is unfortunately not installed via apt, so we
# can't replace it with an apt-supplied version very easily. Additionally, we
# can't permit the Travis-preinstalled copy to survive, as the Travis default
# path lists the Travis CMake install location ahead of any place where apt
# would install CMake to. Instead of apt removing or upgrading to a new CMake
# version, we must instead delete the Travis copy of CMake.
- sudo rm -rf /usr/local/cmake*
script:
- echo ctest --build-and-test . build --build-generator Ninja --build-options -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug -DCOVERAGE=ON -DCMAKE_CXX_COMPILER=g++-7 -DCMAKE_C_COMPILER=gcc-7 --test-command ctest
- ctest --build-and-test . build --build-generator Ninja --build-options -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug -DCOVERAGE=ON -DCMAKE_CXX_COMPILER=g++-7 -DCMAKE_C_COMPILER=gcc-7 --test-command ctest
- gcovr --gcov-executable gcov-7 -r . ./build -s -e ".*\.h" --exclude-directories=$TRAVIS_BUILD_DIR/build/UNITTESTS --exclude-directories=$TRAVIS_BUILD_DIR/build/_deps
- ccache -s
### Frozen tools check ###
- &frozen-tools-vm
stage: "Frozen tools check"
name: "Frozen tools check"
env: NAME=frozen_tools_check
before_script:
# Fetch the base branch to compare against
- git fetch origin "${TRAVIS_BRANCH}" --depth=1
script:
# Reject any changes to tools that would require a re-release of the
# tools for the online compiler.
- >-
frozen_files=`\
git diff --name-only FETCH_HEAD..HEAD \
| egrep \
-e "^tools/build_api*" \
-e "^tools/config*" \
-e "^tools/export*" \
-e "^tools/notifier*" \
-e "^tools/paths*" \
-e "^tools/resources*" \
-e "^tools/targets*" \
-e "^tools/toolchains*" \
-e "^tools/utils*" \
-e "^$"`
if [ -z "$frozen_files" ]; then
echo "Success!";
else
echo -e "Failure: Frozen files were modified\n$frozen_files";
echo -e "Please see https://os.mbed.com/blog/entry/Introducing-the-new-Mbed-Tools/" \
"\nfor why we've frozen the legacy tools.";
false;
fi

View File

@ -5,16 +5,25 @@
cmake_minimum_required(VERSION 3.19.0 FATAL_ERROR)
include(${MBED_CONFIG_PATH}/mbed_config.cmake)
include(mbed_set_linker_script)
if(${CMAKE_CROSSCOMPILING})
include(${MBED_CONFIG_PATH}/mbed_config.cmake)
include(mbed_set_linker_script)
endif()
project(mbed-os)
# Add all paths to the list files within Mbed OS
list(APPEND CMAKE_MODULE_PATH
list(APPEND CMAKE_MODULE_PATH
"${mbed-os_SOURCE_DIR}/platform/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_TFM/TARGET_TFM_LATEST/scripts;${mbed-os_SOURCE_DIR}/targets/TARGET_Cypress/scripts;${mbed-os_SOURCE_DIR}/targets/TARGET_NXP/scripts"
)
option(BUILD_TESTING "Run unit tests only." OFF)
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING)
include(CTest)
add_subdirectory(UNITTESTS)
endif()
add_library(mbed-core INTERFACE)
add_library(mbed-os INTERFACE)
@ -33,88 +42,90 @@ target_link_libraries(mbed-baremetal
)
# Validate selected C library type
# The C library type selected has to match the library that the target can support
if(${MBED_C_LIB} STREQUAL "small")
if(NOT "small" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
if("std" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
message(WARNING
"We noticed that target.c_lib is set to `${MBED_C_LIB}`."
" As the ${MBED_TARGET} target does not support a small C library for the ${MBED_TOOLCHAIN} toolchain,"
" we are using the standard C library instead."
)
set(MBED_C_LIB "std" CACHE STRING "")
if(${CMAKE_CROSSCOMPILING})
if(${MBED_C_LIB} STREQUAL "small")
if(NOT "small" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
if("std" IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
message(WARNING
"We noticed that target.c_lib is set to `${MBED_C_LIB}`."
" As the ${MBED_TARGET} target does not support a small C library for the ${MBED_TOOLCHAIN} toolchain,"
" we are using the standard C library instead."
)
set(MBED_C_LIB "std" CACHE STRING "")
endif()
endif()
elseif(NOT ${MBED_C_LIB} IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
message(FATAL_ERROR
"Invalid `target.c_lib` ('${MBED_C_LIB}') for '${MBED_TARGET}' target."
"\nPossible value(s): ${MBED_TARGET_SUPPORTED_C_LIBS}"
)
endif()
elseif(NOT ${MBED_C_LIB} IN_LIST MBED_TARGET_SUPPORTED_C_LIBS)
message(FATAL_ERROR
"Invalid `target.c_lib` ('${MBED_C_LIB}') for '${MBED_TARGET}' target."
"\nPossible value(s): ${MBED_TARGET_SUPPORTED_C_LIBS}"
)
endif()
# Validate selected printf library
set(MBED_PRINTF_LIB_TYPES std minimal-printf)
if(NOT ${MBED_PRINTF_LIB} IN_LIST MBED_PRINTF_LIB_TYPES)
message(FATAL_ERROR
"Invalid printf library type '${MBED_PRINTF_LIB}'. Possible values:\n ${MBED_PRINTF_LIB_TYPES}"
)
endif()
# Validate selected printf library
set(MBED_PRINTF_LIB_TYPES std minimal-printf)
if(NOT ${MBED_PRINTF_LIB} IN_LIST MBED_PRINTF_LIB_TYPES)
message(FATAL_ERROR
"Invalid printf library type '${MBED_PRINTF_LIB}'. Possible values:\n ${MBED_PRINTF_LIB_TYPES}"
)
endif()
mbed_set_cpu_core_definitions(mbed-core)
if(${MBED_TOOLCHAIN_FILE_USED})
mbed_set_profile_options(mbed-core ${MBED_TOOLCHAIN})
mbed_set_c_lib(mbed-core ${MBED_C_LIB})
mbed_set_printf_lib(mbed-core ${MBED_PRINTF_LIB})
mbed_set_cpu_core_definitions(mbed-core)
if(${MBED_TOOLCHAIN_FILE_USED})
mbed_set_profile_options(mbed-core ${MBED_TOOLCHAIN})
mbed_set_c_lib(mbed-core ${MBED_C_LIB})
mbed_set_printf_lib(mbed-core ${MBED_PRINTF_LIB})
target_compile_features(mbed-core
INTERFACE
c_std_11
cxx_std_14
)
target_compile_features(mbed-core
INTERFACE
c_std_11
cxx_std_14
)
endif()
endif()
target_compile_definitions(mbed-core
INTERFACE
${MBED_TARGET_DEFINITIONS}
${MBED_CONFIG_DEFINITIONS}
)
# Add MBED_TEST_MODE for backward compatibility with Greentea tests written for use with Mbed CLI 1
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING)
target_compile_definitions(${PROJECT_NAME}
PUBLIC
MBED_TEST_MODE
)
endif()
# We need to generate a "response file" to pass to the C preprocessor when we preprocess the linker
# script, because of path length limitations on Windows. We set the response file and bind the path
# to a global property here. The MBED_TARGET being built queries this global property when it sets
# the linker script.
#
# We must set this global property before the targets subdirectory is added to the project. This is
# required because the MBED_TARGET depends on the response file. If the path to the response file
# is not defined when the target requests it the config definitions will not be passed to CPP.
#
# TODO: Remove this and find a more idiomatic way of passing compile definitions to CPP without
# using response files or global properties.
mbed_generate_options_for_linker(mbed-core RESPONSE_FILE_PATH)
set_property(GLOBAL PROPERTY COMPILE_DEFS_RESPONSE_FILE ${RESPONSE_FILE_PATH})
# Add compile definitions for backward compatibility with the toolchain
# supported. New source files should instead check for __GNUC__ and __clang__
# for the GCC_ARM and ARM toolchains respectively.
if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM")
target_compile_definitions(mbed-core
INTERFACE
TOOLCHAIN_GCC_ARM
TOOLCHAIN_GCC
)
elseif(${MBED_TOOLCHAIN} STREQUAL "ARM")
target_compile_definitions(mbed-core
INTERFACE
TOOLCHAIN_ARM
${MBED_TARGET_DEFINITIONS}
${MBED_CONFIG_DEFINITIONS}
)
# Add MBED_TEST_MODE for backward compatibility with Greentea tests written for use with Mbed CLI 1
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING)
target_compile_definitions(${PROJECT_NAME}
PUBLIC
MBED_TEST_MODE
)
endif()
# We need to generate a "response file" to pass to the C preprocessor when we preprocess the linker
# script, because of path length limitations on Windows. We set the response file and bind the path
# to a global property here. The MBED_TARGET being built queries this global property when it sets
# the linker script.
#
# We must set this global property before the targets subdirectory is added to the project. This is
# required because the MBED_TARGET depends on the response file. If the path to the response file
# is not defined when the target requests it the config definitions will not be passed to CPP.
#
# TODO: Remove this and find a more idiomatic way of passing compile definitions to CPP without
# using response files or global properties.
mbed_generate_options_for_linker(mbed-core RESPONSE_FILE_PATH)
set_property(GLOBAL PROPERTY COMPILE_DEFS_RESPONSE_FILE ${RESPONSE_FILE_PATH})
# Add compile definitions for backward compatibility with the toolchain
# supported. New source files should instead check for __GNUC__ and __clang__
# for the GCC_ARM and ARM toolchains respectively.
if(${MBED_TOOLCHAIN} STREQUAL "GCC_ARM")
target_compile_definitions(mbed-core
INTERFACE
TOOLCHAIN_GCC_ARM
TOOLCHAIN_GCC
)
elseif(${MBED_TOOLCHAIN} STREQUAL "ARM")
target_compile_definitions(mbed-core
INTERFACE
TOOLCHAIN_ARM
)
endif()
endif()
# Include mbed.h and config from generate folder
@ -136,23 +147,26 @@ add_subdirectory(hal)
add_subdirectory(platform)
add_subdirectory(rtos)
add_subdirectory(targets)
add_subdirectory(storage)
add_subdirectory(events)
add_subdirectory(connectivity)
# The directories below contain optional target libraries
add_subdirectory(events EXCLUDE_FROM_ALL)
add_subdirectory(connectivity EXCLUDE_FROM_ALL)
add_subdirectory(storage EXCLUDE_FROM_ALL)
add_subdirectory(drivers/device_key EXCLUDE_FROM_ALL)
add_subdirectory(drivers/usb EXCLUDE_FROM_ALL)
add_subdirectory(features EXCLUDE_FROM_ALL)
add_subdirectory(cmsis/CMSIS_5/CMSIS/RTOS2 EXCLUDE_FROM_ALL)
add_subdirectory(cmsis/device/rtos EXCLUDE_FROM_ALL)
# Ensure the words that make up the Mbed target name are separated with a hyphen, lowercase, and with the `mbed-` prefix.
string(TOLOWER ${MBED_TARGET} MBED_TARGET_CONVERTED)
string(REPLACE "_" "-" MBED_TARGET_CONVERTED ${MBED_TARGET_CONVERTED})
string(PREPEND MBED_TARGET_CONVERTED "mbed-")
target_link_libraries(mbed-core INTERFACE ${MBED_TARGET_CONVERTED})
if(${CMAKE_CROSSCOMPILING})
# Ensure the words that make up the Mbed target name are separated with a hyphen, lowercase, and with the `mbed-` prefix.
string(TOLOWER ${MBED_TARGET} MBED_TARGET_CONVERTED)
string(REPLACE "_" "-" MBED_TARGET_CONVERTED ${MBED_TARGET_CONVERTED})
string(PREPEND MBED_TARGET_CONVERTED "mbed-")
target_link_libraries(mbed-core INTERFACE ${MBED_TARGET_CONVERTED})
endif()
#
# Converts output file of `target` to binary file and to Intel HEX file.

View File

@ -18,6 +18,7 @@
"storage_filesystem",
"storage_tdb_external",
"fat_chan",
"cordio-stm32wb",
"lora",
"sx1276-lora-driver",
"stm32wl-lora-driver",

View File

@ -0,0 +1,7 @@
{
"macros": [
"MBEDTLS_SELF_TEST",
"MBEDTLS_TIMING_C",
"MBEDTLS_TIMING_ALT"
]
}

View File

@ -56,15 +56,15 @@ void led_thread()
#endif
#define MAX_RETRIES 3
NetworkInterface *interface = NULL;
NetworkInterface *netif = NULL;
static control_t setup_network(const size_t call_count)
{
interface = NetworkInterface::get_default_instance();
TEST_ASSERT_NOT_NULL_MESSAGE(interface, "failed to initialize network");
netif = NetworkInterface::get_default_instance();
TEST_ASSERT_NOT_NULL_MESSAGE(netif, "failed to initialize network");
nsapi_error_t err = -1;
for (int tries = 0; tries < MAX_RETRIES; tries++) {
err = interface->connect();
err = netif->connect();
if (err == NSAPI_ERROR_OK) {
break;
} else {
@ -78,34 +78,34 @@ static control_t setup_network(const size_t call_count)
static control_t download_128(const size_t call_count)
{
download_test(interface, story, sizeof(story), 128);
download_test(netif, story, sizeof(story), 128);
return CaseNext;
}
static control_t download_256(const size_t call_count)
{
download_test(interface, story, sizeof(story), 256);
download_test(netif, story, sizeof(story), 256);
return CaseNext;
}
static control_t download_1k(const size_t call_count)
{
download_test(interface, story, sizeof(story), 1024);
download_test(netif, story, sizeof(story), 1024);
return CaseNext;
}
static control_t download_2k(const size_t call_count)
{
download_test(interface, story, sizeof(story), 2 * 1024);
download_test(netif, story, sizeof(story), 2 * 1024);
return CaseNext;
}
static control_t download_4k(const size_t call_count)
{
download_test(interface, story, sizeof(story), 4 * 1024);
download_test(netif, story, sizeof(story), 4 * 1024);
return CaseNext;
}

View File

@ -61,16 +61,16 @@ void led_thread()
#endif
#define MAX_RETRIES 3
NetworkInterface *interface = NULL;
NetworkInterface *netif = NULL;
static control_t setup_network(const size_t call_count)
{
interface = NetworkInterface::get_default_instance();
TEST_ASSERT_NOT_NULL_MESSAGE(interface, "failed to initialize network");
netif = NetworkInterface::get_default_instance();
TEST_ASSERT_NOT_NULL_MESSAGE(netif, "failed to initialize network");
nsapi_error_t err = -1;
for (int tries = 0; tries < MAX_RETRIES; tries++) {
err = interface->connect();
err = netif->connect();
if (err == NSAPI_ERROR_OK) {
break;
} else {
@ -106,7 +106,7 @@ static uint32_t thread_counter = 0;
void download_fn()
{
uint32_t thread_id = core_util_atomic_incr_u32(&thread_counter, 1);
download_test(interface, story, sizeof(story), 256, thread_id);
download_test(netif, story, sizeof(story), 256, thread_id);
}
void file_fn(size_t buffer)
{

View File

@ -1,75 +1,39 @@
cmake_minimum_required(VERSION 3.0.2)
set(PROJECT_NAME unittests)
set(LIB_NAME MbedOS)
project(${PROJECT_NAME})
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# Setup c++ standard
macro(use_cxx14)
if (CMAKE_VERSION VERSION_LESS 3.1)
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++14")
endif()
else()
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
endmacro()
use_cxx14()
set(CMAKE_CXX_STANDARD 14 CACHE STRING "")
set(CMAKE_CXX_STANDARD_REQUIRED ON CACHE BOOL "")
add_definitions(-DUNITTEST)
if (MINGW)
# enable PRIx formatting globally
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__STDC_FORMAT_MACROS")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__STDC_FORMAT_MACROS")
# enable PRIx formatting globally
add_definitions(-D__STDC_FORMAT_MACROS)
endif (MINGW)
####################
# GTEST
####################
# Download and unpack googletest at configure time
configure_file(googletest-CMakeLists.txt.in googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
RESULT_VARIABLE result
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download)
if (result)
message(FATAL_ERROR "CMake failed for google test: ${result}")
endif()
execute_process(COMMAND ${CMAKE_COMMAND} --build .
RESULT_VARIABLE result
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download)
if (result)
message(FATAL_ERROR "Build failed for google test: ${result}")
endif()
include(FetchContent)
# Download and unpack googletest
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG master
)
FetchContent_MakeAvailable(googletest)
# Prevent overriding the parent project's compiler/linker
# settings on Windows
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
# Add googletest directly to our build. This defines
# the gtest and gtest_main targets.
add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src
${CMAKE_BINARY_DIR}/googletest-build
EXCLUDE_FROM_ALL)
# The gtest/gtest_main/gmock/gmock_main targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later.
target_include_directories(gmock_main SYSTEM BEFORE INTERFACE
"$<BUILD_INTERFACE:${gtest_SOURCE_DIR}/include>"
"$<BUILD_INTERFACE:${gmock_SOURCE_DIR}/include>")
####################
# TESTING
####################
include(CTest)
set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES
"${CMAKE_BINARY_DIR}/Testing"
"${CMAKE_BINARY_DIR}/Testing"
)
####################
@ -78,163 +42,21 @@ set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES
if (COVERAGE)
if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(WARNING "Non-debug build may result misleading code coverage results.")
endif()
if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(WARNING "Non-debug build may result misleading code coverage results.")
endif()
# Append coverage compiler flags
set(COVERAGE_COMPILER_FLAGS "-g -O0 --coverage")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}")
# Append coverage compiler flags
set(COVERAGE_COMPILER_FLAGS "-g -O0 --coverage")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" CACHE STRING "" FORCE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" CACHE STRING "" FORCE)
endif(COVERAGE)
if (VALGRIND)
find_program(MEMORYCHECK_COMMAND valgrind)
find_program(MEMORYCHECK_COMMAND valgrind)
endif(VALGRIND)
####################
# UNIT TESTS
####################
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DUNITTEST")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUNITTEST")
# Set include dirs.
set(unittest-includes-base
"${PROJECT_SOURCE_DIR}/target_h"
"${PROJECT_SOURCE_DIR}/../events/tests/UNITTESTS/target_h"
"${PROJECT_SOURCE_DIR}/../events/tests/UNITTESTS/target_h/equeue"
"${PROJECT_SOURCE_DIR}/target_h/platform"
"${PROJECT_SOURCE_DIR}/target_h/platform/cxxsupport"
"${PROJECT_SOURCE_DIR}/target_h/drivers"
"${PROJECT_SOURCE_DIR}/target_h/rtos/include"
"${PROJECT_SOURCE_DIR}/stubs"
"${PROJECT_SOURCE_DIR}/.."
"${PROJECT_SOURCE_DIR}/../features"
"${PROJECT_SOURCE_DIR}/../platform/include"
"${PROJECT_SOURCE_DIR}/../platform/include/platform"
"${PROJECT_SOURCE_DIR}/../platform/mbed-trace/include"
"${PROJECT_SOURCE_DIR}/../storage/filesystem/littlefs/include"
"${PROJECT_SOURCE_DIR}/../storage/filesystem/fat/include"
"${PROJECT_SOURCE_DIR}/../storage/blockdevice/include"
"${PROJECT_SOURCE_DIR}/../storage/filesystem/include"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/include"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/kv_config"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/kv_config/include"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/tdbstore/include"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/filesystemstore/include"
"${PROJECT_SOURCE_DIR}/../storage/kvstore/kvstore_global_api/include"
"${PROJECT_SOURCE_DIR}/../drivers"
"${PROJECT_SOURCE_DIR}/../drivers/include"
"${PROJECT_SOURCE_DIR}/../drivers/include/drivers"
"${PROJECT_SOURCE_DIR}/../drivers/include/drivers/internal"
"${PROJECT_SOURCE_DIR}/../hal"
"${PROJECT_SOURCE_DIR}/../hal/include"
"${PROJECT_SOURCE_DIR}/../events/include"
"${PROJECT_SOURCE_DIR}/../events/include/events/internal"
"${PROJECT_SOURCE_DIR}/../events/source"
"${PROJECT_SOURCE_DIR}/../rtos/include"
"${PROJECT_SOURCE_DIR}/../features/frameworks"
"${PROJECT_SOURCE_DIR}/../connectivity/libraries/nanostack-libservice"
"${PROJECT_SOURCE_DIR}/../connectivity/libraries/nanostack-libservice/mbed-client-libservice"
"${PROJECT_SOURCE_DIR}/../connectivity/netsocket/include"
"${PROJECT_SOURCE_DIR}/../features/filesystem/fat"
"${PROJECT_SOURCE_DIR}/../features/filesystem/fat/ChaN"
"${PROJECT_SOURCE_DIR}/../features/filesystem/bd"
"${PROJECT_SOURCE_DIR}/../features/filesystem/"
"${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs"
"${PROJECT_SOURCE_DIR}/../features/filesystem/littlefs/littlefs"
"${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/API"
"${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/AT"
"${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/device"
"${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework"
"${PROJECT_SOURCE_DIR}/../connectivity/cellular/include/cellular/framework/common"
"${PROJECT_SOURCE_DIR}/../connectivity"
"${PROJECT_SOURCE_DIR}/../connectivity/lorawan/include/lorawan"
"${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack"
"${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack/mac"
"${PROJECT_SOURCE_DIR}/../connectivity/lorawan/lorastack/phy"
"${PROJECT_SOURCE_DIR}/../connectivity/lorawan"
"${PROJECT_SOURCE_DIR}/../connectivity/mbedtls"
"${PROJECT_SOURCE_DIR}/../connectivity/mbedtls/include"
)
# Create a list for test suites.
set(TEST_SUITES)
# Get all matched tests.
file(GLOB_RECURSE unittest-file-list
"../unittest.cmake" # matches any ../**/unittest.cmake
)
if ("${unittest-file-list}" STREQUAL "")
message(FATAL_ERROR "No tests found. Exiting...")
endif()
# Create unit test targets
foreach(testfile ${unittest-file-list})
####################
# DEFINE TARGETS
####################
# Init file lists.
set(unittest-includes ${unittest-includes-base})
set(unittest-sources)
set(unittest-test-sources)
set(unittest-test-flags)
# Get source files
include("${testfile}")
get_filename_component(TEST_SUITE_DIR ${testfile} DIRECTORY)
file(RELATIVE_PATH
TEST_SUITE_NAME # output
"${PROJECT_SOURCE_DIR}/.." # root
${TEST_SUITE_DIR} #abs dirpath
)
string(REGEX REPLACE "/|\\\\" "-" TEST_SUITE_NAME ${TEST_SUITE_NAME})
set(TEST_SUITES ${TEST_SUITES} ${TEST_SUITE_NAME})
set(LIBS_TO_BE_LINKED gmock_main)
# Build directories list
set(BUILD_DIRECTORIES)
if (unittest-sources)
# Create the testable static library.
add_library("${TEST_SUITE_NAME}.${LIB_NAME}" STATIC ${unittest-sources})
target_include_directories("${TEST_SUITE_NAME}.${LIB_NAME}" PRIVATE
${unittest-includes})
target_compile_options("${TEST_SUITE_NAME}.${LIB_NAME}" PRIVATE
${unittest-test-flags})
set(LIBS_TO_BE_LINKED ${LIBS_TO_BE_LINKED} "${TEST_SUITE_NAME}.${LIB_NAME}")
# Append lib build directory to list
list(APPEND BUILD_DIRECTORIES "./CMakeFiles/${TEST_SUITE_NAME}.${LIB_NAME}.dir")
endif(unittest-sources)
if (unittest-test-sources)
# Create the executable.
add_executable(${TEST_SUITE_NAME} ${unittest-test-sources})
target_include_directories(${TEST_SUITE_NAME} PRIVATE
${unittest-includes})
target_compile_options(${TEST_SUITE_NAME} PRIVATE
${unittest-test-flags})
# Link the executable with the libraries.
target_link_libraries(${TEST_SUITE_NAME} ${LIBS_TO_BE_LINKED})
add_test(NAME "${TEST_SUITE_NAME}" COMMAND ${TEST_SUITE_NAME})
# Append test build directory to list
list(APPEND BUILD_DIRECTORIES "./CMakeFiles/${TEST_SUITE_NAME}.dir")
else()
message(WARNING "No test source files found for ${TEST_SUITE_NAME}.\n")
endif(unittest-test-sources)
endforeach(testfile)
add_subdirectory(stubs)
add_subdirectory(fakes)

View File

@ -1,306 +0,0 @@
## Unit testing
This document describes how to write and use unit tests for Arm Mbed OS.
### Introduction
Unit tests test code in small sections on a host machine. Unlike other testing tools, unit testing doesn't require embedded hardware or need to build a full operating system. Because of this, unit testing can result in faster tests than other tools. Unit testing happens in a build environment where you test each C or C++ class or module in isolation. Build test suites into separate test binaries and stub all access outside to remove dependencies on any specific embedded hardware or software combination. This allows you to complete tests using native compilers on the build machine.
### Prerequisites
Please install the following dependencies to use Mbed OS unit testing:
* GNU toolchains.
* GCC 6 or later. We recommend you use MinGW-W64 on Windows, but any Windows port of the above GCC versions works. Default compilers can be used on Mac OS instead of GCC to shorten build times, but code coverage results can differ.
* CMake 3.0 or newer.
* Python 2.7.x, 3.5 or newer.
* Pip 10.0 or newer.
* Gcovr 4.1 or newer.
* Arm Mbed CLI 1.8.0 or newer.
Detailed instructions for supported operating systems are below.
#### Installing dependencies on Debian or Ubuntu
In a terminal window:
1. `sudo apt-get -y install build-essential cmake`
1. Install Python and Pip with:
```
sudo apt-get -y install python python-setuptools
sudo easy_install pip
```
1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`.
#### Installing dependencies on macOS
In a terminal window:
1. Install [Homebrew](https://brew.sh/).
1. Install Xcode Command Line Tools with `xcode-select --install`.
1. Install CMake with: `brew install cmake`.
1. Install Python and Pip:
```
brew install python
sudo easy_install pip
```
1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`.
1. (Optional) Install GCC with `brew install gcc`.
#### Installing dependencies on Windows
In a terminal window:
1. Download and install MinGW-W64 from [SourceForge](https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/).
1. Download CMake binaries from https://cmake.org/download/, and run the installer.
1. Download Python 2.7 or Python 3 from https://www.python.org/getit/, and run the installer.
1. Add MinGW, CMake and Python into system PATH.
1. Install Gcovr and [Mbed CLI](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html) with `pip install "gcovr>=4.1" mbed-cli`.
### Test code structure
Find unit tests in the Mbed OS repository under the `UNITTESTS` folder. We recommend unit test files use an identical directory path as the file under test. This makes it easier to find unit tests for a particular class or a module. For example, if the file you're testing is `some/example/path/ClassName.cpp`, then all the test files are in the `UNITTESTS/some/example/path/ClassName` directory. Each test suite needs to have its own `unittest.cmake` file for test configuration.
All the class stubs should be located in the `UNITTESTS/stubs` directory. A single stub class can be used by multiple test suites and should follow the naming convention `ClassName_stub.cpp` for the source file, and `ClassName_stub.h` for the header file. Use the actual header files for the unit tests, and don't stub headers if possible. The stubbed headers reside in the `UNITTESTS/target_h` directory.
#### Test discovery
Registering unit tests to run happens automatically, and the test runner handles registration. However, test files do not automatically build. Build unit tests with a separate system that searches for unit tests under the `UNITTESTS` directory.
For the build system to find and build any test suite automatically, include a unit test configuration file named `unittest.cmake` for each unit test suite. This configuration file lists all the source files required for the test build.
#### Test names
The build system automatically generates names of test suites. The name is constructed by taking a relative file path from the UNITTESTS directory to the test directory and replacing path separators with dashes. For example, the test suite name for `some/example/path/ClassName.cpp` is `some-example-path-ClassName`. Suite names are used when deciding which test suites to run.
### Unit testing with Mbed CLI
Mbed CLI supports unit tests through the `mbed test --unittests` command. For information on using Mbed CLI, please see the [CLI documentation](https://os.mbed.com/docs/mbed-os/latest/tools/developing-mbed-cli.html).
### Writing unit tests
A unit tests suite consists of one or more test cases. The test cases should cover all the functions in a class under test. All the external dependencies are stubbed including the other classes in the same module. Avoid stubbing header files. Finally, analyze code coverage to ensure all code is tested, and no dead code is found.
Unit tests are written using [Google Test v1.10.0](https://github.com/google/googletest/releases/tag/release-1.10.0).
Please see the [documentation for Google Test](https://github.com/google/googletest/blob/master/googletest/docs/primer.md) to learn how to write unit tests using its framework. See the [documentation for Google Mock](https://github.com/google/googletest/blob/master/googlemock/docs/Documentation.md) if you want to write and use C++ mock classes instead of stubs.
#### Test suite configuration
Create two files in the test directory for each test suite:
* Unit test source file (`test_ClassName.cpp`).
* Unit test configuration file (`unittest.cmake`).
List all the required files for the build in the `unittest.cmake` file with paths relative to the `UNITTESTS` folder. Use the following variables to list the source files and include paths:
* **unittest-includes**: List of header include paths. You can use this to extend or overwrite default paths listed in `UNITTESTS/CMakeLists.txt`.
* **unittest-sources**: List of files under test.
* **unittest-test-sources**: List of test sources and stubs.
You can also set custom compiler flags and other configurations supported by CMake in `unittest.cmake`.
#### Example
With the following steps, you can write a simple unit test. This example creates dummy classes to be tested, creates and configures unit tests for a class and stubs all external dependencies.
1. Create the following dummy classes in `mbed-os/example`:
**MyClass.h**
```
#ifndef MYCLASS_H_
#define MYCLASS_H_
namespace example {
class MyClass {
public:
int myFunction();
};
}
#endif
```
**MyClass.cpp**
```
#include "MyClass.h"
#include "OtherClass.h"
namespace example {
int MyClass::myFunction() {
OtherClass o = OtherClass();
return o.otherFunction();
}
}
```
**OtherClass.h**
```
#ifndef OTHERCLASS_H_
#define OTHERCLASS_H_
namespace example {
class OtherClass {
public:
int otherFunction();
};
}
#endif
```
**OtherClass.cpp**
```
#include "OtherClass.h"
namespace example {
int OtherClass::otherFunction() {
return 1;
}
}
```
1. Create a directory for MyClass unit tests in `UNITTESTS/example/MyClass`.
1. Create a configuration file and a source file for MyClass unit tests in `UNITTESTS/example/MyClass`:
**unittest.cmake**
```
# Add here additional test specific include paths
set(unittest-includes ${unittest-includes}
../example
)
# Add here classes under test
set(unittest-sources
../example/MyClass.cpp
)
# Add here test classes and stubs
set(unittest-test-sources
example/MyClass/test_MyClass.cpp
stubs/OtherClass_stub.cpp
)
```
**test_MyClass.cpp**
```
#include "gtest/gtest.h"
#include "example/MyClass.h"
class TestMyClass : public testing::Test {
protected:
example::MyClass *obj;
virtual void SetUp()
{
obj = new example::MyClass();
}
virtual void TearDown()
{
delete obj;
}
};
TEST_F(TestMyClass, constructor)
{
EXPECT_TRUE(obj);
}
TEST_F(TestMyClass, myfunction)
{
EXPECT_EQ(obj->myFunction(), 0);
}
```
1. Stub all external dependencies. Create the following stub in `UNITTESTS/stubs`:
**OtherClass_stub.cpp**
```
#include "example/OtherClass.h"
namespace example {
int OtherClass::otherFunction() {
return 0;
}
}
```
This example does not use any Mbed OS code, but if your unit tests do, then remember to update header stubs in `UNITTESTS/target_h` and source stubs in `UNITTESTS/stubs` with any missing type or function declarations.
### Building and running unit tests
Use Mbed CLI to build and run unit tests. For advanced use, you can run CMake and a Make program directly.
#### Build tests directly with CMake
1. Create a build directory `mkdir UNITTESTS/build`.
1. Move to the build directory `cd UNITTESTS/build`.
1. Run CMake using a relative path to `UNITTESTS` folder as the argument. So from `UNITTESTS/build` use `cmake ..`:
* Add `-g [generator]` if generating other than Unix Makefiles such in case of MinGW use `-g "MinGW Makefiles"`.
* Add `-DCMAKE_MAKE_PROGRAM=<value>`, `-DCMAKE_CXX_COMPILER=<value>` and `-DCMAKE_C_COMPILER=<value>` to use a specific Make program and compilers.
* Add `-DCMAKE_BUILD_TYPE=Debug` for a debug build.
* Add `-DCOVERAGE=True` to add coverage compiler flags.
* Add `-Dgtest_disable_pthreads=ON` to run in a single thread.
* See the [CMake manual](https://cmake.org/cmake/help/v3.0/manual/cmake.1.html) for more information.
1. Run a Make program to build tests.
#### Run tests directly with CTest
Run a test binary in the build directory to run a unit test suite. To run multiple test suites at once, use the CTest test runner. Run CTest with `ctest`. Add `-v` to get results for each test case. See the [CTest manual](https://cmake.org/cmake/help/v3.0/manual/ctest.1.html) for more information.
#### Run tests with GUI test runner
1. Install `gtest-runner` according to the [documentation](https://github.com/nholthaus/gtest-runner).
1. Run `gtest-runner`.
1. Add test executables into the list and run.
### Debugging
1. Use Mbed CLI to build a debug build. For advanced use, run CMake directly with `-DCMAKE_BUILD_TYPE=Debug`, and then run a Make program.
1. Run GDB with a test executable as an argument to debug unit tests.
1. Run tests with Valgrind to analyze the test memory profile.
### Get code coverage
Use Mbed CLI to generate code coverage reports. For advanced use, follow these steps:
1. Run CMake with both `-DCMAKE_BUILD_TYPE=Debug` and `-DCOVERAGE=True`.
1. Run a Make program to build the tests.
1. Run the tests.
1. Run Gcovr or any other code coverage tool directly in the build directory.
### Troubleshooting
**Problem:** Generic problems with CMake or with the build process.
* **Solution**: Delete the build directory. Make sure that CMake, g++, GCC and a Make program can be found in the path and are correct versions.
**Problem:** (Windows) Virus protection identifies files generated by CMake as malicious and quarantines the files.
* **Solution**: Restore false-positive files from the quarantine.
**Problem:** (Windows) Git with shell installation adds sh.exe to the path and then CMake throws an error: sh.exe was found in your PATH. For MinGW make to work correctly, sh.exe must NOT be in your path.
* **Solution**: Remove sh.exe from the system path.
**Problem:** (Mac OS) CMake compiler check fails on Mac OS Mojave when using GCC-8.
* **Solution**: Make sure gnm (binutils) is not installed. Uninstall binutils with `brew uninstall binutils`.

View File

@ -1,57 +0,0 @@
####################
# UNIT TESTS
####################
set(unittest-includes ${unittest-includes}
.
..
../connectivity/mbedtls/include/mbedtls/
../connectivity/mbedtls/platform/inc/
../platform/mbed-trace/include/mbed-trace/
)
set(unittest-test-sources
empty_baseline/empty_baseline.cpp
)
set(unittest-test-flags
-DDEVICE_ANALOGIN
-DDEVICE_ANALOGOUT
-DDEVICE_CAN
-DDEVICE_ETHERNET
-DDEVICE_FLASH
-DDEVICE_I2C
-DDEVICE_I2CSLAVE
-DDEVICE_I2C_ASYNCH
-DDEVICE_INTERRUPTIN
-DDEVICE_LPTICKER
-DDEVICE_PORTIN
-DDEVICE_PORTINOUT
-DDEVICE_PORTOUT
-DDEVICE_PWMOUT
-DDEVICE_QSPI
-DDEVICE_SERIAL
-DDEVICE_SERIAL_ASYNCH
-DDEVICE_SERIAL_FC
-DDEVICE_SPI
-DDEVICE_SPISLAVE
-DDEVICE_SPI_ASYNCH
-DCOMPONENT_FLASHIAP
-DMBED_CONF_PLATFORM_CTHUNK_COUNT_MAX=10
-DMBED_CONF_DATAFLASH_SPI_FREQ=1
-DMBED_CONF_FLASHIAP_BLOCK_DEVICE_BASE_ADDRESS=0
-DMBED_CONF_FLASHIAP_BLOCK_DEVICE_SIZE=0
-DMBED_CONF_QSPIF_QSPI_FREQ=1
-DMBED_CONF_QSPIF_QSPI_MIN_READ_SIZE=1
-DMBED_CONF_QSPIF_QSPI_MIN_PROG_SIZE=1
-DMBED_LFS_READ_SIZE=64
-DMBED_LFS_PROG_SIZE=64
-DMBED_LFS_BLOCK_SIZE=512
-DMBED_LFS_LOOKAHEAD=512
-DFLASHIAP_APP_ROM_END_ADDR=0x80000
-DMBED_CONF_STORAGE_TDB_INTERNAL_INTERNAL_SIZE=1024
-DMBED_CONF_STORAGE_TDB_INTERNAL_INTERNAL_BASE_ADDRESS=0x80000
-DMBED_CONF_STORAGE_STORAGE_TYPE=default
-DMBED_CONF_FAT_CHAN_FF_MAX_SS=4096
)

View File

@ -0,0 +1,5 @@
# Copyright (c) 2020 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_subdirectory(events)
add_subdirectory(ble)

163
UNITTESTS/fakes/ble/BLE.cpp Normal file
View File

@ -0,0 +1,163 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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/BLE.h"
#include "GattServerImpl_mock.h"
#include "GattClientImpl_mock.h"
#include "GapImpl_mock.h"
#include "SecurityManagerImpl_mock.h"
#include "ble/GattClient.h"
#include "ble/GattServer.h"
#include "ble/SecurityManager.h"
#include "ble/Gap.h"
#include "ble_mocks.h"
namespace ble {
static GapMock *gap_impl = nullptr;
static GattServerMock *gatt_server_impl = nullptr;
static GattClientMock *gatt_client_impl = nullptr;
static SecurityManagerMock *security_manager_impl = nullptr;
static Gap *gap = nullptr;
static GattServer *gatt_server = nullptr;
static GattClient *gatt_client = nullptr;
static SecurityManager *security_manager = nullptr;
GapMock& gap_mock() {
return *ble::gap_impl;
}
GattServerMock& gatt_server_mock() {
return *ble::gatt_server_impl;
}
GattClientMock& gatt_client_mock() {
return *ble::gatt_client_impl;
}
SecurityManagerMock& security_manager_mock() {
return *ble::security_manager_impl;
}
void init_mocks() {
if (gap_impl) {
/* we are already initialised */
return;
}
/* mocks */
gap_impl = new GapMock();
gatt_server_impl = new GattServerMock();
gatt_client_impl = new GattClientMock();
security_manager_impl = new SecurityManagerMock();
/* user APIS */
gap = new Gap(gap_impl);
gatt_server = new GattServer(gatt_server_impl);
gatt_client = new GattClient(gatt_client_impl);
security_manager = new SecurityManager(security_manager_impl);
}
void delete_mocks() {
delete gap;
delete gap_impl;
delete gatt_server;
delete gatt_server_impl;
delete gatt_client;
delete gatt_client_impl;
delete security_manager;
delete security_manager_impl;
gap = nullptr;
gap_impl = nullptr;
gatt_server = nullptr;
gatt_server_impl = nullptr;
gatt_client = nullptr;
gatt_client_impl = nullptr;
security_manager = nullptr;
security_manager_impl = nullptr;
}
class BLEInstanceBase {
};
BLE::BLE(ble::BLEInstanceBase &transport) : transport(transport)
{
}
BLE& BLE::Instance()
{
static ble::BLEInstanceBase transport;
static BLE instance(transport);
init_mocks();
return instance;
}
ble::Gap &BLE::gap()
{
init_mocks();
return *ble::gap;
}
ble::GattServer &BLE::gattServer()
{
init_mocks();
return *ble::gatt_server;
}
ble::GattClient &BLE::gattClient()
{
init_mocks();
return *ble::gatt_client;
}
ble::SecurityManager &BLE::securityManager()
{
init_mocks();
return *ble::security_manager;
}
const ble::Gap &BLE::gap() const
{
auto &self = const_cast<BLE &>(*this);
return const_cast<const ble::Gap &>(self.gap());
}
const ble::GattServer &BLE::gattServer() const
{
auto &self = const_cast<BLE &>(*this);
return const_cast<const ble::GattServer &>(self.gattServer());
}
const ble::GattClient &BLE::gattClient() const
{
auto &self = const_cast<BLE &>(*this);
return const_cast<const ble::GattClient &>(self.gattClient());
}
const ble::SecurityManager &BLE::securityManager() const
{
auto &self = const_cast<BLE &>(*this);
return const_cast<const ble::SecurityManager &>(self.securityManager());
}
void BLE::processEvents()
{
}
}

View File

@ -0,0 +1,41 @@
# Copyright (c) 2020 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-fakes-ble)
target_include_directories(mbed-fakes-ble
PUBLIC
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/include
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/include/ble
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source
PRIVATE
${gtest_SOURCE_DIR}/include
${gmock_SOURCE_DIR}/include
)
target_sources(mbed-fakes-ble
PRIVATE
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/gap/AdvertisingParameters.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/gap/ConnectionParameters.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/gatt/DiscoveredCharacteristic.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/Gap.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/GattClient.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/GattServer.cpp
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/source/SecurityManager.cpp
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/BLE.cpp
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/source/GattServerImpl_mock.cpp
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/ble_mocks.h
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/GapImpl_mock.h
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/GattClientImpl_mock.h
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/GattServerImpl_mock.h
${mbed-os_SOURCE_DIR}/UNITTESTS/fakes/ble/SecurityManagerImpl_mock.h
)
target_link_libraries(mbed-fakes-ble
PRIVATE
mbed-headers
mbed-stubs-headers
gcov
)

View File

@ -0,0 +1,91 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GAPMOCK_H
#define BLE_GAPMOCK_H
#include "gmock/gmock.h"
#include "source/generic/GapImpl.h"
namespace ble {
class GapMock : public ble::impl::Gap {
public:
GapMock() {};
GapMock(const GapMock&) = delete;
GapMock& operator=(const GapMock&) = delete;
virtual ~GapMock() {};
MOCK_METHOD((ble_error_t), reset, (), (override));
MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override));
MOCK_METHOD(bool, isFeatureSupported, (controller_supported_features_t feature), (override));
MOCK_METHOD(uint8_t, getMaxAdvertisingSetNumber, (), (override));
MOCK_METHOD(uint16_t, getMaxAdvertisingDataLength, (), (override));
MOCK_METHOD(uint16_t, getMaxConnectableAdvertisingDataLength, (), (override));
MOCK_METHOD(uint16_t, getMaxActiveSetAdvertisingDataLength, (), (override));
MOCK_METHOD(ble_error_t, createAdvertisingSet, (advertising_handle_t *handle, const AdvertisingParameters &parameters), (override));
MOCK_METHOD(ble_error_t, destroyAdvertisingSet, (advertising_handle_t handle), (override));
MOCK_METHOD(ble_error_t, setAdvertisingParameters, (advertising_handle_t handle, const AdvertisingParameters &params), (override));
MOCK_METHOD(ble_error_t, setAdvertisingPayload, (advertising_handle_t handle, mbed::Span<const uint8_t> payload), (override));
MOCK_METHOD(ble_error_t, setAdvertisingScanResponse, (advertising_handle_t handle, mbed::Span<const uint8_t> response), (override));
MOCK_METHOD(ble_error_t, startAdvertising, (advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents), (override));
MOCK_METHOD(ble_error_t, stopAdvertising, (advertising_handle_t handle), (override));
MOCK_METHOD(bool, isAdvertisingActive, (advertising_handle_t handle), (override));
MOCK_METHOD(ble_error_t, setPeriodicAdvertisingParameters, (advertising_handle_t handle, periodic_interval_t periodicAdvertisingIntervalMin, periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower), (override));
MOCK_METHOD(ble_error_t, setPeriodicAdvertisingPayload, (advertising_handle_t handle, mbed::Span<const uint8_t> payload), (override));
MOCK_METHOD(ble_error_t, startPeriodicAdvertising, (advertising_handle_t handle), (override));
MOCK_METHOD(ble_error_t, stopPeriodicAdvertising, (advertising_handle_t handle), (override));
MOCK_METHOD(bool, isPeriodicAdvertisingActive, (advertising_handle_t handle), (override));
MOCK_METHOD(ble_error_t, setScanParameters, (const ScanParameters &params), (override));
MOCK_METHOD(ble_error_t, startScan, (scan_duration_t duration, duplicates_filter_t filtering, scan_period_t period), (override));
MOCK_METHOD(ble_error_t, initiate_scan, (), (override));
MOCK_METHOD(ble_error_t, stopScan, (), (override));
MOCK_METHOD(ble_error_t, createSync, (peer_address_type_t peerAddressType, const address_t &peerAddress, uint8_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout), (override));
MOCK_METHOD(ble_error_t, createSync, (slave_latency_t maxPacketSkip, sync_timeout_t timeout), (override));
MOCK_METHOD(ble_error_t, cancelCreateSync, (), (override));
MOCK_METHOD(ble_error_t, terminateSync, (periodic_sync_handle_t handle), (override));
MOCK_METHOD(ble_error_t, addDeviceToPeriodicAdvertiserList, (peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid), (override));
MOCK_METHOD(ble_error_t, removeDeviceFromPeriodicAdvertiserList, (peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid), (override));
MOCK_METHOD(ble_error_t, clearPeriodicAdvertiserList, (), (override));
MOCK_METHOD(ble_error_t, connect, (peer_address_type_t peerAddressType, const address_t &peerAddress, const ConnectionParameters &connectionParams), (override));
MOCK_METHOD(ble_error_t, cancelConnect, (), (override));
MOCK_METHOD(ble_error_t, updateConnectionParameters, (connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength), (override));
MOCK_METHOD(ble_error_t, manageConnectionParametersUpdateRequest, (bool userManageConnectionUpdateRequest), (override));
MOCK_METHOD(ble_error_t, acceptConnectionParametersUpdate, (connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength), (override));
MOCK_METHOD(ble_error_t, rejectConnectionParametersUpdate, (connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, disconnect, (connection_handle_t connectionHandle, local_disconnection_reason_t reason), (override));
MOCK_METHOD(ble_error_t, readPhy, (connection_handle_t connection), (override));
MOCK_METHOD(ble_error_t, setPreferredPhys, (const phy_set_t *txPhys, const phy_set_t *rxPhys), (override));
MOCK_METHOD(ble_error_t, setPhy, (connection_handle_t connection, const phy_set_t *txPhys, const phy_set_t *rxPhys, coded_symbol_per_bit_t codedSymbol), (override));
MOCK_METHOD(ble_error_t, enablePrivacy, (bool enable), (override));
MOCK_METHOD(ble_error_t, setPeripheralPrivacyConfiguration, (const peripheral_privacy_configuration_t *configuration), (override));
MOCK_METHOD(ble_error_t, getPeripheralPrivacyConfiguration, (peripheral_privacy_configuration_t *configuration), (override));
MOCK_METHOD(ble_error_t, setCentralPrivacyConfiguration, (const central_privacy_configuration_t *configuration), (override));
MOCK_METHOD(ble_error_t, getCentralPrivacyConfiguration, (central_privacy_configuration_t *configuration), (override));
MOCK_METHOD(uint8_t, getMaxWhitelistSize, (), (const, override));
MOCK_METHOD(ble_error_t, getWhitelist, (whitelist_t &whitelist), (const, override));
MOCK_METHOD(ble_error_t, setWhitelist, (const whitelist_t &whitelist), (override));
MOCK_METHOD(ble_error_t, getAddress, (own_address_type_t &typeP, address_t &address), (override));
MOCK_METHOD(void, onShutdown, (const GapShutdownCallback_t &callback), (override));
MOCK_METHOD(GapShutdownCallbackChain_t&, onShutdown, (), (override));
MOCK_METHOD(ble_error_t, setRandomStaticAddress, (const ble::address_t &address), (override));
MOCK_METHOD(ble::address_t, getRandomStaticAddress, (), (override));
};
}
#endif //BLE_GAPMOCK_H

View File

@ -0,0 +1,62 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GATTCLIENTMOCK_H
#define BLE_GATTCLIENTMOCK_H
#include "gmock/gmock.h"
#include "source/generic/GattClientImpl.h"
namespace ble {
class GattClientMock : public ble::impl::GattClient {
public:
GattClientMock() {};
GattClientMock(const GattClientMock&) = delete;
GattClientMock& operator=(const GattClientMock&) = delete;
virtual ~GattClientMock() {};
MOCK_METHOD(ble_error_t, reset, (), (override));
MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override));
MOCK_METHOD(ble_error_t, launchServiceDiscovery, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t sc, ServiceDiscovery::CharacteristicCallback_t cc, const UUID &matchingServiceUUID, const UUID &matchingCharacteristicUUIDIn), (override));
MOCK_METHOD(ble_error_t, discoverServices, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t callback, const UUID &matchingServiceUUID), (override));
MOCK_METHOD(ble_error_t, discoverServices, (ble::connection_handle_t connectionHandle, ServiceDiscovery::ServiceCallback_t callback, GattAttribute::Handle_t startHandle, GattAttribute::Handle_t endHandle), (override));
MOCK_METHOD(bool, isServiceDiscoveryActive, (), (const, override));
MOCK_METHOD(void, terminateServiceDiscovery, (), (override));
MOCK_METHOD(ble_error_t, read, (ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle, uint16_t offset), (const, override));
MOCK_METHOD(ble_error_t, write, (GattClient::WriteOp_t cmd, ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle, size_t length, const uint8_t *value), (const, override));
MOCK_METHOD(void, onDataRead, (ReadCallback_t callback), (override));
MOCK_METHOD(ReadCallbackChain_t&, onDataRead, (), (override));
MOCK_METHOD(void, onDataWritten, (WriteCallback_t callback), (override));
MOCK_METHOD(WriteCallbackChain_t&, onDataWritten, (), (override));
MOCK_METHOD(void, onServiceDiscoveryTermination, (ServiceDiscovery::TerminationCallback_t callback), (override));
MOCK_METHOD(ble_error_t, discoverCharacteristicDescriptors, (const DiscoveredCharacteristic &characteristic, const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback, const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback), (override));
MOCK_METHOD(bool, isCharacteristicDescriptorDiscoveryActive, (const DiscoveredCharacteristic &characteristic), (const, override));
MOCK_METHOD(void, terminateCharacteristicDescriptorDiscovery, (const DiscoveredCharacteristic &characteristic), (override));
MOCK_METHOD(ble_error_t, negotiateAttMtu, (ble::connection_handle_t connection), (override));
MOCK_METHOD(void, onHVX, (HVXCallback_t callback), (override));
MOCK_METHOD(void, onShutdown, (const GattClientShutdownCallback_t &callback), (override));
MOCK_METHOD(GattClientShutdownCallbackChain_t&, onShutdown, (), (override));
MOCK_METHOD(HVXCallbackChain_t&, onHVX, (), (override));
MOCK_METHOD(void, processReadResponse, (const GattReadCallbackParams *params), (override));
MOCK_METHOD(void, processWriteResponse, (const GattWriteCallbackParams *params), (override));
MOCK_METHOD(void, processHVXEvent, (const GattHVXCallbackParams *params), (override));
};
}
#endif //BLE_GATTCLIENTMOCK_H

View File

@ -0,0 +1,105 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GATTSERVERMOCK_H
#define BLE_GATTSERVERMOCK_H
#include "gmock/gmock.h"
#include "source/GattServerImpl.h"
namespace ble {
class GattServerMock : public ble::impl::GattServer {
public:
GattServerMock();
GattServerMock(const GattServerMock&) = delete;
GattServerMock& operator=(const GattServerMock&) = delete;
virtual ~GattServerMock();
MOCK_METHOD(ble_error_t, reset, (ble::GattServer* server), (override));
MOCK_METHOD(void, setEventHandler, (EventHandler *handler), (override));
MOCK_METHOD(ble_error_t, addService, (GattService &service), (override));
MOCK_METHOD(ble_error_t, read, (GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP), (override));
MOCK_METHOD(ble_error_t, read, (ble::connection_handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP), (override));
MOCK_METHOD(ble_error_t, write, (GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly), (override));
MOCK_METHOD(ble_error_t, write, (ble::connection_handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly), (override));
MOCK_METHOD(ble_error_t, areUpdatesEnabled, (const GattCharacteristic &characteristic, bool *enabledP), (override));
MOCK_METHOD(ble_error_t, areUpdatesEnabled, (ble::connection_handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP), (override));
MOCK_METHOD(ble::Gap::PreferredConnectionParams_t, getPreferredConnectionParams, (), (override));
MOCK_METHOD(void, setPreferredConnectionParams, (const ble::Gap::PreferredConnectionParams_t &params), (override));
MOCK_METHOD(bool, isOnDataReadAvailable, (), (const, override));
MOCK_METHOD(void, onDataSent, (const DataSentCallback_t &callback), (override));
MOCK_METHOD(DataSentCallbackChain_t&, onDataSent, (), (override));
MOCK_METHOD(void, onDataWritten, (const DataWrittenCallback_t &callback), (override));
MOCK_METHOD(DataWrittenCallbackChain_t&, onDataWritten, (), (override));
MOCK_METHOD(ble_error_t, onDataRead, (const DataReadCallback_t &callback), (override));
MOCK_METHOD(DataReadCallbackChain_t&, onDataRead, (), (override));
MOCK_METHOD(void, onShutdown, (const GattServerShutdownCallback_t &callback), (override));
MOCK_METHOD(GattServerShutdownCallbackChain_t&, onShutdown, (), (override));
MOCK_METHOD(void, onUpdatesEnabled, (EventCallback_t callback), (override));
MOCK_METHOD(void, onUpdatesDisabled, (EventCallback_t callback), (override));
MOCK_METHOD(void, onConfirmationReceived, (EventCallback_t callback), (override));
MOCK_METHOD(void, handleDataWrittenEvent, (const GattWriteCallbackParams *params), (override));
MOCK_METHOD(void, handleDataReadEvent, (const GattReadCallbackParams *params), (override));
MOCK_METHOD(void, handleEvent, (GattServerEvents::gattEvent_e type, ble::connection_handle_t connHandle, GattAttribute::Handle_t attributeHandle), (override));
MOCK_METHOD(void, handleDataSentEvent, (unsigned count), (override));
// Fake part
// Descriptor representation of a descriptor registered with ble::test::register_services
struct descriptor_t {
UUID uuid;
ble::attribute_handle_t handle;
ble::att_security_requirement_t read_security = ble::att_security_requirement_t::NONE;
ble::att_security_requirement_t write_security = ble::att_security_requirement_t::NONE;
bool is_readable;
bool is_writable;
std::vector<uint8_t> value; // Use capacity to determine the max size.
};
// Characteristic representation of a characteristic registered with ble::test::register_services
struct characteristic_t {
UUID uuid;
ble::attribute_handle_t value_handle;
uint8_t properties;
ble::att_security_requirement_t read_security = ble::att_security_requirement_t::NONE;
ble::att_security_requirement_t write_security = ble::att_security_requirement_t::NONE;
ble::att_security_requirement_t update_security = ble::att_security_requirement_t::NONE;
FunctionPointerWithContext<GattReadAuthCallbackParams *>
read_cb;
FunctionPointerWithContext<GattWriteAuthCallbackParams *>
write_cb;
bool has_variable_len;
std::vector<uint8_t> value; // Use capacity to determine the max size.
std::vector<descriptor_t> descriptors;
};
// Service representation of a service registered with ble::test::register_services
struct service_t {
UUID uuid;
ble::attribute_handle_t handle;
std::vector<characteristic_t> characteristics;
};
void fake_register_services(GattService& gattService);
std::vector<service_t> services;
ble::attribute_handle_t current_handle = 1;
};
}
#endif //BLE_GATTSERVERMOCK_H

View File

@ -0,0 +1,73 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 SECURITYMANAGERMOCK_H
#define SECURITYMANAGERMOCK_H
#include "gmock/gmock.h"
#include "source/generic/SecurityManagerImpl.h"
namespace ble {
class SecurityManagerMock : public ble::impl::SecurityManager {
public:
SecurityManagerMock() {};
SecurityManagerMock(const GattServerMock&) = delete;
SecurityManagerMock& operator=(const GattServerMock&) = delete;
virtual ~SecurityManagerMock() {};
MOCK_METHOD(ble_error_t, reset, (), (override));
MOCK_METHOD(ble_error_t, init, (bool enableBonding, bool requireMITM, SecurityIOCapabilities_t iocaps, const Passkey_t passkey, bool signing, const char *dbFilepath), (override));
MOCK_METHOD(ble_error_t, setDatabaseFilepath, (const char *dbFilepath), (override));
MOCK_METHOD(ble_error_t, preserveBondingStateOnReset, (bool enable), (override));
MOCK_METHOD(ble_error_t, purgeAllBondingState, (), (override));
MOCK_METHOD(ble_error_t, generateWhitelistFromBondTable, (::ble::whitelist_t *whitelist), (const, override));
MOCK_METHOD(ble_error_t, requestPairing, (ble::connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, acceptPairingRequest, (ble::connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, cancelPairingRequest, (ble::connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, setPairingRequestAuthorisation, (bool required), (override));
MOCK_METHOD(ble_error_t, getPeerIdentity, (ble::connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, allowLegacyPairing, (bool allow), (override));
MOCK_METHOD(ble_error_t, getSecureConnectionsSupport, (bool *enabled), (override));
MOCK_METHOD(ble_error_t, setIoCapability, (SecurityIOCapabilities_t iocaps), (override));
MOCK_METHOD(ble_error_t, setDisplayPasskey, (const Passkey_t passkey), (override));
MOCK_METHOD(ble_error_t, setLinkSecurity, (ble::connection_handle_t connectionHandle, SecurityMode_t securityMode), (override));
MOCK_METHOD(ble_error_t, setKeypressNotification, (bool enabled), (override));
MOCK_METHOD(ble_error_t, enableSigning, (ble::connection_handle_t connectionHandle, bool enabled), (override));
MOCK_METHOD(ble_error_t, setHintFutureRoleReversal, (bool enable), (override));
MOCK_METHOD(ble_error_t, getLinkEncryption, (ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption), (override));
MOCK_METHOD(ble_error_t, setLinkEncryption, (ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption), (override));
MOCK_METHOD(ble_error_t, setEncryptionKeyRequirements, (uint8_t minimumByteSize, uint8_t maximumByteSize), (override));
MOCK_METHOD(ble_error_t, getEncryptionKeySize, (connection_handle_t connectionHandle, uint8_t *size), (override));
MOCK_METHOD(ble_error_t, requestAuthentication, (ble::connection_handle_t connectionHandle), (override));
MOCK_METHOD(ble_error_t, generateOOB, (const ble::address_t *address), (override));
MOCK_METHOD(ble_error_t, setOOBDataUsage, (ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM), (override));
MOCK_METHOD(ble_error_t, passkeyEntered, (ble::connection_handle_t connectionHandle, Passkey_t passkey), (override));
MOCK_METHOD(ble_error_t, legacyPairingOobReceived, (const ble::address_t *address, const ble::oob_tk_t *tk), (override));
MOCK_METHOD(ble_error_t, confirmationEntered, (ble::connection_handle_t connectionHandle, bool confirmation), (override));
MOCK_METHOD(ble_error_t, sendKeypressNotification, (ble::connection_handle_t connectionHandle, ble::Keypress_t keypress), (override));
MOCK_METHOD(ble_error_t, oobReceived, (const ble::address_t *address, const ble::oob_lesc_value_t *random, const ble::oob_confirm_t *confirm), (override));
MOCK_METHOD(ble_error_t, getSigningKey, (ble::connection_handle_t connectionHandle, bool authenticated), (override));
MOCK_METHOD(ble_error_t, setPrivateAddressTimeout, (uint16_t timeout_in_seconds), (override));
MOCK_METHOD(void, onShutdown, (const SecurityManagerShutdownCallback_t &callback), (override));
MOCK_METHOD(SecurityManagerShutdownCallbackChain_t&, onShutdown, (), (override));
MOCK_METHOD(void, setSecurityManagerEventHandler, (EventHandler *handler), (override));
};
}
#endif //SECURITYMANAGERMOCK_H

View File

@ -0,0 +1,45 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_MOCKS_H
#define BLE_MOCKS_H
#include "GattServerImpl_mock.h"
#include "GattClientImpl_mock.h"
#include "GapImpl_mock.h"
#include "SecurityManagerImpl_mock.h"
/***
* You must use delete_mocks() at the end of the test. BLE::Instance(), ble::gap() etc. inits the mocks. Do not cache
* pointers between tests. Call BLE::Instance() at the start of the tests, otherwise call init_mocks() yourself.
* To access mocks use:
* gap_mock(), gatt_server_mock(), gatt_client_mock(), security_manager_mock().
* All functions are in namespace ble.
*/
namespace ble {
void init_mocks();
void delete_mocks();
GapMock& gap_mock();
GattServerMock& gatt_server_mock();
GattClientMock& gatt_client_mock();
SecurityManagerMock& security_manager_mock();
}
#endif // BLE_MOCKS_H

View File

@ -0,0 +1,137 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GATTSERVERSTUB_H
#define BLE_GATTSERVERSTUB_H
#include "ble/GattServer.h"
#include "generic/GattServerEvents.h"
#include "ble/Gap.h"
namespace ble {
namespace impl {
class GattServer {
public:
GattServer() {};
GattServer(const GattServer&) = delete;
GattServer& operator=(const GattServer&) = delete;
virtual ~GattServer() {};
using EventHandler = ble::GattServer::EventHandler;
using DataSentCallback_t = ble::GattServer::DataSentCallback_t ;
using DataSentCallbackChain_t = ble::GattServer::DataSentCallbackChain_t ;
using DataWrittenCallback_t = ble::GattServer::DataWrittenCallback_t ;
using DataWrittenCallbackChain_t = ble::GattServer::DataWrittenCallbackChain_t ;
using DataReadCallback_t = ble::GattServer::DataReadCallback_t;
using DataReadCallbackChain_t = ble::GattServer::DataReadCallbackChain_t;
using GattServerShutdownCallback_t = ble::GattServer::GattServerShutdownCallback_t;
using GattServerShutdownCallbackChain_t = ble::GattServer::GattServerShutdownCallbackChain_t;
using EventCallback_t = ble::GattServer::EventCallback_t;
virtual void setEventHandler(EventHandler *handler) { };
virtual ble_error_t reset(ble::GattServer* server) { return BLE_ERROR_NONE; };
virtual ble_error_t addService(GattService &service) { return BLE_ERROR_NONE; };
virtual ble_error_t read(
GattAttribute::Handle_t attributeHandle,
uint8_t buffer[],
uint16_t *lengthP
) { return BLE_ERROR_NONE; };
virtual ble_error_t read(
ble::connection_handle_t connectionHandle,
GattAttribute::Handle_t attributeHandle,
uint8_t *buffer,
uint16_t *lengthP
) { return BLE_ERROR_NONE; };
virtual ble_error_t write(
GattAttribute::Handle_t attributeHandle,
const uint8_t *value,
uint16_t size,
bool localOnly = false
) { return BLE_ERROR_NONE; };
virtual ble_error_t write(
ble::connection_handle_t connectionHandle,
GattAttribute::Handle_t attributeHandle,
const uint8_t *value,
uint16_t size,
bool localOnly = false
) { return BLE_ERROR_NONE; };
virtual ble_error_t areUpdatesEnabled(
const GattCharacteristic &characteristic,
bool *enabledP
) { return BLE_ERROR_NONE; };
virtual ble_error_t areUpdatesEnabled(
ble::connection_handle_t connectionHandle,
const GattCharacteristic &characteristic,
bool *enabledP
) { return BLE_ERROR_NONE; };
virtual ble::Gap::PreferredConnectionParams_t getPreferredConnectionParams() {
ble::Gap::PreferredConnectionParams_t params = {0}; return params;
};
virtual void setPreferredConnectionParams(const ble::Gap::PreferredConnectionParams_t &params) { };
virtual bool isOnDataReadAvailable() const { return true; };
virtual void onDataSent(const DataSentCallback_t &callback) { };
virtual DataSentCallbackChain_t &onDataSent() { static DataSentCallbackChain_t chain; return chain; };
virtual void onDataWritten(const DataWrittenCallback_t &callback) { };
virtual DataWrittenCallbackChain_t &onDataWritten() { static DataWrittenCallbackChain_t chain; return chain; };
virtual ble_error_t onDataRead(const DataReadCallback_t &callback) { return BLE_ERROR_NONE; };
virtual DataReadCallbackChain_t &onDataRead() { static DataReadCallbackChain_t chain; return chain; };
virtual void onShutdown(const GattServerShutdownCallback_t &callback) { };
virtual GattServerShutdownCallbackChain_t &onShutdown() { static GattServerShutdownCallbackChain_t chain; return chain; };
virtual void onUpdatesEnabled(EventCallback_t callback) { };
virtual void onUpdatesDisabled(EventCallback_t callback) { };
virtual void onConfirmationReceived(EventCallback_t callback) { };
virtual void handleDataWrittenEvent(const GattWriteCallbackParams *params) { };
virtual void handleDataReadEvent(const GattReadCallbackParams *params) { };
virtual void handleEvent(
GattServerEvents::gattEvent_e type,
ble::connection_handle_t connHandle,
GattAttribute::Handle_t attributeHandle
) { };
virtual void handleDataSentEvent(unsigned count) { };
};
}
}
#endif //BLE_GATTSERVERSTUB_H

View File

@ -0,0 +1,96 @@
/* mbed Microcontroller Library
* Copyright (c) 2021 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "GattServerImpl_mock.h"
namespace ble {
GattServerMock::GattServerMock()
{
ON_CALL(*this, addService).WillByDefault([this](GattService &service) {
// Fake registration, it populates the handles of the input and store its
// representation in the services field.
fake_register_services(service);
return BLE_ERROR_NONE;
});
}
GattServerMock::~GattServerMock() {};
void GattServerMock::fake_register_services(GattService& gattService)
{
gattService.setHandle(current_handle++);
service_t result {
gattService.getUUID(),
gattService.getHandle()
};
for (size_t i = 0; i < gattService.getCharacteristicCount(); ++i) {
current_handle++; // Increment for the characteristic declaration handle
auto& ref = *gattService.getCharacteristic(i);
ref.getValueAttribute().setHandle(current_handle++);
characteristic_t c;
c.uuid = ref.getValueAttribute().getUUID();
c.value_handle = ref.getValueHandle();
c.properties = ref.getProperties();
c.read_security = ref.getReadSecurityRequirement();
c.write_security = ref.getWriteSecurityRequirement();
c.update_security = ref.getUpdateSecurityRequirement();
c.read_cb = ref.getReadAuthorizationCallback();
c.write_cb = ref.getWriteAuthorizationCallback();
c.value.reserve(ref.getValueAttribute().getMaxLength());
c.value.resize(ref.getValueAttribute().getLength());
{
auto value_ptr = ref.getValueAttribute().getValuePtr();
if (value_ptr) {
std::copy(value_ptr, value_ptr + c.value.size(), c.value.begin());
}
}
c.has_variable_len = ref.getValueAttribute().hasVariableLength();
for (size_t j = 0; j < ref.getDescriptorCount(); ++j) {
auto& ref_desc = *ref.getDescriptor(j);
ref_desc.setHandle(current_handle++);
descriptor_t d;
d.uuid = ref_desc.getUUID();
d.handle = ref_desc.getHandle();
d.read_security = ref_desc.getReadSecurityRequirement();
d.write_security = ref_desc.getWriteSecurityRequirement();
d.is_readable = ref_desc.isReadAllowed();
d.is_writable = ref_desc.isWriteAllowed();
d.value.reserve(ref_desc.getMaxLength());
d.value.resize(ref_desc.getLength());
{
auto value_ptr = ref_desc.getValuePtr();
if (value_ptr) {
std::copy(value_ptr, value_ptr + d.value.size(), d.value.begin());
}
}
c.descriptors.push_back(d);
}
result.characteristics.push_back(c);
}
services.push_back(result);
}
}

View File

@ -0,0 +1,317 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GAPSTUB_H
#define BLE_GAPSTUB_H
namespace ble {
namespace impl {
class Gap {
public:
Gap() {};
Gap(const Gap&) = delete;
Gap& operator=(const Gap&) = delete;
virtual ~Gap() {};
using EventHandler = ::ble::Gap::EventHandler;
using GapShutdownCallback_t = ::ble::Gap::GapShutdownCallback_t;
using GapShutdownCallbackChain_t = ::ble::Gap::GapShutdownCallbackChain_t ;
using PreferredConnectionParams_t = ::ble::Gap::PreferredConnectionParams_t ;
#if BLE_FEATURE_PRIVACY
#if BLE_ROLE_BROADCASTER
static const peripheral_privacy_configuration_t default_peripheral_privacy_configuration;
#endif // BLE_ROLE_BROADCASTER
#if BLE_ROLE_OBSERVER
/**
* Default peripheral privacy configuration.
*/
static const central_privacy_configuration_t default_central_privacy_configuration;
#endif // BLE_ROLE_OBSERVER
#endif // BLE_FEATURE_PRIVACY
public:
virtual void setEventHandler(EventHandler *handler) { };
virtual bool isFeatureSupported(controller_supported_features_t feature) { return true; };
/* advertising */
#if BLE_ROLE_BROADCASTER
virtual uint8_t getMaxAdvertisingSetNumber() { return 1; };
virtual uint16_t getMaxAdvertisingDataLength() { return 23; };
virtual uint16_t getMaxConnectableAdvertisingDataLength() { return 21; };
virtual uint16_t getMaxActiveSetAdvertisingDataLength() { return 21; };
#if BLE_FEATURE_EXTENDED_ADVERTISING
virtual ble_error_t createAdvertisingSet(
advertising_handle_t *handle,
const AdvertisingParameters &parameters
) { return BLE_ERROR_NONE; };
virtual ble_error_t destroyAdvertisingSet(advertising_handle_t handle) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_EXTENDED_ADVERTISING
virtual ble_error_t setAdvertisingParameters(
advertising_handle_t handle,
const AdvertisingParameters &params
) { return BLE_ERROR_NONE; };
virtual ble_error_t setAdvertisingPayload(
advertising_handle_t handle,
mbed::Span<const uint8_t> payload
) { return BLE_ERROR_NONE; };
virtual ble_error_t setAdvertisingScanResponse(
advertising_handle_t handle,
mbed::Span<const uint8_t> response
) { return BLE_ERROR_NONE; };
virtual ble_error_t startAdvertising(
advertising_handle_t handle,
adv_duration_t maxDuration = adv_duration_t::forever(),
uint8_t maxEvents = 0
) { return BLE_ERROR_NONE; };
virtual ble_error_t stopAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; };
virtual bool isAdvertisingActive(advertising_handle_t handle) { return true; };
#endif // BLE_ROLE_BROADCASTER
#if BLE_ROLE_BROADCASTER
#if BLE_FEATURE_PERIODIC_ADVERTISING
virtual ble_error_t setPeriodicAdvertisingParameters(
advertising_handle_t handle,
periodic_interval_t periodicAdvertisingIntervalMin,
periodic_interval_t periodicAdvertisingIntervalMax,
bool advertiseTxPower = true
) { return BLE_ERROR_NONE; };
virtual ble_error_t setPeriodicAdvertisingPayload(
advertising_handle_t handle,
mbed::Span<const uint8_t> payload
) { return BLE_ERROR_NONE; };
virtual ble_error_t startPeriodicAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; };
virtual ble_error_t stopPeriodicAdvertising(advertising_handle_t handle) { return BLE_ERROR_NONE; };
virtual bool isPeriodicAdvertisingActive(advertising_handle_t handle) { return true; };
#endif // BLE_ROLE_BROADCASTER
#endif // BLE_FEATURE_PERIODIC_ADVERTISING
/* scanning */
#if BLE_ROLE_OBSERVER
virtual ble_error_t setScanParameters(const ScanParameters &params) { return BLE_ERROR_NONE; };
virtual ble_error_t startScan(
scan_duration_t duration = scan_duration_t::forever(),
duplicates_filter_t filtering = duplicates_filter_t::DISABLE,
scan_period_t period = scan_period_t(0)
) { return BLE_ERROR_NONE; };
virtual ble_error_t initiate_scan() { return BLE_ERROR_NONE; };
virtual ble_error_t stopScan() { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_OBSERVER
#if BLE_ROLE_OBSERVER
#if BLE_FEATURE_PERIODIC_ADVERTISING
virtual ble_error_t createSync(
peer_address_type_t peerAddressType,
const address_t &peerAddress,
uint8_t sid,
slave_latency_t maxPacketSkip,
sync_timeout_t timeout
) { return BLE_ERROR_NONE; };
virtual ble_error_t createSync(
slave_latency_t maxPacketSkip,
sync_timeout_t timeout
) { return BLE_ERROR_NONE; };
virtual ble_error_t cancelCreateSync() { return BLE_ERROR_NONE; };
virtual ble_error_t terminateSync(periodic_sync_handle_t handle) { return BLE_ERROR_NONE; };
virtual ble_error_t addDeviceToPeriodicAdvertiserList(
peer_address_type_t peerAddressType,
const address_t &peerAddress,
advertising_sid_t sid
) { return BLE_ERROR_NONE; };
virtual ble_error_t removeDeviceFromPeriodicAdvertiserList(
peer_address_type_t peerAddressType,
const address_t &peerAddress,
advertising_sid_t sid
) { return BLE_ERROR_NONE; };
virtual ble_error_t clearPeriodicAdvertiserList() { return BLE_ERROR_NONE; };
uint8_t getMaxPeriodicAdvertiserListSize() { return 1; };
#endif // BLE_ROLE_OBSERVER
#endif // BLE_FEATURE_PERIODIC_ADVERTISING
#if BLE_ROLE_CENTRAL
virtual ble_error_t connect(
peer_address_type_t peerAddressType,
const address_t &peerAddress,
const ConnectionParameters &connectionParams
) { return BLE_ERROR_NONE; };
virtual ble_error_t cancelConnect() { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_CENTRAL
#if BLE_FEATURE_CONNECTABLE
virtual ble_error_t updateConnectionParameters(
connection_handle_t connectionHandle,
conn_interval_t minConnectionInterval,
conn_interval_t maxConnectionInterval,
slave_latency_t slaveLatency,
supervision_timeout_t supervision_timeout,
conn_event_length_t minConnectionEventLength = conn_event_length_t(0),
conn_event_length_t maxConnectionEventLength = conn_event_length_t(0)
) { return BLE_ERROR_NONE; };
virtual ble_error_t manageConnectionParametersUpdateRequest(
bool userManageConnectionUpdateRequest
) { return BLE_ERROR_NONE; };
virtual ble_error_t acceptConnectionParametersUpdate(
connection_handle_t connectionHandle,
conn_interval_t minConnectionInterval,
conn_interval_t maxConnectionInterval,
slave_latency_t slaveLatency,
supervision_timeout_t supervision_timeout,
conn_event_length_t minConnectionEventLength = conn_event_length_t(0),
conn_event_length_t maxConnectionEventLength = conn_event_length_t(0)
) { return BLE_ERROR_NONE; };
virtual ble_error_t rejectConnectionParametersUpdate(
connection_handle_t connectionHandle
) { return BLE_ERROR_NONE; };
virtual ble_error_t disconnect(
connection_handle_t connectionHandle,
local_disconnection_reason_t reason
) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_CONNECTABLE
#if BLE_FEATURE_PHY_MANAGEMENT
virtual ble_error_t readPhy(connection_handle_t connection) { return BLE_ERROR_NONE; };
virtual ble_error_t setPreferredPhys(
const phy_set_t *txPhys,
const phy_set_t *rxPhys
) { return BLE_ERROR_NONE; };
virtual ble_error_t setPhy(
connection_handle_t connection,
const phy_set_t *txPhys,
const phy_set_t *rxPhys,
coded_symbol_per_bit_t codedSymbol
) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_PHY_MANAGEMENT
#if BLE_FEATURE_PRIVACY
virtual ble_error_t enablePrivacy(bool enable) { return BLE_ERROR_NONE; };
#if BLE_ROLE_BROADCASTER
virtual ble_error_t setPeripheralPrivacyConfiguration(
const peripheral_privacy_configuration_t *configuration
) { return BLE_ERROR_NONE; };
virtual ble_error_t getPeripheralPrivacyConfiguration(
peripheral_privacy_configuration_t *configuration
) { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_BROADCASTER
#if BLE_ROLE_OBSERVER
virtual ble_error_t setCentralPrivacyConfiguration(
const central_privacy_configuration_t *configuration
) { return BLE_ERROR_NONE; };
virtual ble_error_t getCentralPrivacyConfiguration(
central_privacy_configuration_t *configuration
) { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_OBSERVER
#endif // BLE_FEATURE_PRIVACY
#if BLE_FEATURE_WHITELIST
virtual uint8_t getMaxWhitelistSize() const { return 1; };
virtual ble_error_t getWhitelist(whitelist_t &whitelist) const { return BLE_ERROR_NONE; };
virtual ble_error_t setWhitelist(const whitelist_t &whitelist) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_WHITELIST
virtual ble_error_t getAddress(
own_address_type_t &typeP,
address_t &address
) { return BLE_ERROR_NONE; };
static ble_error_t getRandomAddressType(
ble::address_t address,
ble::random_address_type_t *addressType
) { return BLE_ERROR_NONE;};
virtual ble_error_t reset() { return BLE_ERROR_NONE; };
virtual void onShutdown(const GapShutdownCallback_t &callback) { };
virtual GapShutdownCallbackChain_t &onShutdown() { static GapShutdownCallbackChain_t chain; return chain; };
/*
* API reserved for the controller driver to set the random static address.
* Setting a new random static address while the controller is operating is
* forbidden by the Bluetooth specification.
*/
virtual ble_error_t setRandomStaticAddress(const ble::address_t &address) { return BLE_ERROR_NONE; };
virtual ble::address_t getRandomStaticAddress() { return ble::address_t(); };
};
}
}
#endif //BLE_GAPSTUB_H

View File

@ -0,0 +1,133 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 BLE_GATTCLIENTSTUB_H
#define BLE_GATTCLIENTSTUB_H
#include "events/EventQueue.h"
namespace ble {
namespace impl {
class GattClient {
public:
using EventHandler = ble::GattClient::EventHandler;
using WriteOp_t = ble::GattClient::WriteOp_t;
using HVXCallback_t = ble::GattClient::HVXCallback_t ;
using GattClientShutdownCallback_t = ble::GattClient::GattClientShutdownCallback_t ;
using GattClientShutdownCallbackChain_t = ble::GattClient::GattClientShutdownCallbackChain_t ;
using HVXCallbackChain_t = ble::GattClient::HVXCallbackChain_t ;
using ReadCallbackChain_t = ble::GattClient::ReadCallbackChain_t ;
using WriteCallbackChain_t = ble::GattClient::WriteCallbackChain_t ;
GattClient() {};
GattClient(const GattClient&) = delete;
GattClient& operator=(const GattClient&) = delete;
virtual ~GattClient() {};
virtual void setEventHandler(EventHandler *handler) { };
virtual ble_error_t launchServiceDiscovery(
ble::connection_handle_t connectionHandle,
ServiceDiscovery::ServiceCallback_t sc = nullptr,
ServiceDiscovery::CharacteristicCallback_t cc = nullptr,
const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN),
const UUID &matchingCharacteristicUUIDIn = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)
) { return BLE_ERROR_NONE; };
virtual ble_error_t discoverServices(
ble::connection_handle_t connectionHandle,
ServiceDiscovery::ServiceCallback_t callback,
const UUID &matchingServiceUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)
) { return BLE_ERROR_NONE; };
virtual ble_error_t discoverServices(
ble::connection_handle_t connectionHandle,
ServiceDiscovery::ServiceCallback_t callback,
GattAttribute::Handle_t startHandle,
GattAttribute::Handle_t endHandle
) { return BLE_ERROR_NONE; };
virtual bool isServiceDiscoveryActive(void) const { return true; };
virtual void terminateServiceDiscovery(void) { };
virtual ble_error_t read(
ble::connection_handle_t connHandle,
GattAttribute::Handle_t attributeHandle,
uint16_t offset
) const { return BLE_ERROR_NONE; };
virtual ble_error_t write(
GattClient::WriteOp_t cmd,
ble::connection_handle_t connHandle,
GattAttribute::Handle_t attributeHandle,
size_t length,
const uint8_t *value
) const { return BLE_ERROR_NONE; };
/* Event callback handlers. */
virtual void onDataRead(ReadCallback_t callback) { };
virtual ReadCallbackChain_t &onDataRead() { static ReadCallbackChain_t chain; return chain; };
virtual void onDataWritten(WriteCallback_t callback) { };
virtual WriteCallbackChain_t &onDataWritten() { static WriteCallbackChain_t chain; return chain; };
virtual void onServiceDiscoveryTermination(
ServiceDiscovery::TerminationCallback_t callback
) { };
virtual ble_error_t discoverCharacteristicDescriptors(
const DiscoveredCharacteristic &characteristic,
const CharacteristicDescriptorDiscovery::DiscoveryCallback_t &discoveryCallback,
const CharacteristicDescriptorDiscovery::TerminationCallback_t &terminationCallback
) { return BLE_ERROR_NONE; };
virtual bool isCharacteristicDescriptorDiscoveryActive(
const DiscoveredCharacteristic &characteristic
) const { return true; };
virtual void terminateCharacteristicDescriptorDiscovery(
const DiscoveredCharacteristic &characteristic
) { };
virtual ble_error_t negotiateAttMtu(ble::connection_handle_t connection) { return BLE_ERROR_NONE; };
virtual void onHVX(HVXCallback_t callback) { };
virtual void onShutdown(const GattClientShutdownCallback_t &callback) { };
virtual GattClientShutdownCallbackChain_t &onShutdown() { static GattClientShutdownCallbackChain_t chain; return chain; };
virtual HVXCallbackChain_t &onHVX() { static HVXCallbackChain_t chain; return chain; };
virtual ble_error_t reset(void) { return BLE_ERROR_NONE; };
virtual void processReadResponse(const GattReadCallbackParams *params) { };
virtual void processWriteResponse(const GattWriteCallbackParams *params) { };
virtual void processHVXEvent(const GattHVXCallbackParams *params) { };
};
}
}
#endif //BLE_GATTCLIENTSTUB_H

View File

@ -0,0 +1,186 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 SECURITYMANAGERSTUB_H
#define SECURITYMANAGERSTUB_H
namespace ble {
namespace impl {
class SecurityManager {
public:
SecurityManager() {};
SecurityManager(const SecurityManager&) = delete;
SecurityManager& operator=(const SecurityManager&) = delete;
virtual ~SecurityManager() {};
using SecurityIOCapabilities_t = ble::SecurityManager::SecurityIOCapabilities_t;
using SecurityMode_t = ble::SecurityManager::SecurityMode_t;
using SecurityManagerShutdownCallback_t = ble::SecurityManager::SecurityManagerShutdownCallback_t;
using SecurityManagerShutdownCallbackChain_t = ble::SecurityManager::SecurityManagerShutdownCallbackChain_t;
using EventHandler = ble::SecurityManager::EventHandler;
using Passkey_t = ble::SecurityManager::Passkey_t ;
static auto constexpr IO_CAPS_NONE = ble::SecurityManager::IO_CAPS_NONE;
virtual ble_error_t init(
bool enableBonding = true,
bool requireMITM = true,
SecurityIOCapabilities_t iocaps = IO_CAPS_NONE,
const Passkey_t passkey = nullptr,
bool signing = true,
const char *dbFilepath = nullptr
) { return BLE_ERROR_NONE; };
virtual ble_error_t setDatabaseFilepath(const char *dbFilepath = nullptr) { return BLE_ERROR_NONE; };
virtual ble_error_t reset() { return BLE_ERROR_NONE; };
virtual ble_error_t preserveBondingStateOnReset(bool enable) { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// List management
//
virtual ble_error_t purgeAllBondingState() { return BLE_ERROR_NONE; };
virtual ble_error_t generateWhitelistFromBondTable(::ble::whitelist_t *whitelist) const { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// Pairing
//
#if BLE_ROLE_CENTRAL
virtual ble_error_t requestPairing(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_CENTRAL
#if BLE_ROLE_PERIPHERAL
virtual ble_error_t acceptPairingRequest(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; };
#endif // BLE_ROLE_PERIPHERAL
virtual ble_error_t cancelPairingRequest(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; };
virtual ble_error_t setPairingRequestAuthorisation(bool required = true) { return BLE_ERROR_NONE; };
virtual ble_error_t getPeerIdentity(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// Feature support
//
#if BLE_FEATURE_SECURE_CONNECTIONS
virtual ble_error_t allowLegacyPairing(bool allow = true) { return BLE_ERROR_NONE; };
virtual ble_error_t getSecureConnectionsSupport(bool *enabled) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_SECURE_CONNECTIONS
////////////////////////////////////////////////////////////////////////////
// Security settings
//
virtual ble_error_t setIoCapability(SecurityIOCapabilities_t iocaps) { return BLE_ERROR_NONE; };
virtual ble_error_t setDisplayPasskey(const Passkey_t passkey) { return BLE_ERROR_NONE; };
virtual ble_error_t setLinkSecurity(ble::connection_handle_t connectionHandle, SecurityMode_t securityMode) { return BLE_ERROR_NONE; };
virtual ble_error_t setKeypressNotification(bool enabled = true) { return BLE_ERROR_NONE; };
#if BLE_FEATURE_SIGNING
virtual ble_error_t enableSigning(ble::connection_handle_t connectionHandle, bool enabled = true) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_SIGNING
virtual ble_error_t setHintFutureRoleReversal(bool enable = true) { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// Encryption
//
virtual ble_error_t getLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t *encryption) { return BLE_ERROR_NONE; };
virtual ble_error_t setLinkEncryption(ble::connection_handle_t connectionHandle, ble::link_encryption_t encryption) { return BLE_ERROR_NONE; };
virtual ble_error_t setEncryptionKeyRequirements(uint8_t minimumByteSize, uint8_t maximumByteSize) { return BLE_ERROR_NONE; };
virtual ble_error_t getEncryptionKeySize(
connection_handle_t connectionHandle,
uint8_t *size
) { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// Authentication
//
virtual ble_error_t requestAuthentication(ble::connection_handle_t connectionHandle) { return BLE_ERROR_NONE; };
////////////////////////////////////////////////////////////////////////////
// MITM
//
virtual ble_error_t generateOOB(const ble::address_t *address) { return BLE_ERROR_NONE; };
virtual ble_error_t setOOBDataUsage(ble::connection_handle_t connectionHandle, bool useOOB, bool OOBProvidesMITM = true) { return BLE_ERROR_NONE; };
virtual ble_error_t passkeyEntered(ble::connection_handle_t connectionHandle, Passkey_t passkey) { return BLE_ERROR_NONE; };
virtual ble_error_t legacyPairingOobReceived(const ble::address_t *address, const ble::oob_tk_t *tk) { return BLE_ERROR_NONE; };
#if BLE_FEATURE_SECURE_CONNECTIONS
virtual ble_error_t confirmationEntered(ble::connection_handle_t connectionHandle, bool confirmation) { return BLE_ERROR_NONE; };
virtual ble_error_t sendKeypressNotification(ble::connection_handle_t connectionHandle, ble::Keypress_t keypress) { return BLE_ERROR_NONE; };
virtual ble_error_t oobReceived(
const ble::address_t *address,
const ble::oob_lesc_value_t *random,
const ble::oob_confirm_t *confirm
) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_SECURE_CONNECTIONS
////////////////////////////////////////////////////////////////////////////
// Keys
//
#if BLE_FEATURE_SIGNING
virtual ble_error_t getSigningKey(ble::connection_handle_t connectionHandle, bool authenticated) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_SIGNING
////////////////////////////////////////////////////////////////////////////
// Privacy
//
#if BLE_FEATURE_PRIVACY
virtual ble_error_t setPrivateAddressTimeout(
uint16_t timeout_in_seconds
) { return BLE_ERROR_NONE; };
#endif // BLE_FEATURE_PRIVACY
/* Event callback handlers. */
public:
virtual void onShutdown(const SecurityManagerShutdownCallback_t &callback) { };
template<typename T>
void onShutdown(T *objPtr, void (T::*memberPtr)(const SecurityManager *)) { };
virtual SecurityManagerShutdownCallbackChain_t &onShutdown() { static SecurityManagerShutdownCallbackChain_t chain; return chain; };
virtual void setSecurityManagerEventHandler(EventHandler *handler) { };
};
}
}
#endif //SECURITYMANAGERSTUB_H

View File

@ -0,0 +1,20 @@
# Copyright (c) 2020 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-fakes-event-queue)
target_sources(mbed-fakes-event-queue
PRIVATE
events/EventQueue.cpp
)
target_include_directories(mbed-fakes-event-queue
PUBLIC
.
)
target_link_libraries(mbed-fakes-event-queue
PRIVATE
mbed-headers
gcov
)

View File

@ -0,0 +1,120 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "EventQueue.h"
namespace events {
handle_t EventQueue::call_handler(function_t handler)
{
return call_handler_in(0, handler);
}
handle_t EventQueue::call_handler_in(tick_t ms, function_t handler)
{
_handler_id++;
_handlers.push_back(
internal_event{
std::unique_ptr<function_t>(new function_t(handler)),
_now + ms,
_handler_id
}
);
return _handler_id;
}
bool EventQueue::cancel_handler(handle_t handle)
{
if (!handle) {
return false;
}
auto found = std::remove_if(
_handlers.begin(),
_handlers.end(),
[handle](internal_event& element) -> bool {
return (handle == element.handle);
}
);
if (found != _handlers.end()) {
_handlers.erase(
found,
_handlers.end()
);
return true;
}
return false;
}
void EventQueue::process_events(tick_t duration_ms)
{
// execute all events during the duration
for (uint64_t i = 0; i < duration_ms; ++i) {
process_events();
_now++;
}
// last round to execute immediate events
process_events();
}
void EventQueue::process_events() {
while (true) {
if (_handlers.empty()) {
return;
}
/* to guarantee order we only dispatch one tick at a time*/
auto smallest = std::min_element(
_handlers.begin(),
_handlers.end(),
[](internal_event& element, internal_event& smallest){
return (element.tick < smallest.tick);
}
);
tick_t earliest_tick = smallest->tick;
/* stop if all elements happen later */
if (earliest_tick > _now) {
return;
}
/* dispatch all handlers that happen at this time */
auto found = std::remove_if(
_handlers.begin(),
_handlers.end(),
[earliest_tick](internal_event& element) -> bool {
if (earliest_tick >= element.tick) {
(*(element.handler))();
return true;
} else {
return false;
}
}
);
if (found != _handlers.end()) {
_handlers.erase(found, _handlers.end());
}
}
}
}

View File

@ -0,0 +1,137 @@
/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 EVENTQUEUE_FAKE_H
#define EVENTQUEUE_FAKE_H
#include <map>
#include <memory>
#include <functional>
#include <algorithm>
#include <vector>
#include "events/EventQueue.h"
#include <chrono>
#include <mstd_tuple>
namespace events {
typedef int handle_t;
typedef std::function<void()> function_t;
typedef unsigned tick_t;
class EventQueue {
using duration = std::chrono::duration<int, std::milli>;
public:
EventQueue(unsigned size = 0, unsigned char *buffer = NULL) { delete buffer; };
~EventQueue() { };
/** This will advance time by given amount of milliseconds and then dispatch all events that were set to happen in that time.
*
* @param ms number of miliseconds to advance time
*/
void dispatch(int milliseconds = -1) {
if (milliseconds > 0) {
process_events(milliseconds);
} else {
_now = (tick_t)-1;
process_events();
_now = 0;
}
};
tick_t tick() {
return _now;
};
bool cancel(handle_t id) {
return cancel_handler(id);
};
/** Get number of events in queue.
*
* @return Number of events waiting in the queue.
*/
size_t size() const {
return _handlers.size();
}
template<typename F, typename ... ArgTs>
handle_t call(F f, ArgTs... args) {
return call_handler(
[f, args = mstd::make_tuple(args...)]() {
mstd::apply(f, args);
}
);
}
template<typename F, typename ... ArgTs>
handle_t call_in(duration ms, F f, ArgTs... args) {
return call_handler_in(
ms.count(),
[f, args = mstd::make_tuple(args...)]() {
mstd::apply(f, args);
}
);
}
template <typename T, typename R, typename... ArgTs>
int call(T *obj, R(T::*method)(ArgTs...), ArgTs... args) {
return call_handler(
[obj, method, args = mstd::make_tuple(args...)]() {
mstd::apply(method, obj, args);
}
);
}
template <typename T, typename R, typename... ArgTs>
int call_in(duration ms, T *obj, R(T::*method)(ArgTs...), ArgTs... args) {
return call_handler_in(
ms.count(),
[obj, method, args = mstd::make_tuple(args...)]() {
mstd::apply(method, obj, args);
}
);
}
private:
handle_t call_handler(function_t handler);
handle_t call_handler_in(tick_t ms, function_t handler);
bool cancel_handler(handle_t handle);
void process_events(tick_t duration_ms);
void process_events();
private:
struct internal_event {
std::unique_ptr<function_t> handler;
tick_t tick;
handle_t handle;
};
std::vector<internal_event> _handlers;
tick_t _now = 0;
handle_t _handler_id = 0;
};
}
#endif //EVENTQUEUE_FAKE_H

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
"""
Copyright (c) 2018, Arm Limited
Copyright (c) 2018-2021, Arm Limited
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
@ -71,9 +71,8 @@ def _mbed_unittest_test(options, cwd, pwd):
clean=options.clean)
if options.compile_only:
# Create makefiles
src_path = os.path.relpath(pwd, options.build)
tool.create_makefiles(path_to_src=src_path,
# Create makefiles
tool.create_makefiles(path_to_src=cwd,
generator=options.cmake_generator,
coverage_output_type=options.coverage,
debug=options.debug_build,

View File

@ -0,0 +1,140 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-headers INTERFACE)
add_library(mbed-headers INTERFACE)
add_library(mbed-headers-base INTERFACE)
add_library(mbed-headers-platform INTERFACE)
add_library(mbed-headers-connectivity INTERFACE)
add_library(mbed-headers-storage INTERFACE)
add_library(mbed-headers-hal INTERFACE)
add_library(mbed-headers-events INTERFACE)
add_library(mbed-headers-rtos INTERFACE)
target_link_libraries(mbed-headers
INTERFACE
mbed-headers-base
mbed-headers-platform
mbed-headers-connectivity
mbed-headers-storage
mbed-headers-drivers
mbed-headers-hal
mbed-headers-events
mbed-headers-rtos
)
target_include_directories(mbed-headers-platform
INTERFACE
${mbed-os_SOURCE_DIR}/platform/include
${mbed-os_SOURCE_DIR}/platform/include/platform
${mbed-os_SOURCE_DIR}/platform/randlib/include/mbed-client-randlib/
${mbed-os_SOURCE_DIR}/platform/randlib/include/
${mbed-os_SOURCE_DIR}/platform/mbed-trace/include
)
target_include_directories(mbed-headers-base
INTERFACE
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/platform
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/platform/cxxsupport
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/drivers
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/rtos/include
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/rtos
${mbed-os_SOURCE_DIR}/UNITTESTS/target_h/sys
)
target_include_directories(mbed-headers-storage
INTERFACE
${mbed-os_SOURCE_DIR}/storage/filesystem/fat/include
${mbed-os_SOURCE_DIR}/storage/filesystem/fat/ChaN
${mbed-os_SOURCE_DIR}/storage/filesystem/littlefs
${mbed-os_SOURCE_DIR}/storage/filesystem/littlefs/include
${mbed-os_SOURCE_DIR}/storage/filesystem/littlefsv2/littlefs
${mbed-os_SOURCE_DIR}/storage/filesystem/littlefsv2/littlefs/bd
${mbed-os_SOURCE_DIR}/storage/filesystem/littlefs/littlefs
${mbed-os_SOURCE_DIR}/storage/blockdevice/include
${mbed-os_SOURCE_DIR}/storage/filesystem/include
${mbed-os_SOURCE_DIR}/storage/kvstore/include
${mbed-os_SOURCE_DIR}/storage/kvstore/kv_config
${mbed-os_SOURCE_DIR}/storage/kvstore/kv_config/include
${mbed-os_SOURCE_DIR}/storage/kvstore/tdbstore/include
${mbed-os_SOURCE_DIR}/storage/kvstore/filesystemstore/include
${mbed-os_SOURCE_DIR}/storage/kvstore/kvstore_global_api/include
${mbed-os_SOURCE_DIR}/storage/blockdevice/include/blockdevice
)
target_include_directories(mbed-headers-connectivity
INTERFACE
${mbed-os_SOURCE_DIR}/connectivity/libraries/nanostack-libservice
${mbed-os_SOURCE_DIR}/connectivity/libraries/nanostack-libservice/mbed-client-libservice
${mbed-os_SOURCE_DIR}/connectivity/netsocket/include
${mbed-os_SOURCE_DIR}/connectivity/cellular/include/cellular/framework/API
${mbed-os_SOURCE_DIR}/connectivity/cellular/include/cellular/framework/AT
${mbed-os_SOURCE_DIR}/connectivity/cellular/include/cellular/framework/device
${mbed-os_SOURCE_DIR}/connectivity/cellular/include/cellular/framework
${mbed-os_SOURCE_DIR}/connectivity/cellular/include/cellular/framework/common
${mbed-os_SOURCE_DIR}/connectivity
${mbed-os_SOURCE_DIR}/connectivity/lorawan/include/lorawan
${mbed-os_SOURCE_DIR}/connectivity/lorawan/lorastack
${mbed-os_SOURCE_DIR}/connectivity/lorawan/lorastack/mac
${mbed-os_SOURCE_DIR}/connectivity/lorawan/lorastack/phy
${mbed-os_SOURCE_DIR}/connectivity/lorawan
${mbed-os_SOURCE_DIR}/connectivity/lorawan/system
${mbed-os_SOURCE_DIR}/connectivity/mbedtls
${mbed-os_SOURCE_DIR}/connectivity/mbedtls/include
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/include
${mbed-os_SOURCE_DIR}/connectivity/FEATURE_BLE/include/ble
)
target_include_directories(mbed-headers-events
INTERFACE
${mbed-os_SOURCE_DIR}/events/tests/UNITTESTS/target_h
${mbed-os_SOURCE_DIR}/events/tests/UNITTESTS/target_h/equeue
${mbed-os_SOURCE_DIR}/events/include
${mbed-os_SOURCE_DIR}/events/include/events
${mbed-os_SOURCE_DIR}/events/include/events/internal
)
target_include_directories(mbed-headers-hal
INTERFACE
${mbed-os_SOURCE_DIR}/hal
${mbed-os_SOURCE_DIR}/hal/include
)
target_include_directories(mbed-headers-rtos
INTERFACE
${mbed-os_SOURCE_DIR}/rtos/include
${mbed-os_SOURCE_DIR}/rtos/include/rtos
)
target_include_directories(mbed-headers
INTERFACE
${mbed-os_SOURCE_DIR}/features
${mbed-os_SOURCE_DIR}/features/frameworks
)
target_include_directories(mbed-stubs-headers
INTERFACE
.
${mbed-os_SOURCE_DIR}/connectivity/nanostack/coap-service/test/coap-service/unittest/stub
)
add_subdirectory(connectivity)
add_subdirectory(events)
add_subdirectory(hal)
add_subdirectory(platform)
add_subdirectory(rtos)
add_subdirectory(storage)
add_library(mbed-stubs INTERFACE)
target_link_libraries(mbed-stubs
INTERFACE
mbed-stubs-connectivity
mbed-stubs-drivers
mbed-stubs-events
mbed-stubs-hal
mbed-stubs-platform
mbed-stubs-rtos
mbed-stubs-storage
)

View File

@ -67,6 +67,7 @@ public:
virtual int close()
{
return 0;
}
virtual short poll(short events) const

View File

@ -56,6 +56,7 @@ ATHandler *AT_CellularDevice::get_at_handler()
CellularContext *create_context(const char *apn)
{
return nullptr;
}
void delete_context(CellularContext *context)

View File

@ -0,0 +1,64 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-connectivity)
target_compile_definitions(mbed-stubs-connectivity
PRIVATE
DEVICE_SERIAL=1
DEVICE_INTERRUPTIN=1
MBED_CONF_CELLULAR_USE_SMS=1
MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN=NULL
MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE=115200
MBED_CONF_LORA_OVER_THE_AIR_ACTIVATION=true
MBED_CONF_LORA_AUTOMATIC_UPLINK_MESSAGE=true
MBED_CONF_LORA_TX_MAX_SIZE=255
MBED_CONF_CELLULAR_AT_HANDLER_BUFFER_SIZE=32
MDMTXD=NC
MDMRXD=NC
)
target_sources(mbed-stubs-connectivity
PRIVATE
aes_stub.c
AT_CellularContext_stub.cpp
AT_CellularDevice_stub.cpp
AT_CellularInformation_stub.cpp
AT_CellularNetwork_stub.cpp
AT_CellularSMS_stub.cpp
AT_CellularStack_stub.cpp
AT_ControlPlane_netif_stub.cpp
ATHandler_stub.cpp
CellularContext_stub.cpp
CellularDevice_stub.cpp
CellularInterface_stub.cpp
CellularStateMachine_stub.cpp
CellularUtil_stub.cpp
cipher_stub.c
cmac_stub.c
ip4tos_stub.c
LoRaMacChannelPlan_stub.cpp
LoRaMacCommand_stub.cpp
LoRaMacCrypto_stub.cpp
LoRaMac_stub.cpp
LoRaPHYEU868_stub.cpp
LoRaPHY_stub.cpp
LoRaWANStack_stub.cpp
LoRaWANTimer_stub.cpp
MeshInterface_stub.cpp
NetworkInterfaceDefaults_stub.cpp
NetworkInterface_stub.cpp
NetworkStack_stub.cpp
nsapi_dns_stub.cpp
SocketAddress_stub.cpp
SocketStats_Stub.cpp
stoip4_stub.c
${mbed-os_SOURCE_DIR}/connectivity/nanostack/coap-service/test/coap-service/unittest/stub/mbedtls_stub.c
)
target_link_libraries(mbed-stubs-connectivity
PRIVATE
mbed-headers
mbed-stubs-headers
gtest
)

View File

@ -94,6 +94,7 @@ void LoRaMac::post_process_mlme_ind()
lorawan_time_t LoRaMac::get_current_time(void)
{
return 0;
}
rx_slot_t LoRaMac::get_current_slot(void)

View File

@ -0,0 +1,19 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-events)
target_sources(mbed-stubs-events
PRIVATE
equeue_stub.c
${mbed-os_SOURCE_DIR}/events/tests/UNITTESTS/stubs/EqueuePosix_stub.c
EventFlags_stub.cpp
EventQueue_stub.cpp
mbed_shared_queues_stub.cpp
)
target_link_libraries(mbed-stubs-events
PRIVATE
mbed-headers
mbed-stubs-headers
)

View File

@ -105,7 +105,7 @@ void equeue_background(equeue_t *queue,
int equeue_chain(equeue_t *queue, equeue_t *target)
{
return 0;
}
int equeue_call_in(equeue_t *q, int ms, void (*cb)(void *), void *data)

View File

@ -0,0 +1,29 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-hal)
target_compile_definitions(mbed-stubs-hal
PRIVATE
DEVICE_PWMOUT
DEVICE_WATCHDOG
MBED_WDOG_ASSERT=1
)
target_sources(mbed-stubs-hal
PRIVATE
pwmout_api_stub.c
us_ticker_stub.cpp
watchdog_api_stub.c
)
target_link_options(mbed-stubs-hal
PRIVATE
--coverage
)
target_link_libraries(mbed-stubs-hal
PRIVATE
mbed-headers
mbed-stubs-headers
)

View File

@ -0,0 +1,30 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-platform)
target_sources(mbed-stubs-platform
PRIVATE
mbed_critical_stub.c
mbed_atomic_stub.c
mbed_error.c
mbed_poll_stub.cpp
mbed_assert_stub.cpp
mbed_wait_api_stub.cpp
mbed_retarget_stub.cpp
FileHandle_stub.cpp
nvic_wrapper_stub.c
randLIB_stub.c
randLIB_stub.cpp
)
target_link_options(mbed-stubs-platform
PRIVATE
--coverage
)
target_link_libraries(mbed-stubs-platform
PRIVATE
mbed-headers
mbed-stubs-headers
)

View File

@ -0,0 +1,22 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-rtos)
target_sources(mbed-stubs-rtos
PRIVATE
ConditionVariable_stub.cpp
Kernel_stub.cpp
mbed_rtos_rtx_stub.c
Mutex_stub.cpp
rtx_mutex_stub.c
Semaphore_stub.cpp
ThisThread_stub.cpp
Thread_stub.cpp
)
target_link_libraries(mbed-stubs-rtos
PRIVATE
mbed-headers
mbed-stubs-headers
)

View File

@ -15,6 +15,6 @@
* limitations under the License.
*/
#include "cmsis_os2.h"
#include "mbed_rtos_types.h"
osMutexId_t singleton_mutex_id;

View File

@ -15,7 +15,7 @@
* limitations under the License.
*/
#include "cmsis_os2.h"
#include "mbed_rtos_types.h"
osStatus_t osMutexAcquire(osMutexId_t mutex_id, uint32_t timeout)
{

View File

@ -0,0 +1,26 @@
# Copyright (c) 2021 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
add_library(mbed-stubs-storage)
target_sources(mbed-stubs-storage
PRIVATE
BufferedBlockDevice_stub.cpp
ChainingBlockDevice_stub.cpp
EmulatedSD.cpp
ExhaustibleBlockDevice_stub.cpp
FlashSimBlockDevice_stub.cpp
HeapBlockDevice_stub.cpp
MBRBlockDevice_stub.cpp
ObservingBlockDevice_stub.cpp
ProfilingBlockDevice_stub.cpp
ReadOnlyBlockDevice_stub.cpp
SlicingBlockDevice_stub.cpp
kv_config_stub.cpp
)
target_link_libraries(mbed-stubs-storage
PRIVATE
mbed-headers
mbed-stubs-headers
)

View File

@ -62,6 +62,7 @@ int EmulatedSD::deinit()
{
fclose(_p->fs);
_p->fs = nullptr;
return 0;
}
int EmulatedSD::read(void *buffer, bd_addr_t addr, bd_size_t size)

Some files were not shown because too many files have changed in this diff Show More