From bbab3074ed65f454d94c2edd2ebad0ff6399fbc6 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Fri, 30 Jun 2017 11:48:26 -0700 Subject: [PATCH] [instance] single OpenThread instance optimizations (#1926) This commit new configuration option `enable-multiple-instances` and its corresponding option `OPENTHREAD_ENABLE_MULTIPLE_INSTANCES`. When enabled OpenThread supports handling of multiple instances. By default this is disabled. This commit also adds two optimizations for single instance case to simplify the code and also help reduce memory/RAM usage: (1) OpenThread objects/classes typically keep a reference to a higher level object (e.g., many classes keep track of owning `ThreadNetif`) to be able to access other objects/methods within OpenThread class hierarchy. In single instance mode, the reference member variables are removed and instead global functions are used to access the singleton objects from one class to the other. To implement this, a group of `Locator` classes are defined (e.g., `ThreadNetifLocator`, etc.) which are then used as base class of other OpenThread classes. (2) OpenThread objects which provide a callback/handler (e.g., `Timer`, `Tasklet`, etc.) have `void *mContext` member variable which is used to keep track of the owner of the object. In single instance mode the `mConext` member variables are removed since the owner is expected to be a singleton and can be uniquely determined from the callback function. To implement this, two changes are made: First the handler methods are modified to provide a reference to the object (e.g., `Timer` handler will provide a `Timer &aTimer` as a parameter of its handler callback). Second, a new base class `Context` is introduced which hides the implementation providing an arbitrary context information. A new static method `GetOwner(aContext)` is added to classes which own a callback providing objects. This method help convert a `Context` to the reference of the owner class object. --- configure.ac | 32 ++ etc/visual-studio/UnitTests.vcxproj | 1 - etc/visual-studio/libopenthread-cli.vcxproj | 3 +- .../libopenthread-ncp-spi.vcxproj | 3 +- .../libopenthread-ncp-uart.vcxproj | 3 +- etc/visual-studio/libopenthread.vcxproj | 4 +- .../libopenthread.vcxproj.filters | 9 + etc/visual-studio/libopenthread_k.vcxproj | 4 +- .../libopenthread_k.vcxproj.filters | 9 + etc/visual-studio/mbedtls.vcxproj | 2 +- etc/visual-studio/mbedtls_k.vcxproj | 3 +- etc/visual-studio/ot-cli.vcxproj | 3 +- etc/visual-studio/ot-ncp-spi.vcxproj | 3 +- etc/visual-studio/ot-ncp-uart.vcxproj | 3 +- etc/visual-studio/otLwf.vcxproj | 1 - examples/apps/cli/main.c | 10 +- examples/apps/ncp/main.c | 10 +- include/openthread-windows-config.h | 4 + include/openthread/instance.h | 21 +- include/openthread/platform/memory.h | 12 +- src/cli/cli.cpp | 15 +- src/cli/cli.hpp | 5 +- src/cli/cli_uart.hpp | 8 + src/core/Makefile.am | 4 + src/core/api/instance_api.cpp | 61 ++- src/core/api/link_raw.hpp | 7 +- src/core/api/link_raw_api.cpp | 25 +- src/core/coap/coap.cpp | 36 +- src/core/coap/coap.hpp | 16 +- src/core/coap/coap_secure.cpp | 47 +- src/core/coap/coap_secure.hpp | 4 +- src/core/common/context.hpp | 102 ++++ src/core/common/locator.cpp | 74 +++ src/core/common/locator.hpp | 341 +++++++++++++ src/core/common/message.cpp | 14 +- src/core/common/message.hpp | 6 +- src/core/common/tasklet.cpp | 16 +- src/core/common/tasklet.hpp | 23 +- src/core/common/timer.hpp | 25 +- src/core/common/trickle_timer.cpp | 19 +- src/core/common/trickle_timer.hpp | 30 +- src/core/mac/mac.cpp | 85 ++-- src/core/mac/mac.hpp | 76 ++- src/core/meshcop/announce_begin_client.cpp | 22 +- src/core/meshcop/announce_begin_client.hpp | 16 +- src/core/meshcop/commissioner.cpp | 135 ++--- src/core/meshcop/commissioner.hpp | 19 +- src/core/meshcop/dataset.cpp | 13 +- src/core/meshcop/dataset.hpp | 4 +- src/core/meshcop/dataset_manager.cpp | 198 +++++--- src/core/meshcop/dataset_manager.hpp | 34 +- src/core/meshcop/dataset_manager_ftd.cpp | 34 +- src/core/meshcop/dtls.cpp | 27 +- src/core/meshcop/dtls.hpp | 17 +- src/core/meshcop/energy_scan_client.cpp | 27 +- src/core/meshcop/energy_scan_client.hpp | 13 +- src/core/meshcop/joiner.cpp | 95 ++-- src/core/meshcop/joiner.hpp | 16 +- src/core/meshcop/joiner_router.cpp | 87 ++-- src/core/meshcop/joiner_router.hpp | 16 +- src/core/meshcop/leader.cpp | 56 ++- src/core/meshcop/leader.hpp | 16 +- src/core/meshcop/panid_query_client.cpp | 27 +- src/core/meshcop/panid_query_client.hpp | 13 +- src/core/net/dhcp6_client.cpp | 36 +- src/core/net/dhcp6_client.hpp | 16 +- src/core/net/dhcp6_server.cpp | 29 +- src/core/net/dhcp6_server.hpp | 5 +- src/core/net/dns_client.cpp | 16 +- src/core/net/dns_client.hpp | 5 +- src/core/net/icmp6.cpp | 21 +- src/core/net/icmp6.hpp | 13 +- src/core/net/ip6.cpp | 15 +- src/core/net/ip6.hpp | 4 +- src/core/net/ip6_mpl.cpp | 30 +- src/core/net/ip6_mpl.hpp | 9 +- src/core/net/ip6_routes.cpp | 6 +- src/core/net/ip6_routes.hpp | 4 +- src/core/net/netif.cpp | 18 +- src/core/net/netif.hpp | 17 +- src/core/net/udp6.cpp | 8 +- src/core/net/udp6.hpp | 5 +- src/core/openthread-instance.h | 5 +- src/core/openthread-single-instance.h | 108 ++++ src/core/thread/address_resolver.cpp | 85 ++-- src/core/thread/address_resolver.hpp | 17 +- src/core/thread/announce_begin_server.cpp | 31 +- src/core/thread/announce_begin_server.hpp | 18 +- src/core/thread/data_poll_manager.cpp | 36 +- src/core/thread/data_poll_manager.hpp | 17 +- src/core/thread/energy_scan_server.cpp | 45 +- src/core/thread/energy_scan_server.hpp | 17 +- src/core/thread/key_manager.cpp | 32 +- src/core/thread/key_manager.hpp | 9 +- src/core/thread/lowpan.cpp | 23 +- src/core/thread/lowpan.hpp | 9 +- src/core/thread/mesh_forwarder.cpp | 296 ++++++----- src/core/thread/mesh_forwarder.hpp | 37 +- src/core/thread/mle.cpp | 469 ++++++++++-------- src/core/thread/mle.hpp | 21 +- src/core/thread/mle_router.cpp | 278 ++++++----- src/core/thread/mle_router_ftd.hpp | 6 +- src/core/thread/network_data.cpp | 17 +- src/core/thread/network_data.hpp | 13 +- src/core/thread/network_data_leader.cpp | 25 +- src/core/thread/network_data_leader_ftd.cpp | 63 ++- src/core/thread/network_data_leader_ftd.hpp | 3 +- src/core/thread/network_data_local.cpp | 30 +- src/core/thread/network_diagnostic.cpp | 87 ++-- src/core/thread/network_diagnostic.hpp | 15 +- src/core/thread/panid_query_server.cpp | 38 +- src/core/thread/panid_query_server.hpp | 17 +- src/core/thread/src_match_controller.cpp | 9 +- src/core/thread/src_match_controller.hpp | 14 +- src/core/thread/thread_netif.cpp | 9 +- src/core/thread/thread_netif.hpp | 20 +- src/core/utils/child_supervision.cpp | 69 ++- src/core/utils/child_supervision.hpp | 14 +- src/core/utils/jam_detector.cpp | 20 +- src/core/utils/jam_detector.hpp | 7 +- src/ncp/ncp_base.cpp | 6 +- src/ncp/ncp_base.hpp | 2 +- src/ncp/ncp_spi.cpp | 5 +- src/ncp/ncp_spi.hpp | 2 +- src/ncp/ncp_uart.cpp | 7 +- src/ncp/ncp_uart.hpp | 2 +- tests/unit/test_aes.cpp | 15 +- tests/unit/test_diag.cpp | 4 +- tests/unit/test_fuzz.cpp | 6 +- tests/unit/test_hmac_sha256.cpp | 15 +- tests/unit/test_link_quality.cpp | 3 +- tests/unit/test_lowpan.cpp | 35 +- tests/unit/test_lowpan.hpp | 3 +- tests/unit/test_mac_frame.cpp | 3 +- tests/unit/test_message.cpp | 17 +- tests/unit/test_message_queue.cpp | 50 +- tests/unit/test_ncp_buffer.cpp | 25 +- tests/unit/test_platform.cpp | 36 +- tests/unit/test_platform.h | 4 + tests/unit/test_priority_queue.cpp | 42 +- tests/unit/test_timer.cpp | 120 +++-- tests/unit/test_toolchain.cpp | 2 +- third_party/mbedtls/mbedtls-config.h | 9 +- 143 files changed, 2932 insertions(+), 1831 deletions(-) create mode 100644 src/core/common/context.hpp create mode 100644 src/core/common/locator.cpp create mode 100644 src/core/common/locator.hpp create mode 100644 src/core/openthread-single-instance.h diff --git a/configure.ac b/configure.ac index eb786ac24..3f43a29d5 100644 --- a/configure.ac +++ b/configure.ac @@ -506,6 +506,37 @@ AC_DEFINE_UNQUOTED([OPENTHREAD_ENABLE_NCP_UART],[${OPENTHREAD_ENABLE_NCP_UART}], AC_MSG_CHECKING([sould NCP support UART]) AC_MSG_RESULT([${OPENTHREAD_ENABLE_UART}]) +# +# Multiple OpenThread Instances +# + +AC_ARG_ENABLE(multiple-instances, + [AS_HELP_STRING([--enable-multiple-instances],[Enable support for multiple OpenThread instances @<:@default=no@:>@.])], + [ + case "${enableval}" in + + no|yes) + enable_multiple_instances=${enableval} + ;; + + *) + AC_MSG_ERROR([Invalid value ${enable_multiple_instances} for --enable-multiple-instances]) + ;; + esac + ], + [enable_multiple_instances=no]) + +if test "$enable_multiple_instances" = "yes"; then + OPENTHREAD_ENABLE_MULTIPLE_INSTANCES=1 +else + OPENTHREAD_ENABLE_MULTIPLE_INSTANCES=0 +fi + +AC_MSG_RESULT(${enable_multiple_instances}) +AC_SUBST(OPENTHREAD_ENABLE_MULTIPLE_INSTANCES) +AM_CONDITIONAL([OPENTHREAD_ENABLE_MULTIPLE_INSTANCES], [test "${enable_multiple_instances}" = "yes"]) +AC_DEFINE_UNQUOTED([OPENTHREAD_ENABLE_MULTIPLE_INSTANCES],[${OPENTHREAD_ENABLE_MULTIPLE_INSTANCES}],[Define to 1 if you want to enable support for multiple OpenThread instances.]) + # # Builtin mbedtls # @@ -1382,6 +1413,7 @@ AC_MSG_NOTICE([ OpenThread NCP-MTD support : ${enable_ncp_app_mtd} OpenThread NCP-FTD support : ${enable_ncp_app_ftd} OpenThread NCP-BUS Configuration : ${with_ncp_bus} + OpenThread Multiple Instances support : ${enable_multiple_instances} OpenThread MTD Network Diagnostic support : ${enable_mtd_network_diagnostic} OpenThread builtin mbedtls support : ${enable_builtin_mbedtls} OpenThread TMF Proxy support : ${enable_tmf_proxy} diff --git a/etc/visual-studio/UnitTests.vcxproj b/etc/visual-studio/UnitTests.vcxproj index d44a0235f..f8a64483f 100644 --- a/etc/visual-studio/UnitTests.vcxproj +++ b/etc/visual-studio/UnitTests.vcxproj @@ -49,7 +49,6 @@ %(PreprocessorDefinitions) MBEDTLS_CONFIG_FILE="mbedtls-config.h"; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; Level3 diff --git a/etc/visual-studio/libopenthread-cli.vcxproj b/etc/visual-studio/libopenthread-cli.vcxproj index 06e1a5658..8120e9fc8 100644 --- a/etc/visual-studio/libopenthread-cli.vcxproj +++ b/etc/visual-studio/libopenthread-cli.vcxproj @@ -1,6 +1,6 @@  - + {41B32069-632E-4578-855B-A36EBFA80B56} StaticLibrary @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); MBEDTLS_CONFIG_FILE="mbedtls-config.h"; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; OTBUILD; diff --git a/etc/visual-studio/libopenthread-ncp-spi.vcxproj b/etc/visual-studio/libopenthread-ncp-spi.vcxproj index d8a63d3c1..2b01424c6 100644 --- a/etc/visual-studio/libopenthread-ncp-spi.vcxproj +++ b/etc/visual-studio/libopenthread-ncp-spi.vcxproj @@ -1,6 +1,6 @@  - + {B92F449E-0FD9-44FC-ACFA-6521A3240CA2} StaticLibrary @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); MBEDTLS_CONFIG_FILE="mbedtls-config.h"; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; OPENTHREAD_ENABLE_NCP_SPI=1; OPENTHREAD_ENABLE_NCP_UART=0; diff --git a/etc/visual-studio/libopenthread-ncp-uart.vcxproj b/etc/visual-studio/libopenthread-ncp-uart.vcxproj index c5339c0b7..e7c59740e 100644 --- a/etc/visual-studio/libopenthread-ncp-uart.vcxproj +++ b/etc/visual-studio/libopenthread-ncp-uart.vcxproj @@ -1,6 +1,6 @@ - + {D94867D2-6DAE-47E2-962A-5E8E658134D1} StaticLibrary @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); MBEDTLS_CONFIG_FILE="mbedtls-config.h"; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; OPENTHREAD_ENABLE_NCP_SPI=0; OPENTHREAD_ENABLE_NCP_UART=1; diff --git a/etc/visual-studio/libopenthread.vcxproj b/etc/visual-studio/libopenthread.vcxproj index 3a6549071..945af97c4 100644 --- a/etc/visual-studio/libopenthread.vcxproj +++ b/etc/visual-studio/libopenthread.vcxproj @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); MBEDTLS_CONFIG_FILE="mbedtls-config.h"; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; OTBUILD; @@ -77,6 +76,7 @@ + @@ -149,8 +149,10 @@ + + diff --git a/etc/visual-studio/libopenthread.vcxproj.filters b/etc/visual-studio/libopenthread.vcxproj.filters index f6b99f71c..dc88bc545 100644 --- a/etc/visual-studio/libopenthread.vcxproj.filters +++ b/etc/visual-studio/libopenthread.vcxproj.filters @@ -126,6 +126,9 @@ Source Files\coap + + Source Files\common + Source Files\common @@ -335,12 +338,18 @@ Header Files\common + + Header Files\common + Header Files\common Header Files\common + + Header Files\common + Header Files\common diff --git a/etc/visual-studio/libopenthread_k.vcxproj b/etc/visual-studio/libopenthread_k.vcxproj index ca6772c58..648b03fca 100644 --- a/etc/visual-studio/libopenthread_k.vcxproj +++ b/etc/visual-studio/libopenthread_k.vcxproj @@ -42,7 +42,6 @@ OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; OPENTHREAD_PROJECT_CORE_CONFIG_FILE="openthread-core-windows-config.h"; WINDOWS_LOGGING; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_FTD=1; HAVE_STDBOOL_H=1; HAVE_STDINT_H=1; @@ -86,6 +85,7 @@ + @@ -180,9 +180,11 @@ + + diff --git a/etc/visual-studio/libopenthread_k.vcxproj.filters b/etc/visual-studio/libopenthread_k.vcxproj.filters index 28fb65f8e..6f72961a6 100644 --- a/etc/visual-studio/libopenthread_k.vcxproj.filters +++ b/etc/visual-studio/libopenthread_k.vcxproj.filters @@ -126,6 +126,9 @@ Source Files\coap + + Source Files\common + Source Files\common @@ -335,12 +338,18 @@ Header Files\common + + Header Files\common + Header Files\common Header Files\common + + Header Files\common + Header Files\common diff --git a/etc/visual-studio/mbedtls.vcxproj b/etc/visual-studio/mbedtls.vcxproj index a08835d07..c81832eaf 100644 --- a/etc/visual-studio/mbedtls.vcxproj +++ b/etc/visual-studio/mbedtls.vcxproj @@ -39,7 +39,7 @@ ;%(PreprocessorDefinitions); MBEDTLS_CONFIG_FILE="mbedtls-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; + OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; ..\..\include; diff --git a/etc/visual-studio/mbedtls_k.vcxproj b/etc/visual-studio/mbedtls_k.vcxproj index 4cf8941ed..51fd42d88 100644 --- a/etc/visual-studio/mbedtls_k.vcxproj +++ b/etc/visual-studio/mbedtls_k.vcxproj @@ -1,6 +1,6 @@  - + {69BE8E8C-CF1E-46D6-932B-DB435F47059B} {8c0e3d8b-df43-455b-815a-4a0e72973bc6} @@ -50,7 +50,6 @@ OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; HAVE_STDBOOL_H=1; HAVE_STDINT_H=1; - OPENTHREAD_MULTIPLE_INSTANCE; 4132;4242;4245;4603;4627;4986;4987;4996;%(DisableSpecificWarnings) Level4 diff --git a/etc/visual-studio/ot-cli.vcxproj b/etc/visual-studio/ot-cli.vcxproj index 7f712b895..6d669f422 100644 --- a/etc/visual-studio/ot-cli.vcxproj +++ b/etc/visual-studio/ot-cli.vcxproj @@ -1,6 +1,6 @@  - + {91D3ADEA-F1FE-4433-95B6-F8F6A7CF7BAF} Win32Proj @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; OPENTHREAD_FTD=1; - OPENTHREAD_MULTIPLE_INSTANCE; %(AdditionalIncludeDirectories); diff --git a/etc/visual-studio/ot-ncp-spi.vcxproj b/etc/visual-studio/ot-ncp-spi.vcxproj index 61e1372a6..af117a4bb 100644 --- a/etc/visual-studio/ot-ncp-spi.vcxproj +++ b/etc/visual-studio/ot-ncp-spi.vcxproj @@ -1,6 +1,6 @@  - + {B4C744EC-B662-46C6-A076-FB58FA8FDF1B} Win32Proj @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; OPENTHREAD_FTD=1; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_ENABLE_NCP_SPI=1; OPENTHREAD_ENABLE_NCP_UART=0; diff --git a/etc/visual-studio/ot-ncp-uart.vcxproj b/etc/visual-studio/ot-ncp-uart.vcxproj index e6bc76c38..e000631c9 100644 --- a/etc/visual-studio/ot-ncp-uart.vcxproj +++ b/etc/visual-studio/ot-ncp-uart.vcxproj @@ -1,6 +1,6 @@  - + {9EEF9DCD-EA8F-4154-BD02-AB2B31CEC324} Win32Proj @@ -40,7 +40,6 @@ %(PreprocessorDefinitions); OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; OPENTHREAD_FTD=1; - OPENTHREAD_MULTIPLE_INSTANCE; OPENTHREAD_ENABLE_NCP_SPI=0; OPENTHREAD_ENABLE_NCP_UART=1; diff --git a/etc/visual-studio/otLwf.vcxproj b/etc/visual-studio/otLwf.vcxproj index 9c5060584..46af170f8 100644 --- a/etc/visual-studio/otLwf.vcxproj +++ b/etc/visual-studio/otLwf.vcxproj @@ -43,7 +43,6 @@ OPENTHREAD_FTD=1; OPENTHREAD_CONFIG_FILE="openthread-windows-config.h"; OPENTHREAD_PROJECT_CORE_CONFIG_FILE="openthread-core-windows-config.h"; - OPENTHREAD_MULTIPLE_INSTANCE; %(AdditionalIncludeDirectories); diff --git a/examples/apps/cli/main.c b/examples/apps/cli/main.c index 54c6af306..17d489395 100644 --- a/examples/apps/cli/main.c +++ b/examples/apps/cli/main.c @@ -35,7 +35,7 @@ #include #include -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES void *otPlatCAlloc(size_t aNum, size_t aSize) { return calloc(aNum, aSize); @@ -56,14 +56,14 @@ int main(int argc, char *argv[]) { otInstance *sInstance; -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES size_t otInstanceBufferLength = 0; uint8_t *otInstanceBuffer = NULL; #endif PlatformInit(argc, argv); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES // Call to query the buffer size (void)otInstanceInit(NULL, &otInstanceBufferLength); @@ -74,7 +74,7 @@ int main(int argc, char *argv[]) // Initialize OpenThread with the buffer sInstance = otInstanceInit(otInstanceBuffer, &otInstanceBufferLength); #else - sInstance = otInstanceInit(); + sInstance = otInstanceInitSingle(); #endif assert(sInstance); @@ -91,7 +91,7 @@ int main(int argc, char *argv[]) } // otInstanceFinalize(sInstance); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES // free(otInstanceBuffer); #endif diff --git a/examples/apps/ncp/main.c b/examples/apps/ncp/main.c index ffc63af89..5f5321802 100644 --- a/examples/apps/ncp/main.c +++ b/examples/apps/ncp/main.c @@ -35,7 +35,7 @@ #include #include -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES void *otPlatCAlloc(size_t aNum, size_t aSize) { return calloc(aNum, aSize); @@ -56,14 +56,14 @@ int main(int argc, char *argv[]) { otInstance *sInstance; -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES size_t otInstanceBufferLength = 0; uint8_t *otInstanceBuffer = NULL; #endif PlatformInit(argc, argv); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES // Call to query the buffer size (void)otInstanceInit(NULL, &otInstanceBufferLength); @@ -74,7 +74,7 @@ int main(int argc, char *argv[]) // Initialize OpenThread with the buffer sInstance = otInstanceInit(otInstanceBuffer, &otInstanceBufferLength); #else - sInstance = otInstanceInit(); + sInstance = otInstanceInitSingle(); #endif assert(sInstance); @@ -91,7 +91,7 @@ int main(int argc, char *argv[]) } // otInstanceFinalize(sInstance); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES // free(otInstanceBuffer); #endif diff --git a/include/openthread-windows-config.h b/include/openthread-windows-config.h index 3ab58518b..a89b9cbf2 100644 --- a/include/openthread-windows-config.h +++ b/include/openthread-windows-config.h @@ -32,6 +32,10 @@ /* Define to 1 to enable the NCP SPI interface. */ // On the command line: #define OPENTHREAD_ENABLE_NCP_SPI 1 +/* Define to 1 if you want to enable support for multiple OpenThread + instances. */ +#define OPENTHREAD_ENABLE_MULTIPLE_INSTANCES 1 + /* Define to 1 if you want to enable default log output. */ #define OPENTHREAD_CONFIG_ENABLE_DEFAULT_LOG_OUTPUT 1 diff --git a/include/openthread/instance.h b/include/openthread/instance.h index d8878ad39..5446ad4d8 100644 --- a/include/openthread/instance.h +++ b/include/openthread/instance.h @@ -35,6 +35,8 @@ #ifndef OPENTHREAD_INSTANCE_H_ #define OPENTHREAD_INSTANCE_H_ +#include + #include #include @@ -157,16 +159,18 @@ OTAPI uint32_t OTCALL otGetCompartmentId(otInstance *aInstance); #else // OTDLL -#ifdef OPENTHREAD_MULTIPLE_INSTANCE /** * This function initializes the OpenThread library. * + * * This function initializes OpenThread and prepares it for subsequent OpenThread API calls. This function must be * called before any other calls to OpenThread. By default, OpenThread is initialized in the 'enabled' state. * + * This function is available and can only be used when support for multiple OpenThread instances is enabled. + * * @param[in] aInstanceBuffer The buffer for OpenThread to use for allocating the otInstance structure. - * @param[inout] aInstanceBufferSize On input, the size of aInstanceBuffer. On output, if not enough space for otInstance, - the number of bytes required for otInstance. + * @param[inout] aInstanceBufferSize On input, the size of aInstanceBuffer. On output, if not enough space for + * otInstance, the number of bytes required for otInstance. * * @retval otInstance* The new OpenThread instance structure. * @@ -174,18 +178,19 @@ OTAPI uint32_t OTCALL otGetCompartmentId(otInstance *aInstance); * */ otInstance *otInstanceInit(void *aInstanceBuffer, size_t *aInstanceBufferSize); -#else // OPENTHREAD_MULTIPLE_INSTANCE + /** - * This function initializes the static instance of the OpenThread library. + * This function initializes the static single instance of the OpenThread library. * * This function initializes OpenThread and prepares it for subsequent OpenThread API calls. This function must be * called before any other calls to OpenThread. By default, OpenThread is initialized in the 'enabled' state. * - * @retval otInstance* The new OpenThread instance structure. + * This function is available and can only be used when support for multiple OpenThread instances is disabled. + * + * @retval The new single OpenThread instance structure. * */ -otInstance *otInstanceInit(void); -#endif // OPENTHREAD_MULTIPLE_INSTANCE +otInstance *otInstanceInitSingle(void); /** * This function disables the OpenThread library. diff --git a/include/openthread/platform/memory.h b/include/openthread/platform/memory.h index c9a1fec93..bbada59ec 100644 --- a/include/openthread/platform/memory.h +++ b/include/openthread/platform/memory.h @@ -49,9 +49,9 @@ extern "C" { * */ -// Currently, OpenThread only requires dynamic memory allocation when supporting multiple -// simultaneous instances, for MbedTls. -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +/* + * OpenThread only requires dynamic memory allocation when supporting multiple simultaneous instances, for MbedTls. + */ /** * Dynamically allocates new memory. On platforms that support it, should just redirect to calloc. For @@ -61,6 +61,8 @@ extern "C" { * memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes * of value zero." * + * This function is available and can ONLY be used only when support for multiple OpenThread instances is enabled. + * * @param[in] aNum The number of blocks to allocate * @param[in] aSize The size of each block to allocate * @@ -72,12 +74,12 @@ void *otPlatCAlloc(size_t aNum, size_t aSize); /** * Frees memory that was dynamically allocated. * + * This function is available and can ONLY be used only when support for multiple OpenThread instances is enabled. + * * @param[in] aPtr A pointer the memory blocks to free. The pointer may be NULL. */ void otPlatFree(void *aPtr); -#endif - /** * @} * diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index 953bfb066..8ef49f8f2 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -1682,9 +1682,9 @@ exit: AppendResult(error); } -void Interpreter::s_HandlePingTimer(void *aContext) +void Interpreter::s_HandlePingTimer(Timer &aTimer) { - static_cast(aContext)->HandlePingTimer(); + GetOwner(aTimer).HandlePingTimer(); } void Interpreter::HandlePingTimer() @@ -3181,5 +3181,16 @@ void Interpreter::HandleDiagnosticGetResponse(Message &aMessage, const Ip6::Mess } #endif +Interpreter &Interpreter::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Interpreter &interpreter = *static_cast(aContext.GetContext()); +#else + Interpreter &interpreter = Uart::sUartServer->GetInterpreter(); + OT_UNUSED_VARIABLE(aContext); +#endif + return interpreter; +} + } // namespace Cli } // namespace ot diff --git a/src/cli/cli.hpp b/src/cli/cli.hpp index 41bf28f76..e44b9aafb 100644 --- a/src/cli/cli.hpp +++ b/src/cli/cli.hpp @@ -50,6 +50,7 @@ #endif #include "common/code_utils.hpp" +#include "common/context.hpp" #ifndef OTDLL #include @@ -283,7 +284,7 @@ private: #ifndef OTDLL static void s_HandleIcmpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo, const otIcmp6Header *aIcmpHeader); - static void s_HandlePingTimer(void *aContext); + static void s_HandlePingTimer(Timer &aTimer); #endif static void OTCALL s_HandleActiveScanResult(otActiveScanResult *aResult, void *aContext); static void OTCALL s_HandleNetifStateChanged(uint32_t aFlags, void *aContext); @@ -329,6 +330,8 @@ private: void HandleDnsResponse(const char *aHostname, Ip6::Address &aAddress, uint32_t aTtl, otError aResult); #endif + static Interpreter &GetOwner(const Context &aContext); + #if OPENTHREAD_ENABLE_APPLICATION_COAP Coap mCoap; diff --git a/src/cli/cli_uart.hpp b/src/cli/cli_uart.hpp index 9665fe95f..a061dbdde 100644 --- a/src/cli/cli_uart.hpp +++ b/src/cli/cli_uart.hpp @@ -91,6 +91,14 @@ public: */ int OutputFormatV(const char *aFmt, va_list aAp); + /** + * This method returns a reference to the interpreter object. + * + * @returns A reference to the interpreter object. + * + */ + Interpreter &GetInterpreter(void) { return mInterpreter; } + void ReceiveTask(const uint8_t *aBuf, uint16_t aBufLength); void SendDoneTask(void); diff --git a/src/core/Makefile.am b/src/core/Makefile.am index 7690b117c..f3ec6e6b9 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -119,6 +119,7 @@ SOURCES_COMMON = \ coap/coap_secure.cpp \ common/crc16.cpp \ common/logging.cpp \ + common/locator.cpp \ common/message.cpp \ common/tasklet.cpp \ common/timer.cpp \ @@ -199,14 +200,17 @@ HEADERS_COMMON = \ openthread-core-config.h \ openthread-core-default-config.h \ openthread-instance.h \ + openthread-single-instance.h \ api/link_raw.hpp \ coap/coap.hpp \ coap/coap_header.hpp \ coap/coap_secure.hpp \ common/code_utils.hpp \ + common/context.hpp \ common/crc16.hpp \ common/debug.hpp \ common/encoding.hpp \ + common/locator.hpp \ common/logging.hpp \ common/message.hpp \ common/settings.hpp \ diff --git a/src/core/api/instance_api.cpp b/src/core/api/instance_api.cpp index 469bfdf8f..1cf4b5dff 100644 --- a/src/core/api/instance_api.cpp +++ b/src/core/api/instance_api.cpp @@ -40,13 +40,45 @@ #include #include "openthread-instance.h" +#include "openthread-single-instance.h" #include "common/logging.hpp" #include "common/new.hpp" -#ifndef OPENTHREAD_MULTIPLE_INSTANCE +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + static otDEFINE_ALIGNED_VAR(sInstanceRaw, sizeof(otInstance), uint64_t); otInstance *sInstance = NULL; -#endif + +otInstance *otGetInstance(void) +{ + return sInstance; +} + +ot::ThreadNetif &otGetThreadNetif(void) +{ + return sInstance->mThreadNetif; +} + +ot::MeshForwarder &otGetMeshForwarder(void) +{ + return sInstance->mThreadNetif.GetMeshForwarder(); +} + +ot::TimerScheduler &otGetTimerScheduler(void) +{ + return sInstance->mIp6.mTimerScheduler; +} + +ot::TaskletScheduler &otGetTaskletScheduler(void) +{ + return sInstance->mIp6.mTaskletScheduler; +} + +ot::Ip6::Ip6 &otGetIp6(void) +{ + return sInstance->mIp6; +} +#endif // #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES otInstance::otInstance(void) : mReceiveIp6DatagramCallback(NULL), @@ -95,11 +127,11 @@ void otInstancePostConstructor(otInstance *aInstance) #endif } -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES otInstance *otInstanceInit(void *aInstanceBuffer, size_t *aInstanceBufferSize) { - otInstance *aInstance = NULL; + otInstance *instance = NULL; otLogFuncEntry(); @@ -111,27 +143,31 @@ otInstance *otInstanceInit(void *aInstanceBuffer, size_t *aInstanceBufferSize) VerifyOrExit(aInstanceBuffer != NULL); // Construct the context - aInstance = new(aInstanceBuffer)otInstance(); + instance = new(aInstanceBuffer)otInstance(); // Execute post constructor operations - otInstancePostConstructor(aInstance); + otInstancePostConstructor(instance); - otLogInfoApi(aInstance, "otInstance Initialized"); + otLogInfoApi(instance, "otInstance Initialized"); exit: otLogFuncExit(); - return aInstance; + return instance; } -#else +#else // #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES -otInstance *otInstanceInit() +otInstance *otInstanceInitSingle(void) { otLogFuncEntry(); VerifyOrExit(sInstance == NULL); + // We need to ensure `sInstance` pointer is correctly set + // before any object constructor is called. + sInstance = reinterpret_cast(&sInstanceRaw); + // Construct the context sInstance = new(&sInstanceRaw)otInstance(); @@ -146,7 +182,7 @@ exit: return sInstance; } -#endif +#endif // #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES void otInstanceFinalize(otInstance *aInstance) { @@ -156,9 +192,10 @@ void otInstanceFinalize(otInstance *aInstance) (void)otThreadSetEnabled(aInstance, false); (void)otIp6SetEnabled(aInstance, false); -#ifndef OPENTHREAD_MULTIPLE_INSTANCE +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES sInstance = NULL; #endif + otLogFuncExit(); } diff --git a/src/core/api/link_raw.hpp b/src/core/api/link_raw.hpp index b9e4e5e33..53ed61252 100644 --- a/src/core/api/link_raw.hpp +++ b/src/core/api/link_raw.hpp @@ -111,6 +111,8 @@ public: void InvokeEnergyScanDone(int8_t aEnergyScanMaxRssi); private: + otError DoTransmit(otRadioFrame *aFrame); + static LinkRaw &GetOwner(const Context &aContext); otInstance &mInstance; bool mEnabled; @@ -119,8 +121,6 @@ private: otLinkRawTransmitDone mTransmitDoneCallback; otLinkRawEnergyScanDone mEnergyScanDoneCallback; - otError DoTransmit(otRadioFrame *aFrame); - #if OPENTHREAD_LINKRAW_TIMER_REQUIRED enum TimerReason @@ -135,6 +135,7 @@ private: TimerReason mTimerReason; static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); #endif // OPENTHREAD_LINKRAW_TIMER_REQUIRED @@ -158,7 +159,7 @@ private: Tasklet mEnergyScanTask; int8_t mEnergyScanRssi; - static void HandleEnergyScanTask(void *aContext); + static void HandleEnergyScanTask(Tasklet &aTasklet); void HandleEnergyScanTask(void); #endif // OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN diff --git a/src/core/api/link_raw_api.cpp b/src/core/api/link_raw_api.cpp index f32fc58b9..5e6f34def 100644 --- a/src/core/api/link_raw_api.cpp +++ b/src/core/api/link_raw_api.cpp @@ -32,12 +32,13 @@ */ #include -#include -#include + #include #include #include "openthread-instance.h" +#include "common/debug.hpp" +#include "common/logging.hpp" #if OPENTHREAD_ENABLE_RAW_LINK_API @@ -483,6 +484,11 @@ void LinkRaw::HandleTimer(void *aContext) static_cast(aContext)->HandleTimer(); } +void LinkRaw::HandleTimer(Timer &aTimer) +{ + GetOwner(aTimer).HandleTimer(); +} + void LinkRaw::HandleTimer(void) { TimerReason timerReason = mTimerReason; @@ -578,9 +584,9 @@ void LinkRaw::StartCsmaBackoff(void) #if OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN -void LinkRaw::HandleEnergyScanTask(void *aContext) +void LinkRaw::HandleEnergyScanTask(Tasklet &aTasklet) { - static_cast(aContext)->HandleEnergyScanTask(); + GetOwner(aTasklet).HandleEnergyScanTask(); } void LinkRaw::HandleEnergyScanTask(void) @@ -607,6 +613,17 @@ void LinkRaw::HandleEnergyScanTask(void) #endif // OPENTHREAD_CONFIG_ENABLE_SOFTWARE_ENERGY_SCAN +LinkRaw &LinkRaw::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + LinkRaw &link = *static_cast(aContext.GetContext()); +#else + LinkRaw &link = otGetInstance()->mLinkRaw; + OT_UNUSED_VARIABLE(aContext); +#endif + return link; +} + } // namespace ot #endif // OPENTHREAD_ENABLE_RAW_LINK_API diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 6842d3dd8..3c380ebc9 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -50,7 +50,7 @@ namespace ot { namespace Coap { Coap::Coap(ThreadNetif &aNetif): - mNetif(aNetif), + ThreadNetifLocator(aNetif), mSocket(aNetif.GetIp6().mUdp), mRetransmissionTimer(aNetif.GetIp6().mTimerScheduler, &Coap::HandleRetransmissionTimer, this), mResources(NULL), @@ -287,9 +287,20 @@ exit: return error; } -void Coap::HandleRetransmissionTimer(void *aContext) +Coap &Coap::GetOwner(const Context &aContext) { - static_cast(aContext)->HandleRetransmissionTimer(); +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Coap &coap = *static_cast(aContext.GetContext()); +#else + Coap &coap = otGetThreadNetif().GetCoap(); + OT_UNUSED_VARIABLE(aContext); +#endif + return coap; +} + +void Coap::HandleRetransmissionTimer(Timer &aTimer) +{ + GetOwner(aTimer).HandleRetransmissionTimer(); } void Coap::HandleRetransmissionTimer(void) @@ -543,7 +554,7 @@ exit: if (error) { - otLogInfoCoapErr(mNetif.GetInstance(), error, "Receive failed"); + otLogInfoCoapErr(GetNetif().GetInstance(), error, "Receive failed"); } } @@ -704,7 +715,7 @@ exit: if (error != OT_ERROR_NONE) { - otLogInfoCoapErr(mNetif.GetInstance(), error, "Failed to process request"); + otLogInfoCoapErr(GetNetif().GetInstance(), error, "Failed to process request"); if (error == OT_ERROR_NOT_FOUND) { @@ -887,9 +898,20 @@ void ResponsesQueue::DequeueAllResponses(void) } } -void ResponsesQueue::HandleTimer(void *aContext) +ResponsesQueue &ResponsesQueue::GetOwner(const Context &aContext) { - static_cast(aContext)->HandleTimer(); +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + ResponsesQueue &queue = *static_cast(aContext.GetContext()); +#else + ResponsesQueue &queue = otGetThreadNetif().GetCoap().mResponsesQueue; + OT_UNUSED_VARIABLE(aContext); +#endif + return queue; +} + +void ResponsesQueue::HandleTimer(Timer &aTimer) +{ + GetOwner(aTimer).HandleTimer(); } void ResponsesQueue::HandleTimer(void) diff --git a/src/core/coap/coap.hpp b/src/core/coap/coap.hpp index 7a9707e28..bcc9dbaf9 100644 --- a/src/core/coap/coap.hpp +++ b/src/core/coap/coap.hpp @@ -33,6 +33,7 @@ #include "coap/coap_header.hpp" #include "common/debug.hpp" +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "net/ip6.hpp" @@ -407,20 +408,22 @@ private: }; void DequeueResponse(Message &aMessage) { mQueue.Dequeue(aMessage); aMessage.Free(); } + static ResponsesQueue &GetOwner(const Context &aContext); + static void HandleTimer(Timer &aTimer); + void HandleTimer(void); MessageQueue mQueue; Timer mTimer; - - static void HandleTimer(void *aContext); - void HandleTimer(void); }; /** * This class implements the CoAP client and server. * */ -class Coap +class Coap: public ThreadNetifLocator { + friend class ResponsesQueue; + public: /** * This function pointer is called before CoAP server processing a CoAP packets. @@ -661,7 +664,6 @@ protected: */ virtual void Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - ThreadNetif &mNetif; Ip6::UdpSocket mSocket; private: @@ -686,9 +688,11 @@ private: otError SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); otError SendEmptyMessage(Header::Type aType, const Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo); - static void HandleRetransmissionTimer(void *aContext); + static void HandleRetransmissionTimer(Timer &aTimer); void HandleRetransmissionTimer(void); + static Coap &GetOwner(const Context &aContext); + MessageQueue mPendingRequests; uint16_t mMessageId; Timer mRetransmissionTimer; diff --git a/src/core/coap/coap_secure.cpp b/src/core/coap/coap_secure.cpp index eda824715..e117639cf 100644 --- a/src/core/coap/coap_secure.cpp +++ b/src/core/coap/coap_secure.cpp @@ -98,33 +98,33 @@ otError CoapSecure::Connect(const Ip6::MessageInfo &aMessageInfo, ConnectedCallb mConnectedCallback = aCallback; mConnectedContext = aContext; - return mNetif.GetDtls().Start(true, &CoapSecure::HandleDtlsConnected, &CoapSecure::HandleDtlsReceive, - &CoapSecure::HandleDtlsSend, this); + return GetNetif().GetDtls().Start(true, &CoapSecure::HandleDtlsConnected, &CoapSecure::HandleDtlsReceive, + &CoapSecure::HandleDtlsSend, this); } bool CoapSecure::IsConnectionActive(void) { - return mNetif.GetDtls().IsStarted(); + return GetNetif().GetDtls().IsStarted(); } bool CoapSecure::IsConnected(void) { - return mNetif.GetDtls().IsConnected(); + return GetNetif().GetDtls().IsConnected(); } otError CoapSecure::Disconnect(void) { - return mNetif.GetDtls().Stop(); + return GetNetif().GetDtls().Stop(); } MeshCoP::Dtls &CoapSecure::GetDtls(void) { - return mNetif.GetDtls(); + return GetNetif().GetDtls(); } otError CoapSecure::SetPsk(const uint8_t *aPsk, uint8_t aPskLength) { - return mNetif.GetDtls().SetPsk(aPsk, aPskLength); + return GetNetif().GetDtls().SetPsk(aPsk, aPskLength); } otError CoapSecure::SendMessage(Message &aMessage, otCoapResponseHandler aHandler, void *aContext) @@ -151,14 +151,16 @@ otError CoapSecure::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMess otError CoapSecure::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { OT_UNUSED_VARIABLE(aMessageInfo); - return mNetif.GetDtls().Send(aMessage, aMessage.GetLength()); + return GetNetif().GetDtls().Send(aMessage, aMessage.GetLength()); } void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); + otLogFuncEntry(); - if (!mNetif.GetDtls().IsStarted()) + if (!netif.GetDtls().IsStarted()) { Ip6::SockAddr sockAddr; sockAddr.mAddress = aMessageInfo.GetPeerAddr(); @@ -168,14 +170,14 @@ void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr()); mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort()); - if (mNetif.IsUnicastAddress(aMessageInfo.GetSockAddr())) + if (netif.IsUnicastAddress(aMessageInfo.GetSockAddr())) { mPeerAddress.SetSockAddr(aMessageInfo.GetSockAddr()); } mPeerAddress.SetSockPort(aMessageInfo.GetSockPort()); - mNetif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this); + netif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this); } else { @@ -184,9 +186,9 @@ void CoapSecure::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort())); } - mNetif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, - sizeof(mPeerAddress.GetPeerAddr().mFields)); - mNetif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); + netif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, + sizeof(mPeerAddress.GetPeerAddr().mFields)); + netif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); exit: otLogFuncExit(); @@ -216,7 +218,7 @@ void CoapSecure::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength) otLogFuncEntry(); - VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL); + VerifyOrExit((message = GetNetif().GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL); SuccessOrExit(message->Append(aBuf, aLength)); Coap::Receive(*message, mPeerAddress); @@ -271,9 +273,9 @@ exit: return error; } -void CoapSecure::HandleUdpTransmit(void *aContext) +void CoapSecure::HandleUdpTransmit(Tasklet &aTasklet) { - return static_cast(aContext)->HandleUdpTransmit(); + GetOwner(aTasklet).HandleUdpTransmit(); } void CoapSecure::HandleUdpTransmit(void) @@ -305,6 +307,17 @@ exit: otLogFuncExit(); } +CoapSecure &CoapSecure::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + CoapSecure &coap = *static_cast(aContext.GetContext()); +#else + CoapSecure &coap = otGetThreadNetif().GetCoapSecure(); + OT_UNUSED_VARIABLE(aContext); +#endif + return coap; +} + } // namespace Coap } // namespace ot diff --git a/src/core/coap/coap_secure.hpp b/src/core/coap/coap_secure.hpp index 5f78c52f6..8ef72ea8d 100644 --- a/src/core/coap/coap_secure.hpp +++ b/src/core/coap/coap_secure.hpp @@ -211,9 +211,11 @@ private: static otError HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); otError HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType); - static void HandleUdpTransmit(void *aContext); + static void HandleUdpTransmit(Tasklet &aTasklet); void HandleUdpTransmit(void); + static CoapSecure &GetOwner(const Context &aContext); + Ip6::MessageInfo mPeerAddress; ConnectedCallback mConnectedCallback; void *mConnectedContext; diff --git a/src/core/common/context.hpp b/src/core/common/context.hpp new file mode 100644 index 000000000..276b6e0c1 --- /dev/null +++ b/src/core/common/context.hpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2017, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes definitions for maintaining a pointer to arbitrary context information. + */ + +#ifndef CONTEXT_HPP_ +#define CONTEXT_HPP_ + +#include +#include + +#include "openthread-core-config.h" + +namespace ot { + +/** + * @addtogroup core-context + * + * @brief + * This module includes definitions for maintaining a pointer to arbitrary context information. + * + * @{ + * + */ + +/** + * This class implements definitions for maintaining a pointer to arbitrary context information. + * + * This is used as base class for objects that provide a callback or handler (e.g., Timer or Tasklet). + * + */ +class Context +{ +public: + +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + /** + * This method returns the pointer to the arbitrary context information. + * + * @returns The pointer to the context information. + * + */ + void *GetContext(void) const { return mContext; } +#endif + +protected: + /** + * This constructor initializes the context object. + * + * @param[in] aContext A pointer to arbitrary context information. + * + */ + Context(void *aContext) +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + : mContext(aContext) +#endif + { + OT_UNUSED_VARIABLE(aContext); + } + +private: +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + void *mContext; +#endif +}; + +/** + * @} + * + */ + +} // namespace ot + +#endif // CONTEXT_HPP_ diff --git a/src/core/common/locator.cpp b/src/core/common/locator.cpp new file mode 100644 index 000000000..c4a66b8b8 --- /dev/null +++ b/src/core/common/locator.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2017, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file implements the locator class for OpenThread objects. + */ + +#define WPP_NAME "locator.tmh" + +#include + +#include "locator.hpp" + +#include "openthread-instance.h" +#include "net/ip6.hpp" + +namespace ot { + +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + +otInstance *ThreadNetifLocator::GetInstance(void) const +{ + return otInstanceFromThreadNetif(&GetNetif()); +} + +otInstance *MeshForwarderLocator::GetInstance(void) const +{ + return otInstanceFromThreadNetif(&GetMeshForwarder().GetNetif()); +} + +otInstance *TimerSchedulerLocator::GetInstance(void) const +{ + return otInstanceFromIp6(Ip6::Ip6FromTimerScheduler(&GetTimerScheduler())); +} + +otInstance *TaskletSchedulerLocator::GetInstance(void) const +{ + return otInstanceFromIp6(Ip6::Ip6FromTaskletScheduler(&GetTaskletScheduler())); +} + +otInstance *Ip6Locator::GetInstance(void) const +{ + return otInstanceFromIp6(&GetIp6()); +} + +#endif // #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + +} // namespace ot diff --git a/src/core/common/locator.hpp b/src/core/common/locator.hpp new file mode 100644 index 000000000..1e38525d5 --- /dev/null +++ b/src/core/common/locator.hpp @@ -0,0 +1,341 @@ +/* + * Copyright (c) 2017, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes definitions for locator class for OpenThread objects. + */ + +#ifndef LOCATOR_HPP_ +#define LOCATOR_HPP_ + +#include + +#include + +#include "openthread-core-config.h" +#include "openthread-single-instance.h" + +namespace ot { + +class ThreadNetif; +class MeshForwarder; +class TaskletScheduler; +class TimerScheduler; +namespace Ip6 { class Ip6; } + +/** + * @addtogroup core-locator + * + * @brief + * This module includes definitions for locator base class for OpenThread objects. + * + * @{ + * + */ + +/** + * This template class implements the base locator for OpenThread objects. + * + */ +template +class Locator +{ +protected: + /** + * This constructor initializes the locator. + * + * @param[in] aObject A reference to the object. + * + */ + Locator(Type &aObject) +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + : mLocatorObject(aObject) +#endif + { + OT_UNUSED_VARIABLE(aObject); + } + +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Type &mLocatorObject; +#endif +}; + +/** + * This class implements a locator for ThreadNetif object. + * + */ +class ThreadNetifLocator: private Locator +{ +public: + /** + * This method returns a reference to the thread network interface. + * + * @returns A reference to the thread network interface. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + ThreadNetif &GetNetif(void) const { return mLocatorObject; } +#else + ThreadNetif &GetNetif(void) const { return otGetThreadNetif(); } +#endif + + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const; +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aThreadNetif A reference to the thread network interface. + * + */ + ThreadNetifLocator(ThreadNetif &aThreadNetif): Locator(aThreadNetif) { } +}; + +/** + * This class implements a locator for MeshForwarder object. + * + */ +class MeshForwarderLocator: private Locator +{ +public: + /** + * This method returns a reference to the MeshForwarder. + * + * @returns A reference to the MeshForwarder. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + MeshForwarder &GetMeshForwarder(void) const { return mLocatorObject; } +#else + MeshForwarder &GetMeshForwarder(void) const { return otGetMeshForwarder(); } +#endif + + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const; +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aMeshForwarder A reference to the MeshForwarder. + * + */ + MeshForwarderLocator(MeshForwarder &aMeshForwarder): Locator(aMeshForwarder) { } +}; + +/** + * This class implements a locator for TimerScheduler object. + * + */ +class TimerSchedulerLocator: private Locator +{ +public: + /** + * This method returns a reference to the TimerScheduler. + * + * @returns A reference to the TimerScheduler. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + TimerScheduler &GetTimerScheduler(void) const { return mLocatorObject; } +#else + TimerScheduler &GetTimerScheduler(void) const { return otGetTimerScheduler(); } +#endif + + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const; +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aTimerScheduler A reference to the TimerScheduler. + * + */ + TimerSchedulerLocator(TimerScheduler &aTimerScheduler): Locator(aTimerScheduler) { } +}; + +/** + * This class implements a locator for TaskletScheduler object. + * + */ +class TaskletSchedulerLocator: private Locator +{ +public: + /** + * This method returns a reference to the TaskletScheduler. + * + * @returns A reference to the TaskletScheduler. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + TaskletScheduler &GetTaskletScheduler(void) const { return mLocatorObject; } +#else + TaskletScheduler &GetTaskletScheduler(void) const { return otGetTaskletScheduler(); } +#endif + + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const; +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aTaskletScheduler A reference to the TaskletScheduler. + * + */ + TaskletSchedulerLocator(TaskletScheduler &aTaskletScheduler): Locator(aTaskletScheduler) { } +}; + +/** + * This class implements a locator for Ip6 object. + * + */ +class Ip6Locator: private Locator +{ +public: + /** + * This method returns a reference to the Ip6. + * + * @returns A reference to the Ip6. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Ip6::Ip6 &GetIp6(void) const { return mLocatorObject; } +#else + Ip6::Ip6 &GetIp6(void) const { return otGetIp6(); } +#endif + + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const; +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aIp6 A reference to the Ip6. + * + */ + Ip6Locator(Ip6::Ip6 &aIp6): Locator(aIp6) { } +}; + +/** + * This class implements locator for otInstance object + * + */ +class InstanceLocator +{ +public: + /** + * This method returns the pointer to the parent otInstance structure. + * + * @returns The pointer to the parent otInstance structure, or NULL if the instance has been finalized. + * + */ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *GetInstance(void) const { return mInstance; } +#else + otInstance *GetInstance(void) const { return otGetInstance(); } +#endif + +protected: + /** + * This constructor initializes the object. + * + * @param[in] aInstance A pointer to the otInstance. + * + */ + InstanceLocator(otInstance *aInstance) +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + : mInstance(aInstance) +#endif + { + OT_UNUSED_VARIABLE(aInstance); + } + +private: +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + otInstance *mInstance; +#endif +}; + +/** + * @} + * + */ + +} // namespace ot + +#endif // LOCATOR_HPP_ diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index 2c0864611..bc8901766 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -45,12 +45,12 @@ namespace ot { MessagePool::MessagePool(otInstance *aInstance) : - mInstance(aInstance), + InstanceLocator(aInstance), mAllQueue() { #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT // Initialize Platform buffer pool management. - otPlatMessagePoolInit(mInstance, kNumBuffers, sizeof(Buffer)); + otPlatMessagePoolInit(GetInstance(), kNumBuffers, sizeof(Buffer)); #else memset(mBuffers, 0, sizeof(mBuffers)); @@ -64,8 +64,6 @@ MessagePool::MessagePool(otInstance *aInstance) : mBuffers[kNumBuffers - 1].SetNextBuffer(NULL); mNumFreeBuffers = kNumBuffers; #endif - - OT_UNUSED_VARIABLE(mInstance); } Message *MessagePool::New(uint8_t aType, uint16_t aReserved) @@ -108,7 +106,7 @@ Buffer *MessagePool::NewBuffer(void) #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT - buffer = static_cast(otPlatMessagePoolNew(mInstance)); + buffer = static_cast(otPlatMessagePoolNew(GetInstance())); #else @@ -124,7 +122,7 @@ Buffer *MessagePool::NewBuffer(void) if (buffer == NULL) { - otLogInfoMem(mInstance, "No available message buffer"); + otLogInfoMem(GetInstance(), "No available message buffer"); } return buffer; @@ -138,7 +136,7 @@ otError MessagePool::FreeBuffers(Buffer *aBuffer) { tmpBuffer = aBuffer->GetNextBuffer(); #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT - otPlatMessagePoolFree(mInstance, aBuffer); + otPlatMessagePoolFree(GetInstance(), aBuffer); #else // OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT aBuffer->SetNextBuffer(mFreeBuffers); mFreeBuffers = aBuffer; @@ -155,7 +153,7 @@ otError MessagePool::ReclaimBuffers(int aNumBuffers) uint16_t numFreeBuffers; #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT - numFreeBuffers = otPlatMessagePoolNumFreeBuffers(mInstance); + numFreeBuffers = otPlatMessagePoolNumFreeBuffers(GetInstance()); #else numFreeBuffers = mNumFreeBuffers; #endif diff --git a/src/core/common/message.hpp b/src/core/common/message.hpp index 2d92eae5b..876e3e8ce 100644 --- a/src/core/common/message.hpp +++ b/src/core/common/message.hpp @@ -44,6 +44,7 @@ #include "openthread-core-config.h" #include "common/code_utils.hpp" +#include "common/locator.hpp" #include "mac/mac_frame.hpp" namespace ot { @@ -967,7 +968,7 @@ private: * This class represents a message pool * */ -class MessagePool +class MessagePool: public InstanceLocator { friend class Message; friend class MessageQueue; @@ -1105,7 +1106,7 @@ public: * */ #if OPENTHREAD_CONFIG_PLATFORM_MESSAGE_MANAGEMENT - uint16_t GetFreeBufferCount(void) const { return otPlatMessagePoolNumFreeBuffers(mInstance); } + uint16_t GetFreeBufferCount(void) const { return otPlatMessagePoolNumFreeBuffers(GetInstance()); } #else uint16_t GetFreeBufferCount(void) const { return mNumFreeBuffers; } #endif @@ -1127,7 +1128,6 @@ private: Buffer *mFreeBuffers; #endif - otInstance *mInstance; PriorityQueue mAllQueue; }; diff --git a/src/core/common/tasklet.cpp b/src/core/common/tasklet.cpp index 35d0c6aa8..08ad90c33 100644 --- a/src/core/common/tasklet.cpp +++ b/src/core/common/tasklet.cpp @@ -37,6 +37,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "net/ip6.hpp" @@ -44,16 +45,16 @@ namespace ot { Tasklet::Tasklet(TaskletScheduler &aScheduler, Handler aHandler, void *aContext): - mScheduler(aScheduler), + TaskletSchedulerLocator(aScheduler), + Context(aContext), mHandler(aHandler), - mContext(aContext), mNext(NULL) { } otError Tasklet::Post(void) { - return mScheduler.Post(*this); + return GetTaskletScheduler().Post(*this); } TaskletScheduler::TaskletScheduler(void): @@ -72,7 +73,7 @@ otError TaskletScheduler::Post(Tasklet &aTasklet) { mHead = &aTasklet; mTail = &aTasklet; - otTaskletsSignalPending(aTasklet.mScheduler.GetIp6()->GetInstance()); + otTaskletsSignalPending(aTasklet.GetInstance()); } else { @@ -117,7 +118,7 @@ void TaskletScheduler::ProcessQueuedTasklets(void) { if (mHead != NULL) { - otTaskletsSignalPending(cur->mScheduler.GetIp6()->GetInstance()); + otTaskletsSignalPending(mHead->GetInstance()); } break; @@ -125,9 +126,4 @@ void TaskletScheduler::ProcessQueuedTasklets(void) } } -Ip6::Ip6 *TaskletScheduler::GetIp6(void) -{ - return Ip6::Ip6FromTaskletScheduler(this); -} - } // namespace ot diff --git a/src/core/common/tasklet.hpp b/src/core/common/tasklet.hpp index 6d9a3dcce..68fb029b1 100644 --- a/src/core/common/tasklet.hpp +++ b/src/core/common/tasklet.hpp @@ -38,9 +38,10 @@ #include -namespace ot { +#include "common/context.hpp" +#include "common/locator.hpp" -namespace Ip6 { class Ip6; } +namespace ot { class TaskletScheduler; @@ -58,7 +59,7 @@ class TaskletScheduler; * This class is used to represent a tasklet. * */ -class Tasklet +class Tasklet: public TaskletSchedulerLocator, public Context { friend class TaskletScheduler; @@ -66,10 +67,10 @@ public: /** * This function pointer is called when the tasklet is run. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aTasklet A reference to the tasklet being run. * */ - typedef void (*Handler)(void *aContext); + typedef void (*Handler)(Tasklet &aTasklet); /** * This constructor creates a tasklet instance. @@ -88,11 +89,9 @@ public: otError Post(void); private: - void RunTask(void) { mHandler(mContext); } + void RunTask(void) { mHandler(*this); } - TaskletScheduler &mScheduler; Handler mHandler; - void *mContext; Tasklet *mNext; }; @@ -134,14 +133,6 @@ public: */ void ProcessQueuedTasklets(void); - /** - * This method returns the pointer to the parent Ip6 structure. - * - * @returns The pointer to the parent Ip6 structure. - * - */ - Ip6::Ip6 *GetIp6(void); - private: Tasklet *PopTasklet(void); Tasklet *mHead; diff --git a/src/core/common/timer.hpp b/src/core/common/timer.hpp index a081ba287..ac5ef22e5 100644 --- a/src/core/common/timer.hpp +++ b/src/core/common/timer.hpp @@ -40,7 +40,9 @@ #include #include +#include "common/context.hpp" #include "common/debug.hpp" +#include "common/locator.hpp" #include "common/tasklet.hpp" namespace ot { @@ -133,7 +135,7 @@ private: * This class implements a timer. * */ -class Timer +class Timer: public TimerSchedulerLocator, public Context { friend class TimerScheduler; @@ -147,9 +149,10 @@ public: /** * This function pointer is called when the timer expires. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aTimer A reference to the expired timer instance. + * */ - typedef void (*Handler)(void *aContext); + typedef void (*Handler)(Timer &aTimer); /** * This constructor creates a timer instance. @@ -160,9 +163,9 @@ public: * */ Timer(TimerScheduler &aScheduler, Handler aHandler, void *aContext): - mScheduler(aScheduler), + TimerSchedulerLocator(aScheduler), + Context(aContext), mHandler(aHandler), - mContext(aContext), mFireTime(0), mNext(this) { } @@ -201,13 +204,17 @@ public: * (aDt must be smaller than or equal to kMaxDt). * */ - void StartAt(uint32_t aT0, uint32_t aDt) { assert(aDt <= kMaxDt); mFireTime = aT0 + aDt; mScheduler.Add(*this); } + void StartAt(uint32_t aT0, uint32_t aDt) { + assert(aDt <= kMaxDt); + mFireTime = aT0 + aDt; + GetTimerScheduler().Add(*this); + } /** * This method stops the timer. * */ - void Stop(void) { mScheduler.Remove(*this); } + void Stop(void) { GetTimerScheduler().Remove(*this); } /** * This static method returns the current time in milliseconds. @@ -245,11 +252,9 @@ private: */ bool DoesFireBefore(const Timer &aTimer); - void Fired(void) { mHandler(mContext); } + void Fired(void) { mHandler(*this); } - TimerScheduler &mScheduler; Handler mHandler; - void *mContext; uint32_t mFireTime; Timer *mNext; }; diff --git a/src/core/common/trickle_timer.cpp b/src/core/common/trickle_timer.cpp index f2cf95674..d71873c02 100644 --- a/src/core/common/trickle_timer.cpp +++ b/src/core/common/trickle_timer.cpp @@ -37,6 +37,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -49,7 +50,7 @@ TrickleTimer::TrickleTimer( #endif Handler aTransmitHandler, Handler aIntervalExpiredHandler, void *aContext) : - mTimer(aScheduler, HandleTimerFired, this), + Timer(aScheduler, HandleTimerFired, aContext), #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT k(aRedundancyConstant), c(0), @@ -61,8 +62,7 @@ TrickleTimer::TrickleTimer( t(0), mPhase(kPhaseDormant), mTransmitHandler(aTransmitHandler), - mIntervalExpiredHandler(aIntervalExpiredHandler), - mContext(aContext) + mIntervalExpiredHandler(aIntervalExpiredHandler) { } @@ -97,7 +97,7 @@ void TrickleTimer::Start(uint32_t aIntervalMin, uint32_t aIntervalMax, Mode aMod void TrickleTimer::Stop(void) { mPhase = kPhaseDormant; - mTimer.Stop(); + Timer::Stop(); } #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT @@ -117,7 +117,7 @@ void TrickleTimer::IndicateInconsistent(void) I = Imin; // Stop the existing timer - mTimer.Stop(); + Timer::Stop(); // Start a new interval StartNewInterval(); @@ -156,13 +156,12 @@ void TrickleTimer::StartNewInterval(void) } // Start the timer for 't' milliseconds from now - mTimer.Start(t); + Timer::Start(t); } -void TrickleTimer::HandleTimerFired(void *aContext) +void TrickleTimer::HandleTimerFired(Timer &aTimer) { - TrickleTimer *obj = static_cast(aContext); - obj->HandleTimerFired(); + static_cast(&aTimer)->HandleTimerFired(); } void TrickleTimer::HandleTimerFired(void) @@ -205,7 +204,7 @@ void TrickleTimer::HandleTimerFired(void) mPhase = kPhaseInterval; // Start the time for 'I - t' milliseconds - mTimer.Start(I - t); + Timer::Start(I - t); } } diff --git a/src/core/common/trickle_timer.hpp b/src/core/common/trickle_timer.hpp index 90e10b1dc..0d37399b0 100644 --- a/src/core/common/trickle_timer.hpp +++ b/src/core/common/trickle_timer.hpp @@ -34,6 +34,7 @@ #ifndef TRICKLE_TIMER_HPP_ #define TRICKLE_TIMER_HPP_ +#include "common/context.hpp" #include "common/timer.hpp" namespace ot { @@ -52,7 +53,7 @@ namespace ot { * This class implements a trickle timer. * */ -class TrickleTimer +class TrickleTimer: public Timer { public: @@ -69,12 +70,12 @@ public: /** * This function pointer is called when the timer expires. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aTimer A reference to the expired timer. * * @retval TRUE If the trickle timer should continue running. * @retval FALSE If the trickle timer should stop running. */ - typedef bool (*Handler)(void *aContext); + typedef bool (*Handler)(TrickleTimer &aTimer); /** * This constructor creates a trickle timer instance. @@ -110,6 +111,17 @@ public: */ void Start(uint32_t aIntervalMin, uint32_t aIntervalMax, Mode aMode); + /** + * This method start the trickle timer. + * + * @param[in] aStartTime The start time. + * @param[in] aIntervalMin The minimum interval for the timer, Imin. + * @param[in] aIntervalMax The maximum interval for the timer, Imax. + * @param[in] aMode The operating mode for the timer. + * + */ + void StartAt(uint32_t aStartTime, uint32_t aIntervalMin, uint32_t aIntervalMax, Mode aMode); + /** * This method stops the trickle timer. * @@ -131,14 +143,17 @@ public: void IndicateInconsistent(void); private: - bool TransmitFired(void) { return mTransmitHandler(mContext); } - bool IntervalExpiredFired(void) { return mIntervalExpiredHandler ? mIntervalExpiredHandler(mContext) : true; } + bool TransmitFired(void) { return mTransmitHandler(*this); } + bool IntervalExpiredFired(void) { return mIntervalExpiredHandler ? mIntervalExpiredHandler(*this) : true; } void StartNewInterval(void); - static void HandleTimerFired(void *aContext); + static void HandleTimerFired(Timer &aTimer); void HandleTimerFired(void); + // Shadow base class method to ensure it is hidden. + void StartAt(void) { } + typedef enum Phase { ///< Indicates we are currently not running @@ -149,8 +164,6 @@ private: kPhaseInterval = 3, } Phase; - Timer mTimer; - #ifdef ENABLE_TRICKLE_TIMER_SUPPRESSION_SUPPORT // Redundancy constant const uint32_t k; @@ -177,7 +190,6 @@ private: // Callback variables Handler mTransmitHandler; Handler mIntervalExpiredHandler; - void *mContext; }; /** diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index 7294bae39..461f3595d 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -114,12 +114,12 @@ void Mac::StartCsmaBackoff(void) } Mac::Mac(ThreadNetif &aThreadNetif): + ThreadNetifLocator(aThreadNetif), mMacTimer(aThreadNetif.GetIp6().mTimerScheduler, &Mac::HandleMacTimer, this), #if !OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_BACKOFF_TIMER mBackoffTimer(aThreadNetif.GetIp6().mTimerScheduler, &Mac::HandleBeginTransmit, this), #endif mReceiveTimer(aThreadNetif.GetIp6().mTimerScheduler, &Mac::HandleReceiveTimer, this), - mNetif(aThreadNetif), mShortAddress(kShortAddrInvalid), mPanId(kPanIdBroadcast), mChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL), @@ -168,11 +168,6 @@ Mac::Mac(ThreadNetif &aThreadNetif): otPlatRadioEnable(GetInstance()); } -otInstance *Mac::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError Mac::ActiveScan(uint32_t aScanChannels, uint16_t aScanDuration, ActiveScanHandler aHandler, void *aContext) { otError error; @@ -372,9 +367,9 @@ exit: return; } -void Mac::HandleEnergyScanSampleRssi(void *aContext) +void Mac::HandleEnergyScanSampleRssi(Tasklet &aTasklet) { - static_cast(aContext)->HandleEnergyScanSampleRssi(); + GetOwner(aTasklet).HandleEnergyScanSampleRssi(); } void Mac::HandleEnergyScanSampleRssi(void) @@ -667,12 +662,12 @@ void Mac::SendBeacon(Frame &aFrame) beaconPayload = reinterpret_cast(beacon->GetPayload()); - if (mNetif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_BEACONS) + if (GetNetif().GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_BEACONS) { beaconPayload->Init(); // set the Joining Permitted flag - mNetif.GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); + GetNetif().GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); if (numUnsecurePorts) { @@ -698,6 +693,7 @@ void Mac::SendBeacon(Frame &aFrame) void Mac::ProcessTransmitSecurity(Frame &aFrame) { + KeyManager &keyManager = GetNetif().GetKeyManager(); uint32_t frameCounter = 0; uint8_t securityLevel; uint8_t keyIdMode; @@ -717,19 +713,19 @@ void Mac::ProcessTransmitSecurity(Frame &aFrame) switch (keyIdMode) { case Frame::kKeyIdMode0: - key = mNetif.GetKeyManager().GetKek(); + key = keyManager.GetKek(); extAddress = &mExtAddress; if (!aFrame.IsARetransmission()) { - aFrame.SetFrameCounter(mNetif.GetKeyManager().GetKekFrameCounter()); - mNetif.GetKeyManager().IncrementKekFrameCounter(); + aFrame.SetFrameCounter(keyManager.GetKekFrameCounter()); + keyManager.IncrementKekFrameCounter(); } break; case Frame::kKeyIdMode1: - key = mNetif.GetKeyManager().GetCurrentMacKey(); + key = keyManager.GetCurrentMacKey(); extAddress = &mExtAddress; // If the frame is marked as a retransmission, the `Mac::Sender` which @@ -740,9 +736,9 @@ void Mac::ProcessTransmitSecurity(Frame &aFrame) if (!aFrame.IsARetransmission()) { - aFrame.SetFrameCounter(mNetif.GetKeyManager().GetMacFrameCounter()); - mNetif.GetKeyManager().IncrementMacFrameCounter(); - aFrame.SetKeyId((mNetif.GetKeyManager().GetCurrentKeySequence() & 0x7f) + 1); + aFrame.SetFrameCounter(keyManager.GetMacFrameCounter()); + keyManager.IncrementMacFrameCounter(); + aFrame.SetKeyId((keyManager.GetCurrentKeySequence() & 0x7f) + 1); } break; @@ -787,6 +783,11 @@ void Mac::HandleBeginTransmit(void *aContext) static_cast(aContext)->HandleBeginTransmit(); } +void Mac::HandleBeginTransmit(Timer &aTimer) +{ + GetOwner(aTimer).HandleBeginTransmit(); +} + void Mac::HandleBeginTransmit(void) { Frame &sendFrame(*mTxFrame); @@ -1002,7 +1003,7 @@ void Mac::TransmitDoneTask(otRadioFrame *aFrame, otRadioFrame *aAckFrame, otErro Neighbor *neighbor; framePending = ackFrame->GetFramePending(); - neighbor = mNetif.GetMle().GetNeighbor(addr); + neighbor = GetNetif().GetMle().GetNeighbor(addr); if (neighbor != NULL) { @@ -1124,9 +1125,9 @@ void Mac::RadioSleep(void) } } -void Mac::HandleMacTimer(void *aContext) +void Mac::HandleMacTimer(Timer &aTimer) { - static_cast(aContext)->HandleMacTimer(); + GetOwner(aTimer).HandleMacTimer(); } void Mac::HandleMacTimer(void) @@ -1189,9 +1190,9 @@ exit: return; } -void Mac::HandleReceiveTimer(void *aContext) +void Mac::HandleReceiveTimer(Timer &aTimer) { - static_cast(aContext)->HandleReceiveTimer(); + GetOwner(aTimer).HandleReceiveTimer(); } void Mac::HandleReceiveTimer(void) @@ -1322,6 +1323,7 @@ exit: otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neighbor *aNeighbor) { + KeyManager &keyManager = GetNetif().GetKeyManager(); otError error = OT_ERROR_NONE; uint8_t securityLevel; uint8_t keyIdMode; @@ -1351,7 +1353,7 @@ otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neig switch (keyIdMode) { case Frame::kKeyIdMode0: - VerifyOrExit((macKey = mNetif.GetKeyManager().GetKek()) != NULL, error = OT_ERROR_SECURITY); + VerifyOrExit((macKey = keyManager.GetKek()) != NULL, error = OT_ERROR_SECURITY); extAddress = &aSrcAddr.mExtAddress; break; @@ -1361,23 +1363,23 @@ otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neig aFrame.GetKeyId(keyid); keyid--; - if (keyid == (mNetif.GetKeyManager().GetCurrentKeySequence() & 0x7f)) + if (keyid == (keyManager.GetCurrentKeySequence() & 0x7f)) { // same key index - keySequence = mNetif.GetKeyManager().GetCurrentKeySequence(); - macKey = mNetif.GetKeyManager().GetCurrentMacKey(); + keySequence = keyManager.GetCurrentKeySequence(); + macKey = keyManager.GetCurrentMacKey(); } - else if (keyid == ((mNetif.GetKeyManager().GetCurrentKeySequence() - 1) & 0x7f)) + else if (keyid == ((keyManager.GetCurrentKeySequence() - 1) & 0x7f)) { // previous key index - keySequence = mNetif.GetKeyManager().GetCurrentKeySequence() - 1; - macKey = mNetif.GetKeyManager().GetTemporaryMacKey(keySequence); + keySequence = keyManager.GetCurrentKeySequence() - 1; + macKey = keyManager.GetTemporaryMacKey(keySequence); } - else if (keyid == ((mNetif.GetKeyManager().GetCurrentKeySequence() + 1) & 0x7f)) + else if (keyid == ((keyManager.GetCurrentKeySequence() + 1) & 0x7f)) { // next key index - keySequence = mNetif.GetKeyManager().GetCurrentKeySequence() + 1; - macKey = mNetif.GetKeyManager().GetTemporaryMacKey(keySequence); + keySequence = keyManager.GetCurrentKeySequence() + 1; + macKey = keyManager.GetTemporaryMacKey(keySequence); } else { @@ -1444,9 +1446,9 @@ otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neig aNeighbor->SetLinkFrameCounter(frameCounter + 1); - if (keySequence > mNetif.GetKeyManager().GetCurrentKeySequence()) + if (keySequence > keyManager.GetCurrentKeySequence()) { - mNetif.GetKeyManager().SetCurrentKeySequence(keySequence); + keyManager.SetCurrentKeySequence(keySequence); } } @@ -1506,7 +1508,7 @@ void Mac::ReceiveDoneTask(Frame *aFrame, otError aError) SuccessOrExit(error = aFrame->ValidatePsdu()); aFrame->GetSrcAddr(srcaddr); - neighbor = mNetif.GetMle().GetNeighbor(srcaddr); + neighbor = GetNetif().GetMle().GetNeighbor(srcaddr); switch (srcaddr.mLength) { @@ -1857,7 +1859,7 @@ bool Mac::IsBeaconJoinable(void) uint8_t numUnsecurePorts; bool joinable = false; - mNetif.GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); + GetNetif().GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); if (numUnsecurePorts) { @@ -1872,5 +1874,16 @@ bool Mac::IsBeaconJoinable(void) } #endif // OPENTHREAD_CONFIG_ENABLE_BEACON_RSP_IF_JOINABLE +Mac &Mac::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Mac &mac = *static_cast(aContext.GetContext()); +#else + Mac &mac = otGetInstance()->mThreadNetif.GetMac(); + OT_UNUSED_VARIABLE(aContext); +#endif + return mac; +} + } // namespace Mac } // namespace ot diff --git a/src/core/mac/mac.hpp b/src/core/mac/mac.hpp index 5df2511f1..8e744b347 100644 --- a/src/core/mac/mac.hpp +++ b/src/core/mac/mac.hpp @@ -37,6 +37,8 @@ #include #include "openthread-core-config.h" +#include "common/context.hpp" +#include "common/locator.hpp" #include "common/tasklet.hpp" #include "common/timer.hpp" #include "mac/mac_blacklist.hpp" @@ -101,7 +103,7 @@ enum * This class implements a MAC receiver client. * */ -class Receiver +class Receiver: public Context { friend class Mac; @@ -109,20 +111,20 @@ public: /** * This function pointer is called when a MAC frame is received. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aReceiver A reference to the MAC receiver client object. * @param[in] aFrame A reference to the MAC frame. * */ - typedef void (*ReceiveFrameHandler)(void *aContext, Frame &aFrame); + typedef void (*ReceiveFrameHandler)(Receiver &aReceiver, Frame &aFrame); /** * This function pointer is called on a data request command (data poll) timeout, i.e., when the ack in response to * a data request command indicated a frame is pending, but no frame was received after `kDataPollTimeout` interval. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aReceiver A reference to the MAC receiver client object. * */ - typedef void (*DataPollTimeoutHandler)(void *aContext); + typedef void (*DataPollTimeoutHandler)(Receiver &aReceiver); /** * This constructor creates a MAC receiver client. @@ -132,24 +134,24 @@ public: * @param[in] aContext A pointer to arbitrary context information. * */ - Receiver(ReceiveFrameHandler aReceiveFrameHandler, DataPollTimeoutHandler aPollTimeoutHandler, void *aContext) { - mReceiveFrameHandler = aReceiveFrameHandler; - mPollTimeoutHandler = aPollTimeoutHandler; - mContext = aContext; - mNext = NULL; + Receiver(ReceiveFrameHandler aReceiveFrameHandler, DataPollTimeoutHandler aPollTimeoutHandler, void *aContext): + Context(aContext), + mReceiveFrameHandler(aReceiveFrameHandler), + mPollTimeoutHandler(aPollTimeoutHandler), + mNext(NULL) { } private: - void HandleReceivedFrame(Frame &frame) { mReceiveFrameHandler(mContext, frame); } + void HandleReceivedFrame(Frame &frame) { mReceiveFrameHandler(*this, frame); } + void HandleDataPollTimeout(void) { if (mPollTimeoutHandler != NULL) { - mPollTimeoutHandler(mContext); + mPollTimeoutHandler(*this); } } ReceiveFrameHandler mReceiveFrameHandler; DataPollTimeoutHandler mPollTimeoutHandler; - void *mContext; Receiver *mNext; }; @@ -157,7 +159,7 @@ private: * This class implements a MAC sender client. * */ -class Sender +class Sender: public Context { friend class Mac; @@ -165,21 +167,21 @@ public: /** * This function pointer is called when the MAC is about to transmit the frame. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aSender A reference to the MAC sender client object. * @param[in] aFrame A reference to the MAC frame buffer. * */ - typedef otError(*FrameRequestHandler)(void *aContext, Frame &aFrame); + typedef otError(*FrameRequestHandler)(Sender &aSender, Frame &aFrame); /** * This function pointer is called when the MAC is done sending the frame. * - * @param[in] aContext A pointer to arbitrary context information. + * @param[in] aSender A reference to the MAC sender client object. * @param[in] aFrame A reference to the MAC frame buffer that was sent. * @param[in] aError The status of the last MSDU transmission. * */ - typedef void (*SentFrameHandler)(void *aContext, Frame &aFrame, otError aError); + typedef void (*SentFrameHandler)(Sender &aSender, Frame &aFrame, otError aError); /** * This constructor creates a MAC sender client. @@ -189,20 +191,19 @@ public: * @param[in] aContext A pointer to arbitrary context information. * */ - Sender(FrameRequestHandler aFrameRequestHandler, SentFrameHandler aSentFrameHandler, void *aContext) { - mFrameRequestHandler = aFrameRequestHandler; - mSentFrameHandler = aSentFrameHandler; - mContext = aContext; - mNext = NULL; + Sender(FrameRequestHandler aFrameRequestHandler, SentFrameHandler aSentFrameHandler, void *aContext): + Context(aContext), + mFrameRequestHandler(aFrameRequestHandler), + mSentFrameHandler(aSentFrameHandler), + mNext(NULL) { } private: - otError HandleFrameRequest(Frame &frame) { return mFrameRequestHandler(mContext, frame); } - void HandleSentFrame(Frame &frame, otError error) { mSentFrameHandler(mContext, frame, error); } + otError HandleFrameRequest(Frame &frame) { return mFrameRequestHandler(*this, frame); } + void HandleSentFrame(Frame &frame, otError error) { mSentFrameHandler(*this, frame, error); } FrameRequestHandler mFrameRequestHandler; SentFrameHandler mSentFrameHandler; - void *mContext; Sender *mNext; }; @@ -210,7 +211,7 @@ private: * This class implements the IEEE 802.15.4 MAC. * */ -class Mac +class Mac: public ThreadNetifLocator { public: /** @@ -221,14 +222,6 @@ public: */ explicit Mac(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This function pointer is called on receiving an IEEE 802.15.4 Beacon during an Active Scan. * @@ -256,7 +249,7 @@ public: * @param[out] aResult A reference to `otActiveScanResult` where the result is stored. * * @retval OT_ERROR_NONE Successfully converted the beacon into active scan result. - * @retavl OT_ERROR_INVALID_ARGS The @a aBeaconFrame was NULL. + * @retval OT_ERROR_INVALID_ARGS The @a aBeaconFrame was NULL. * @retval OT_ERROR_PARSE Failed parsing the beacon frame. * */ @@ -679,13 +672,14 @@ private: void StartEnergyScan(void); otError HandleMacCommand(Frame &aFrame); - static void HandleMacTimer(void *aContext); + static void HandleMacTimer(Timer &aTimer); void HandleMacTimer(void); static void HandleBeginTransmit(void *aContext); + static void HandleBeginTransmit(Timer &aTimer); void HandleBeginTransmit(void); - static void HandleReceiveTimer(void *aContext); + static void HandleReceiveTimer(Timer &aTimer); void HandleReceiveTimer(void); - static void HandleEnergyScanSampleRssi(void *aContext); + static void HandleEnergyScanSampleRssi(Tasklet &aTasklet); void HandleEnergyScanSampleRssi(void); void StartCsmaBackoff(void); @@ -695,14 +689,14 @@ private: otError RadioReceive(uint8_t aChannel); void RadioSleep(void); + static Mac &GetOwner(const Context &aContext); + Timer mMacTimer; #if !OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_BACKOFF_TIMER Timer mBackoffTimer; #endif Timer mReceiveTimer; - ThreadNetif &mNetif; - ExtAddress mExtAddress; ShortAddress mShortAddress; PanId mPanId; diff --git a/src/core/meshcop/announce_begin_client.cpp b/src/core/meshcop/announce_begin_client.cpp index 349c4a6a1..f4902c7be 100644 --- a/src/core/meshcop/announce_begin_client.cpp +++ b/src/core/meshcop/announce_begin_client.cpp @@ -39,6 +39,7 @@ #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -52,16 +53,11 @@ namespace ot { -AnnounceBeginClient::AnnounceBeginClient(ThreadNetif &aThreadNetif) : - mNetif(aThreadNetif) +AnnounceBeginClient::AnnounceBeginClient(ThreadNetif &aThreadNetif): + ThreadNetifLocator(aThreadNetif) { } -otInstance *AnnounceBeginClient::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, const Ip6::Address &aAddress) { @@ -75,7 +71,7 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, uint8_t aCount, Ip6::MessageInfo messageInfo; Message *message = NULL; - VerifyOrExit(mNetif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(GetNetif().GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -83,11 +79,11 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, uint8_t aCount, header.AppendUriPathOptions(OT_URI_PATH_ANNOUNCE_BEGIN); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(GetNetif().GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); sessionId.Init(); - sessionId.SetCommissionerSessionId(mNetif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(GetNetif().GetCommissioner().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -102,12 +98,12 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, uint8_t aCount, period.SetPeriod(aPeriod); SuccessOrExit(error = message->Append(&period, sizeof(period))); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(GetNetif().GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = GetNetif().GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent announce begin query"); diff --git a/src/core/meshcop/announce_begin_client.hpp b/src/core/meshcop/announce_begin_client.hpp index 38780e03a..6459ad415 100644 --- a/src/core/meshcop/announce_begin_client.hpp +++ b/src/core/meshcop/announce_begin_client.hpp @@ -35,19 +35,18 @@ #define ANNOUNCE_BEGIN_CLIENT_HPP_ #include "openthread-core-config.h" +#include "common/locator.hpp" #include "coap/coap.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" namespace ot { -class ThreadNetif; - /** * This class implements handling Announce Begin Requests. * */ -class AnnounceBeginClient +class AnnounceBeginClient: public ThreadNetifLocator { public: /** @@ -56,14 +55,6 @@ public: */ AnnounceBeginClient(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method sends a Announce Begin message. * @@ -76,9 +67,6 @@ public: * */ otError SendRequest(uint32_t aChannelMask, uint8_t aCount, uint16_t mPeriod, const Ip6::Address &aAddress); - -private: - ThreadNetif &mNetif; }; /** diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index 9d299431d..fcb83b6e1 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -43,6 +43,7 @@ #include #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/encoding.hpp" #include "common/logging.hpp" @@ -62,6 +63,7 @@ namespace ot { namespace MeshCoP { Commissioner::Commissioner(ThreadNetif &aThreadNetif): + ThreadNetifLocator(aThreadNetif), mAnnounceBegin(aThreadNetif), mEnergyScan(aThreadNetif), mPanIdQuery(aThreadNetif), @@ -74,29 +76,27 @@ Commissioner::Commissioner(ThreadNetif &aThreadNetif): mTransmitAttempts(0), mRelayReceive(OT_URI_PATH_RELAY_RX, &Commissioner::HandleRelayReceive, this), mDatasetChanged(OT_URI_PATH_DATASET_CHANGED, &Commissioner::HandleDatasetChanged, this), - mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this), - mNetif(aThreadNetif) + mJoinerFinalize(OT_URI_PATH_JOINER_FINALIZE, &Commissioner::HandleJoinerFinalize, this) { memset(mJoiners, 0, sizeof(mJoiners)); } -otInstance *Commissioner::GetInstance(void) -{ - return mNetif.GetInstance(); -} - void Commissioner::AddCoapResources(void) { - mNetif.GetCoap().AddResource(mRelayReceive); - mNetif.GetCoap().AddResource(mDatasetChanged); - mNetif.GetCoapSecure().AddResource(mJoinerFinalize); + ThreadNetif &netif = GetNetif(); + + netif.GetCoap().AddResource(mRelayReceive); + netif.GetCoap().AddResource(mDatasetChanged); + netif.GetCoapSecure().AddResource(mJoinerFinalize); } void Commissioner::RemoveCoapResources(void) { - mNetif.GetCoap().RemoveResource(mRelayReceive); - mNetif.GetCoap().RemoveResource(mDatasetChanged); - mNetif.GetCoapSecure().RemoveResource(mJoinerFinalize); + ThreadNetif &netif = GetNetif(); + + netif.GetCoap().RemoveResource(mRelayReceive); + netif.GetCoap().RemoveResource(mDatasetChanged); + netif.GetCoapSecure().RemoveResource(mJoinerFinalize); } otError Commissioner::Start(void) @@ -106,7 +106,7 @@ otError Commissioner::Start(void) otLogFuncEntry(); VerifyOrExit(mState == OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); - SuccessOrExit(error = mNetif.GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT, SendRelayTransmit, this)); + SuccessOrExit(error = GetNetif().GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT, SendRelayTransmit, this)); mState = OT_COMMISSIONER_STATE_PETITION; mTransmitAttempts = 0; @@ -125,7 +125,7 @@ otError Commissioner::Stop(void) otLogFuncEntry(); VerifyOrExit(mState != OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); - mNetif.GetCoapSecure().Stop(); + GetNetif().GetCoapSecure().Stop(); mState = OT_COMMISSIONER_STATE_DISABLED; RemoveCoapResources(); @@ -133,7 +133,7 @@ otError Commissioner::Stop(void) mTimer.Stop(); - mNetif.GetDtls().Stop(); + GetNetif().GetDtls().Stop(); SendKeepAlive(); @@ -301,7 +301,7 @@ exit: otError Commissioner::SetProvisioningUrl(const char *aProvisioningUrl) { - return mNetif.GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); + return GetNetif().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); } uint16_t Commissioner::GetSessionId(void) const @@ -314,9 +314,9 @@ otCommissionerState Commissioner::GetState(void) const return mState; } -void Commissioner::HandleTimer(void *aContext) +void Commissioner::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void Commissioner::HandleTimer(void) @@ -336,9 +336,9 @@ void Commissioner::HandleTimer(void) } } -void Commissioner::HandleJoinerExpirationTimer(void *aContext) +void Commissioner::HandleJoinerExpirationTimer(Timer &aTimer) { - static_cast(aContext)->HandleJoinerExpirationTimer(); + GetOwner(aTimer).HandleJoinerExpirationTimer(); } void Commissioner::HandleJoinerExpirationTimer(void) @@ -399,6 +399,7 @@ void Commissioner::UpdateJoinerExpirationTimer(void) otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t aLength) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message; @@ -416,7 +417,7 @@ otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, header.SetPayloadMarker(); } - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); if (aLength > 0) { @@ -426,11 +427,11 @@ otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, SuccessOrExit(error = message->Append(aTlvs, aLength)); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleMgmtCommissionerGetResponse, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, + Commissioner::HandleMgmtCommissionerGetResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent MGMT_COMMISSIONER_GET.req to leader"); @@ -471,6 +472,7 @@ exit: otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDataset &aDataset, const uint8_t *aTlvs, uint8_t aLength) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message; @@ -483,7 +485,7 @@ otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDatase header.AppendUriPathOptions(OT_URI_PATH_COMMISSIONER_SET); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); if (aDataset.mIsLocatorSet) { @@ -529,11 +531,11 @@ otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDatase message->SetLength(message->GetLength() - 1); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleMgmtCommissionerSetResponse, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, + Commissioner::HandleMgmtCommissionerSetResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent MGMT_COMMISSIONER_SET.req to leader"); @@ -573,6 +575,7 @@ exit: otError Commissioner::SendPetition(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message = NULL; @@ -588,18 +591,18 @@ otError Commissioner::SendPetition(void) header.AppendUriPathOptions(OT_URI_PATH_LEADER_PETITION); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); commissionerId.Init(); commissionerId.SetCommissionerId("OpenThread Commissioner"); SuccessOrExit(error = message->Append(&commissionerId, sizeof(Tlv) + commissionerId.GetLength())); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleLeaderPetitionResponse, this)); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, + Commissioner::HandleLeaderPetitionResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent petition"); @@ -673,6 +676,7 @@ exit: otError Commissioner::SendKeepAlive(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message = NULL; @@ -687,7 +691,7 @@ otError Commissioner::SendKeepAlive(void) header.AppendUriPathOptions(OT_URI_PATH_LEADER_KEEP_ALIVE); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); state.Init(); state.SetState(mState == OT_COMMISSIONER_STATE_ACTIVE ? StateTlv::kAccept : StateTlv::kReject); @@ -697,11 +701,11 @@ otError Commissioner::SendKeepAlive(void) sessionId.SetCommissionerSessionId(mSessionId); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleLeaderKeepAliveResponse, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, + Commissioner::HandleLeaderKeepAliveResponse, this)); otLogInfoMeshCoP(GetInstance(), "sent keep alive"); @@ -766,6 +770,7 @@ void Commissioner::HandleRelayReceive(void *aContext, otCoapHeader *aHeader, otM void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error; JoinerUdpPortTlv joinerPort; JoinerIidTlv joinerIid; @@ -794,7 +799,7 @@ void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, SuccessOrExit(error = Tlv::GetValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length)); VerifyOrExit(length <= aMessage.GetLength() - offset, error = OT_ERROR_PARSE); - if (!mNetif.GetCoapSecure().IsConnectionActive()) + if (!netif.GetCoapSecure().IsConnectionActive()) { memcpy(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)); mJoinerIid[0] ^= 0x2; @@ -809,8 +814,8 @@ void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, if (mJoiners[i].mAny || !memcmp(&mJoiners[i].mExtAddress, mJoinerIid, sizeof(mJoiners[i].mExtAddress))) { - error = mNetif.GetCoapSecure().SetPsk(reinterpret_cast(mJoiners[i].mPsk), - static_cast(strlen(mJoiners[i].mPsk))); + error = netif.GetCoapSecure().SetPsk(reinterpret_cast(mJoiners[i].mPsk), + static_cast(strlen(mJoiners[i].mPsk))); SuccessOrExit(error); otLogInfoMeshCoP(GetInstance(), "found joiner, starting new session"); enableJoiner = true; @@ -835,11 +840,11 @@ void Commissioner::HandleRelayReceive(Coap::Header &aHeader, Message &aMessage, aMessage.SetOffset(offset); SuccessOrExit(error = aMessage.SetLength(offset + length)); - joinerMessageInfo.SetPeerAddr(mNetif.GetMle().GetMeshLocal64()); + joinerMessageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); - mNetif.GetCoapSecure().Receive(aMessage, joinerMessageInfo); + netif.GetCoapSecure().Receive(aMessage, joinerMessageInfo); exit: OT_UNUSED_VARIABLE(aMessageInfo); @@ -863,7 +868,7 @@ void Commissioner::HandleDatasetChanged(Coap::Header &aHeader, Message &aMessage otLogInfoMeshCoP(GetInstance(), "received dataset changed"); OT_UNUSED_VARIABLE(aMessage); - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset changed acknowledgment"); @@ -890,8 +895,8 @@ void Commissioner::HandleJoinerFinalize(Coap::Header &aHeader, Message &aMessage if (Tlv::GetTlv(aMessage, Tlv::kProvisioningUrl, sizeof(provisioningUrl), provisioningUrl) == OT_ERROR_NONE) { - if (provisioningUrl.GetLength() != mNetif.GetDtls().mProvisioningUrl.GetLength() || - memcmp(provisioningUrl.GetProvisioningUrl(), mNetif.GetDtls().mProvisioningUrl.GetProvisioningUrl(), + if (provisioningUrl.GetLength() != GetNetif().GetDtls().mProvisioningUrl.GetLength() || + memcmp(provisioningUrl.GetProvisioningUrl(), GetNetif().GetDtls().mProvisioningUrl.GetProvisioningUrl(), provisioningUrl.GetLength()) != 0) { state = StateTlv::kReject; @@ -916,6 +921,7 @@ exit: void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, StateTlv::State aState) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; Ip6::MessageInfo joinerMessageInfo; @@ -928,7 +934,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoapSecure(), responseHeader)) != NULL, + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeJoinerFinalizeResponse); @@ -937,7 +943,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, stateTlv.SetState(aState); SuccessOrExit(error = message->Append(&stateTlv, sizeof(stateTlv))); - joinerMessageInfo.SetPeerAddr(mNetif.GetMle().GetMeshLocal64()); + joinerMessageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); @@ -949,7 +955,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Header &aRequestHeader, message->GetLength() - responseHeader.GetLength()); #endif - SuccessOrExit(error = mNetif.GetCoapSecure().SendMessage(*message, joinerMessageInfo)); + SuccessOrExit(error = netif.GetCoapSecure().SendMessage(*message, joinerMessageInfo)); memcpy(extAddr.m8, mJoinerIid, sizeof(extAddr.m8)); extAddr.SetLocal(!extAddr.IsLocal()); @@ -974,7 +980,7 @@ otError Commissioner::SendRelayTransmit(void *aContext, Message &aMessage, const otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - OT_UNUSED_VARIABLE(aMessageInfo); + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; JoinerUdpPortTlv udpPort; @@ -985,13 +991,15 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf uint16_t offset; Ip6::MessageInfo messageInfo; + OT_UNUSED_VARIABLE(aMessageInfo); + otLogFuncEntry(); header.Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); header.AppendUriPathOptions(OT_URI_PATH_RELAY_TX); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); udpPort.Init(); udpPort.SetUdpPort(mJoinerPort); @@ -1009,7 +1017,7 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf { JoinerRouterKekTlv kek; kek.Init(); - kek.SetKek(mNetif.GetKeyManager().GetKek()); + kek.SetKek(netif.GetKeyManager().GetKek()); SuccessOrExit(error = message->Append(&kek, sizeof(kek))); } @@ -1020,12 +1028,12 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf message->SetLength(offset + aMessage.GetLength()); aMessage.CopyTo(0, offset, aMessage.GetLength(), *message); - messageInfo.SetPeerAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(mJoinerRloc); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); aMessage.Free(); @@ -1068,6 +1076,17 @@ exit: return error; } +Commissioner &Commissioner::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Commissioner &commissioner = *static_cast(aContext.GetContext()); +#else + Commissioner &commissioner = otGetThreadNetif().GetCommissioner(); + OT_UNUSED_VARIABLE(aContext); +#endif + return commissioner; +} + } // namespace MeshCoP } // namespace ot diff --git a/src/core/meshcop/commissioner.hpp b/src/core/meshcop/commissioner.hpp index 8ac4899e6..7e82cb5ec 100644 --- a/src/core/meshcop/commissioner.hpp +++ b/src/core/meshcop/commissioner.hpp @@ -39,6 +39,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" #include "coap/coap_secure.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" #include "meshcop/announce_begin_client.hpp" @@ -54,7 +55,7 @@ class ThreadNetif; namespace MeshCoP { -class Commissioner +class Commissioner: public ThreadNetifLocator { public: /** @@ -65,14 +66,6 @@ public: */ Commissioner(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method starts the Commissioner service. * @@ -219,10 +212,10 @@ private: void AddCoapResources(void); void RemoveCoapResources(void); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); - static void HandleJoinerExpirationTimer(void *aContext); + static void HandleJoinerExpirationTimer(Timer &aTimer); void HandleJoinerExpirationTimer(void); void UpdateJoinerExpirationTimer(void); @@ -265,6 +258,8 @@ private: otError SendPetition(void); otError SendKeepAlive(void); + static Commissioner &GetOwner(const Context &aContext); + otCommissionerState mState; struct Joiner @@ -293,8 +288,6 @@ private: Coap::Resource mRelayReceive; Coap::Resource mDatasetChanged; Coap::Resource mJoinerFinalize; - - ThreadNetif &mNetif; }; } // namespace MeshCoP diff --git a/src/core/meshcop/dataset.cpp b/src/core/meshcop/dataset.cpp index e9d03e3dd..ca788c18b 100644 --- a/src/core/meshcop/dataset.cpp +++ b/src/core/meshcop/dataset.cpp @@ -40,6 +40,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/settings.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -49,9 +50,9 @@ namespace ot { namespace MeshCoP { Dataset::Dataset(otInstance *aInstance, const Tlv::Type aType) : + InstanceLocator(aInstance), mType(aType), - mLength(0), - mInstance(aInstance) + mLength(0) { } @@ -61,7 +62,7 @@ void Dataset::Clear(bool isLocal) if (isLocal) { - otPlatSettingsDelete(mInstance, GetSettingsKey(), -1); + otPlatSettingsDelete(GetInstance(), GetSettingsKey(), -1); } } @@ -436,7 +437,7 @@ otError Dataset::Restore(void) otError error; uint16_t length = sizeof(mTlvs); - error = otPlatSettingsGet(mInstance, GetSettingsKey(), 0, mTlvs, &length); + error = otPlatSettingsGet(GetInstance(), GetSettingsKey(), 0, mTlvs, &length); mLength = (error == OT_ERROR_NONE) ? length : 0; return error; @@ -449,11 +450,11 @@ otError Dataset::Store(void) if (mLength == 0) { - error = otPlatSettingsDelete(mInstance, key, 0); + error = otPlatSettingsDelete(GetInstance(), key, 0); } else { - error = otPlatSettingsSet(mInstance, key, mTlvs, mLength); + error = otPlatSettingsSet(GetInstance(), key, mTlvs, mLength); } return error; diff --git a/src/core/meshcop/dataset.hpp b/src/core/meshcop/dataset.hpp index 494593d20..de2d81d56 100644 --- a/src/core/meshcop/dataset.hpp +++ b/src/core/meshcop/dataset.hpp @@ -35,13 +35,14 @@ #ifndef MESHCOP_DATASET_HPP_ #define MESHCOP_DATASET_HPP_ +#include "common/locator.hpp" #include "common/message.hpp" #include "meshcop/meshcop_tlvs.hpp" namespace ot { namespace MeshCoP { -class Dataset +class Dataset: public InstanceLocator { public: enum @@ -193,7 +194,6 @@ private: Tlv::Type mType; ///< Active or Pending uint8_t mTlvs[kMaxSize]; ///< The Dataset buffer uint16_t mLength; ///< The number of valid bytes in @var mTlvs - otInstance *mInstance; ///< The pointer to an OpenThread instance }; } // namespace MeshCoP diff --git a/src/core/meshcop/dataset_manager.cpp b/src/core/meshcop/dataset_manager.cpp index 9a5409072..b56082624 100644 --- a/src/core/meshcop/dataset_manager.cpp +++ b/src/core/meshcop/dataset_manager.cpp @@ -62,29 +62,25 @@ namespace ot { namespace MeshCoP { DatasetManager::DatasetManager(ThreadNetif &aThreadNetif, const Tlv::Type aType, const char *aUriSet, - const char *aUriGet): + const char *aUriGet, Timer::Handler aTimerHander): + ThreadNetifLocator(aThreadNetif), mLocal(aThreadNetif.GetInstance(), aType), mNetwork(aThreadNetif.GetInstance(), aType), - mNetif(aThreadNetif), - mTimer(aThreadNetif.GetIp6().mTimerScheduler, &DatasetManager::HandleTimer, this), + mTimer(aThreadNetif.GetIp6().mTimerScheduler, aTimerHander, this), mUriSet(aUriSet), mUriGet(aUriGet) { } -otInstance *DatasetManager::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError DatasetManager::ApplyConfiguration(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Dataset *dataset; const Tlv *cur; const Tlv *end; - dataset = mNetif.GetMle().IsAttached() ? &mNetwork : &mLocal; + dataset = netif.GetMle().IsAttached() ? &mNetwork : &mLocal; cur = reinterpret_cast(dataset->GetBytes()); end = reinterpret_cast(dataset->GetBytes() + dataset->GetSize()); @@ -96,21 +92,21 @@ otError DatasetManager::ApplyConfiguration(void) case Tlv::kChannel: { const ChannelTlv *channel = static_cast(cur); - mNetif.GetMac().SetChannel(static_cast(channel->GetChannel())); + netif.GetMac().SetChannel(static_cast(channel->GetChannel())); break; } case Tlv::kPanId: { const PanIdTlv *panid = static_cast(cur); - mNetif.GetMac().SetPanId(panid->GetPanId()); + netif.GetMac().SetPanId(panid->GetPanId()); break; } case Tlv::kExtendedPanId: { const ExtendedPanIdTlv *extpanid = static_cast(cur); - mNetif.GetMac().SetExtendedPanId(extpanid->GetExtendedPanId()); + netif.GetMac().SetExtendedPanId(extpanid->GetExtendedPanId()); break; } @@ -120,14 +116,14 @@ otError DatasetManager::ApplyConfiguration(void) otNetworkName networkName; memset(networkName.m8, 0, sizeof(networkName)); memcpy(networkName.m8, name->GetNetworkName(), name->GetLength()); - mNetif.GetMac().SetNetworkName(networkName.m8); + netif.GetMac().SetNetworkName(networkName.m8); break; } case Tlv::kNetworkMasterKey: { const NetworkMasterKeyTlv *key = static_cast(cur); - mNetif.GetKeyManager().SetMasterKey(key->GetNetworkMasterKey()); + netif.GetKeyManager().SetMasterKey(key->GetNetworkMasterKey()); break; } @@ -136,7 +132,7 @@ otError DatasetManager::ApplyConfiguration(void) case Tlv::kPSKc: { const PSKcTlv *pskc = static_cast(cur); - mNetif.GetKeyManager().SetPSKc(pskc->GetPSKc()); + netif.GetKeyManager().SetPSKc(pskc->GetPSKc()); break; } @@ -145,15 +141,15 @@ otError DatasetManager::ApplyConfiguration(void) case Tlv::kMeshLocalPrefix: { const MeshLocalPrefixTlv *prefix = static_cast(cur); - mNetif.GetMle().SetMeshLocalPrefix(prefix->GetMeshLocalPrefix()); + netif.GetMle().SetMeshLocalPrefix(prefix->GetMeshLocalPrefix()); break; } case Tlv::kSecurityPolicy: { const SecurityPolicyTlv *securityPolicy = static_cast(cur); - mNetif.GetKeyManager().SetKeyRotation(securityPolicy->GetRotationTime()); - mNetif.GetKeyManager().SetSecurityPolicyFlags(securityPolicy->GetFlags()); + netif.GetKeyManager().SetKeyRotation(securityPolicy->GetRotationTime()); + netif.GetKeyManager().SetSecurityPolicyFlags(securityPolicy->GetFlags()); break; } @@ -172,13 +168,14 @@ otError DatasetManager::ApplyConfiguration(void) #if OPENTHREAD_FTD otError DatasetManager::Set(const otOperationalDataset &aDataset, uint8_t &aFlags) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; SuccessOrExit(error = mLocal.Set(aDataset)); mLocal.Store(); aFlags = kFlagLocalUpdated; - switch (mNetif.GetMle().GetRole()) + switch (netif.GetMle().GetRole()) { case OT_DEVICE_ROLE_CHILD: case OT_DEVICE_ROLE_ROUTER: @@ -188,8 +185,8 @@ otError DatasetManager::Set(const otOperationalDataset &aDataset, uint8_t &aFlag case OT_DEVICE_ROLE_LEADER: mNetwork = mLocal; aFlags |= kFlagNetworkUpdated; - mNetif.GetNetworkDataLeader().IncrementVersion(); - mNetif.GetNetworkDataLeader().IncrementStableVersion(); + netif.GetNetworkDataLeader().IncrementVersion(); + netif.GetNetworkDataLeader().IncrementStableVersion(); break; default: @@ -257,27 +254,23 @@ void DatasetManager::HandleNetworkUpdate(uint8_t &aFlags) } } -void DatasetManager::HandleTimer(void *aContext) -{ - static_cast(aContext)->HandleTimer(); -} - void DatasetManager::HandleTimer(void) { + ThreadNetif &netif = GetNetif(); const Timestamp *localActiveTimestamp; const Timestamp *pendingActiveTimestamp; const ActiveTimestampTlv *tlv; - localActiveTimestamp = mNetif.GetActiveDataset().GetLocal().GetTimestamp(); + localActiveTimestamp = netif.GetActiveDataset().GetLocal().GetTimestamp(); VerifyOrExit(localActiveTimestamp != NULL); - VerifyOrExit(mNetif.GetMle().IsAttached()); + VerifyOrExit(netif.GetMle().IsAttached()); VerifyOrExit(mLocal.Compare(mNetwork) < 0); Register(); - tlv = static_cast(mNetif.GetPendingDataset().GetNetwork().Get(Tlv::kActiveTimestamp)); + tlv = static_cast(netif.GetPendingDataset().GetNetwork().Get(Tlv::kActiveTimestamp)); pendingActiveTimestamp = static_cast(tlv); if (pendingActiveTimestamp != NULL && @@ -297,6 +290,7 @@ exit: otError DatasetManager::Register(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message; @@ -313,14 +307,14 @@ otError DatasetManager::Register(void) pending->UpdateDelayTimer(); } - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Append(mLocal.GetBytes(), mLocal.GetSize())); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset to leader"); @@ -361,6 +355,7 @@ void DatasetManager::Get(Coap::Header &aHeader, Message &aMessage, const Ip6::Me #if OPENTHREAD_FTD otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); Tlv tlv; Timestamp *timestamp; uint16_t offset = aMessage.GetOffset(); @@ -387,7 +382,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: pendingTimestamp.SetLength(0); sessionId.SetLength(0); - VerifyOrExit(mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, state = StateTlv::kReject); + VerifyOrExit(netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, state = StateTlv::kReject); // verify that TLV data size is less than maximum TLV value size while (offset < aMessage.GetLength()) @@ -430,7 +425,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: channel.GetChannel() <= OT_RADIO_CHANNEL_MAX, state = StateTlv::kReject); - if (channel.GetChannel() != mNetif.GetMac().GetChannel()) + if (channel.GetChannel() != netif.GetMac().GetChannel()) { doesAffectConnectivity = true; } @@ -439,14 +434,14 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: // check PAN ID if (Tlv::GetTlv(aMessage, Tlv::kPanId, sizeof(panId), panId) == OT_ERROR_NONE && panId.IsValid() && - panId.GetPanId() != mNetif.GetMac().GetPanId()) + panId.GetPanId() != netif.GetMac().GetPanId()) { doesAffectConnectivity = true; } // check mesh local prefix if (Tlv::GetTlv(aMessage, Tlv::kMeshLocalPrefix, sizeof(meshLocalPrefix), meshLocalPrefix) == OT_ERROR_NONE && - memcmp(meshLocalPrefix.GetMeshLocalPrefix(), mNetif.GetMle().GetMeshLocalPrefix(), + memcmp(meshLocalPrefix.GetMeshLocalPrefix(), netif.GetMle().GetMeshLocalPrefix(), meshLocalPrefix.GetLength())) { doesAffectConnectivity = true; @@ -454,7 +449,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: // check network master key if (Tlv::GetTlv(aMessage, Tlv::kNetworkMasterKey, sizeof(masterKey), masterKey) == OT_ERROR_NONE && - memcmp(&masterKey.GetNetworkMasterKey(), &mNetif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE)) + memcmp(&masterKey.GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE)) { doesAffectConnectivity = true; doesAffectMasterKey = true; @@ -463,10 +458,10 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: // check active timestamp rollback if (type == Tlv::kPendingTimestamp && (masterKey.GetLength() == 0 || - memcmp(&masterKey.GetNetworkMasterKey(), &mNetif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE) == 0)) + memcmp(&masterKey.GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE) == 0)) { // no change to master key, active timestamp must be ahead - const Timestamp *localActiveTimestamp = mNetif.GetActiveDataset().GetNetwork().GetTimestamp(); + const Timestamp *localActiveTimestamp = netif.GetActiveDataset().GetNetwork().GetTimestamp(); VerifyOrExit(localActiveTimestamp == NULL || localActiveTimestamp->Compare(activeTimestamp) > 0, state = StateTlv::kReject); @@ -479,7 +474,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: isUpdateFromCommissioner = true; - localId = static_cast(mNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv( + localId = static_cast(netif.GetNetworkDataLeader().GetCommissioningDataSubTlv( Tlv::kCommissionerSessionId)); VerifyOrExit(sessionId.IsValid() && @@ -496,7 +491,7 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: if (type == Tlv::kPendingTimestamp && isUpdateFromCommissioner) { mLocal.Clear(true); - mLocal.Set(mNetif.GetActiveDataset().GetNetwork()); + mLocal.Set(netif.GetActiveDataset().GetNetwork()); } if (type == Tlv::kPendingTimestamp || !doesAffectConnectivity) @@ -529,9 +524,9 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: { delayTimerTlv->SetDelayTimer(DelayTimerTlv::kDelayTimerDefault); } - else if (delayTimerTlv->GetDelayTimer() < mNetif.GetLeader().GetDelayTimerMinimal()) + else if (delayTimerTlv->GetDelayTimer() < netif.GetLeader().GetDelayTimerMinimal()) { - delayTimerTlv->SetDelayTimer(mNetif.GetLeader().GetDelayTimerMinimal()); + delayTimerTlv->SetDelayTimer(netif.GetLeader().GetDelayTimerMinimal()); } } @@ -547,12 +542,12 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: mLocal.Store(); mNetwork = mLocal; - mNetif.GetNetworkDataLeader().IncrementVersion(); - mNetif.GetNetworkDataLeader().IncrementStableVersion(); + netif.GetNetworkDataLeader().IncrementVersion(); + netif.GetNetworkDataLeader().IncrementStableVersion(); } else { - mNetif.GetPendingDataset().ApplyActiveDataset(activeTimestamp, aMessage); + netif.GetPendingDataset().ApplyActiveDataset(activeTimestamp, aMessage); } // notify commissioner if update is from thread device @@ -561,20 +556,20 @@ otError DatasetManager::Set(Coap::Header &aHeader, Message &aMessage, const Ip6: BorderAgentLocatorTlv *borderAgentLocator; Ip6::Address destination; - borderAgentLocator = static_cast(mNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv( + borderAgentLocator = static_cast(netif.GetNetworkDataLeader().GetCommissioningDataSubTlv( Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL); memset(&destination, 0, sizeof(destination)); - destination = mNetif.GetMle().GetMeshLocal16(); + destination = netif.GetMle().GetMeshLocal16(); destination.mFields.m16[7] = HostSwap16(borderAgentLocator->GetBorderAgentLocator()); - mNetif.GetLeader().SendDatasetChanged(destination); + netif.GetLeader().SendDatasetChanged(destination); } exit: - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) { SendSetResponse(aHeader, aMessageInfo, state); } @@ -584,6 +579,7 @@ exit: otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, const uint8_t *aTlvs, uint8_t aLength) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message; @@ -594,11 +590,11 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con header.AppendUriPathOptions(mUriSet); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - if (mNetif.GetCommissioner().IsActive()) + if (netif.GetCommissioner().IsActive()) { const uint8_t *cur = aTlvs; const uint8_t *end = aTlvs + aLength; @@ -621,7 +617,7 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con { CommissionerSessionIdTlv sessionId; sessionId.Init(); - sessionId.SetCommissionerSessionId(mNetif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); } } @@ -722,10 +718,10 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con message->SetLength(message->GetLength() - 1); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset set request to leader"); @@ -741,6 +737,7 @@ exit: otError DatasetManager::SendGetRequest(const uint8_t *aTlvTypes, uint8_t aLength, const otIp6Address *aAddress) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message; @@ -756,7 +753,7 @@ otError DatasetManager::SendGetRequest(const uint8_t *aTlvTypes, uint8_t aLength header.SetPayloadMarker(); } - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); if (aLength > 0) { @@ -772,12 +769,12 @@ otError DatasetManager::SendGetRequest(const uint8_t *aTlvTypes, uint8_t aLength } else { - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset get request"); @@ -794,6 +791,7 @@ exit: void DatasetManager::SendSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; Message *message; @@ -802,13 +800,13 @@ void DatasetManager::SendSetResponse(const Coap::Header &aRequestHeader, const I responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); state.Init(); state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset set response"); @@ -824,6 +822,7 @@ exit: void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, uint8_t *aTlvs, uint8_t aLength) { + ThreadNetif &netif = GetNetif(); Tlv *tlv; otError error = OT_ERROR_NONE; Coap::Header responseHeader; @@ -834,7 +833,7 @@ void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const I responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); if (aLength == 0) { @@ -844,7 +843,7 @@ void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const I while (cur < end) { if (cur->GetType() != Tlv::kNetworkMasterKey || - (mNetif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) + (netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) { SuccessOrExit(error = message->Append(cur, sizeof(Tlv) + cur->GetLength())); } @@ -857,7 +856,7 @@ void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const I for (index = 0; index < aLength; index++) { if (aTlvs[index] == Tlv::kNetworkMasterKey && - !(mNetif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) + !(netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) { continue; } @@ -875,7 +874,7 @@ void DatasetManager::SendGetResponse(const Coap::Header &aRequestHeader, const I message->SetLength(message->GetLength() - 1); } - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset get response"); @@ -887,11 +886,23 @@ exit: } } +static ActiveDatasetBase &GetActiveDatasetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + ActiveDatasetBase &activeDataset = *static_cast(aContext.GetContext()); +#else + ActiveDatasetBase &activeDataset = otGetThreadNetif().GetActiveDataset(); + OT_UNUSED_VARIABLE(aContext); +#endif + return activeDataset; +} + ActiveDatasetBase::ActiveDatasetBase(ThreadNetif &aThreadNetif): - DatasetManager(aThreadNetif, Tlv::kActiveTimestamp, OT_URI_PATH_ACTIVE_SET, OT_URI_PATH_ACTIVE_GET), + DatasetManager(aThreadNetif, Tlv::kActiveTimestamp, OT_URI_PATH_ACTIVE_SET, OT_URI_PATH_ACTIVE_GET, + &ActiveDatasetBase::HandleTimer), mResourceGet(OT_URI_PATH_ACTIVE_GET, &ActiveDatasetBase::HandleGet, this) { - mNetif.GetCoap().AddResource(mResourceGet); + aThreadNetif.GetCoap().AddResource(mResourceGet); } otError ActiveDatasetBase::Restore(void) @@ -932,15 +943,16 @@ exit: otError ActiveDatasetBase::Set(const Dataset &aDataset) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; SuccessOrExit(error = DatasetManager::Set(aDataset)); DatasetManager::ApplyConfiguration(); - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) { - mNetif.GetNetworkDataLeader().IncrementVersion(); - mNetif.GetNetworkDataLeader().IncrementStableVersion(); + netif.GetNetworkDataLeader().IncrementVersion(); + netif.GetNetworkDataLeader().IncrementStableVersion(); } exit: @@ -973,14 +985,31 @@ void ActiveDatasetBase::HandleGet(Coap::Header &aHeader, Message &aMessage, cons DatasetManager::Get(aHeader, aMessage, aMessageInfo); } +void ActiveDatasetBase::HandleTimer(Timer &aTimer) +{ + GetActiveDatasetOwner(aTimer).HandleTimer(); +} + +static PendingDatasetBase &GetPendingDatasetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + PendingDatasetBase &pendingDataset = *static_cast(aContext.GetContext()); +#else + PendingDatasetBase &pendingDataset = otGetThreadNetif().GetPendingDataset(); + OT_UNUSED_VARIABLE(aContext); +#endif + return pendingDataset; +} + PendingDatasetBase::PendingDatasetBase(ThreadNetif &aThreadNetif): - DatasetManager(aThreadNetif, Tlv::kPendingTimestamp, OT_URI_PATH_PENDING_SET, OT_URI_PATH_PENDING_GET), - mTimer(aThreadNetif.GetIp6().mTimerScheduler, &PendingDatasetBase::HandleTimer, this), + DatasetManager(aThreadNetif, Tlv::kPendingTimestamp, OT_URI_PATH_PENDING_SET, OT_URI_PATH_PENDING_GET, + &PendingDatasetBase::HandleTimer), + mDelayTimer(aThreadNetif.GetIp6().mTimerScheduler, &PendingDatasetBase::HandleDelayTimer, this), mLocalTime(0), mNetworkTime(0), mResourceGet(OT_URI_PATH_PENDING_GET, &PendingDatasetBase::HandleGet, this) { - mNetif.GetCoap().AddResource(mResourceGet); + aThreadNetif.GetCoap().AddResource(mResourceGet); } otError PendingDatasetBase::Restore(void) @@ -1057,17 +1086,17 @@ void PendingDatasetBase::ResetDelayTimer(uint8_t aFlags) if (aFlags & kFlagNetworkUpdated) { mNetworkTime = Timer::GetNow(); - mTimer.Stop(); + mDelayTimer.Stop(); if ((delayTimer = static_cast(mNetwork.Get(Tlv::kDelayTimer))) != NULL) { if (delayTimer->GetDelayTimer() == 0) { - HandleTimer(); + HandleDelayTimer(); } else { - mTimer.Start(delayTimer->GetDelayTimer()); + mDelayTimer.Start(delayTimer->GetDelayTimer()); otLogInfoMeshCoP(GetInstance(), "delay timer started"); } } @@ -1110,12 +1139,12 @@ exit: return; } -void PendingDatasetBase::HandleTimer(void *aContext) +void PendingDatasetBase::HandleDelayTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetPendingDatasetOwner(aTimer).HandleDelayTimer(); } -void PendingDatasetBase::HandleTimer(void) +void PendingDatasetBase::HandleDelayTimer(void) { DelayTimerTlv *delayTimer; @@ -1125,7 +1154,7 @@ void PendingDatasetBase::HandleTimer(void) delayTimer = static_cast(mNetwork.Get(Tlv::kDelayTimer)); assert(delayTimer != NULL && delayTimer->GetDelayTimer() == 0); - mNetif.GetActiveDataset().Set(mNetwork); + GetNetif().GetActiveDataset().Set(mNetwork); Clear(false); } @@ -1148,5 +1177,10 @@ void PendingDatasetBase::HandleGet(Coap::Header &aHeader, Message &aMessage, con DatasetManager::Get(aHeader, aMessage, aMessageInfo); } +void PendingDatasetBase::HandleTimer(Timer &aTimer) +{ + GetPendingDatasetOwner(aTimer).HandleTimer(); +} + } // namespace MeshCoP } // namespace ot diff --git a/src/core/meshcop/dataset_manager.hpp b/src/core/meshcop/dataset_manager.hpp index d48cfc346..9585f8b02 100644 --- a/src/core/meshcop/dataset_manager.hpp +++ b/src/core/meshcop/dataset_manager.hpp @@ -38,6 +38,7 @@ #include #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "meshcop/dataset.hpp" #include "net/udp6.hpp" @@ -50,18 +51,9 @@ class ThreadNetif; namespace MeshCoP { -class DatasetManager +class DatasetManager: public ThreadNetifLocator { public: - - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - Dataset &GetLocal(void) { return mLocal; } Dataset &GetNetwork(void) { return mNetwork; } @@ -74,7 +66,8 @@ protected: kFlagNetworkUpdated = 1 << 1, }; - DatasetManager(ThreadNetif &aThreadNetif, const Tlv::Type aType, const char *aUriSet, const char *aUriGet); + DatasetManager(ThreadNetif &aThreadNetif, const Tlv::Type aType, const char *aUriSet, const char *aUriGet, + Timer::Handler aTimerHander); otError Clear(uint8_t &aFlags, bool aOnlyClearNetwork); @@ -86,23 +79,18 @@ protected: void Get(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void HandleNetworkUpdate(uint8_t &aFlags); + void HandleTimer(void); Dataset mLocal; Dataset mNetwork; - ThreadNetif &mNetif; - private: static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleTimer(void *aContext); - void HandleTimer(void); - otError Register(void); void SendGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, uint8_t *aTlvs, uint8_t aLength); - Timer mTimer; const char *mUriSet; @@ -144,6 +132,9 @@ private: const otMessageInfo *aMessageInfo); void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + static void HandleTimer(Timer &aTimer); + void HandleTimer(void) { DatasetManager::HandleTimer(); } + Coap::Resource mResourceGet; }; @@ -167,15 +158,15 @@ public: void UpdateDelayTimer(void); protected: - static void HandleTimer(void *aContext); - void HandleTimer(void); + static void HandleDelayTimer(Timer &aTimer); + void HandleDelayTimer(void); void ResetDelayTimer(uint8_t aFlags); void UpdateDelayTimer(Dataset &aDataset, uint32_t &aStartTime); void HandleNetworkUpdate(uint8_t &aFlags); - Timer mTimer; + Timer mDelayTimer; uint32_t mLocalTime; uint32_t mNetworkTime; @@ -184,6 +175,9 @@ private: const otMessageInfo *aMessageInfo); void HandleGet(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + static void HandleTimer(Timer &aTimer); + void HandleTimer(void) { DatasetManager::HandleTimer(); } + Coap::Resource mResourceGet; }; diff --git a/src/core/meshcop/dataset_manager_ftd.cpp b/src/core/meshcop/dataset_manager_ftd.cpp index 2bbe32f0e..12a27b816 100644 --- a/src/core/meshcop/dataset_manager_ftd.cpp +++ b/src/core/meshcop/dataset_manager_ftd.cpp @@ -74,10 +74,11 @@ bool ActiveDataset::IsTlvInitialized(Tlv::Type aType) otError ActiveDataset::GenerateLocal(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; otOperationalDataset dataset; - VerifyOrExit(mNetif.GetMle().IsAttached(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(netif.GetMle().IsAttached(), error = OT_ERROR_INVALID_STATE); memset(&dataset, 0, sizeof(dataset)); @@ -97,7 +98,7 @@ otError ActiveDataset::GenerateLocal(void) ChannelTlv tlv; tlv.Init(); tlv.SetChannelPage(0); - tlv.SetChannel(mNetif.GetMac().GetChannel()); + tlv.SetChannel(netif.GetMac().GetChannel()); mLocal.Set(tlv); } @@ -115,7 +116,7 @@ otError ActiveDataset::GenerateLocal(void) { ExtendedPanIdTlv tlv; tlv.Init(); - tlv.SetExtendedPanId(mNetif.GetMac().GetExtendedPanId()); + tlv.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); mLocal.Set(tlv); } @@ -124,7 +125,7 @@ otError ActiveDataset::GenerateLocal(void) { MeshLocalPrefixTlv tlv; tlv.Init(); - tlv.SetMeshLocalPrefix(mNetif.GetMle().GetMeshLocalPrefix()); + tlv.SetMeshLocalPrefix(netif.GetMle().GetMeshLocalPrefix()); mLocal.Set(tlv); } @@ -133,7 +134,7 @@ otError ActiveDataset::GenerateLocal(void) { NetworkMasterKeyTlv tlv; tlv.Init(); - tlv.SetNetworkMasterKey(mNetif.GetKeyManager().GetMasterKey()); + tlv.SetNetworkMasterKey(netif.GetKeyManager().GetMasterKey()); mLocal.Set(tlv); } @@ -142,7 +143,7 @@ otError ActiveDataset::GenerateLocal(void) { NetworkNameTlv tlv; tlv.Init(); - tlv.SetNetworkName(mNetif.GetMac().GetNetworkName()); + tlv.SetNetworkName(netif.GetMac().GetNetworkName()); mLocal.Set(tlv); } @@ -151,7 +152,7 @@ otError ActiveDataset::GenerateLocal(void) { PanIdTlv tlv; tlv.Init(); - tlv.SetPanId(mNetif.GetMac().GetPanId()); + tlv.SetPanId(netif.GetMac().GetPanId()); mLocal.Set(tlv); } @@ -160,7 +161,7 @@ otError ActiveDataset::GenerateLocal(void) { PSKcTlv tlv; tlv.Init(); - tlv.SetPSKc(mNetif.GetKeyManager().GetPSKc()); + tlv.SetPSKc(netif.GetKeyManager().GetPSKc()); mLocal.Set(tlv); } @@ -169,8 +170,8 @@ otError ActiveDataset::GenerateLocal(void) { SecurityPolicyTlv tlv; tlv.Init(); - tlv.SetRotationTime(static_cast(mNetif.GetKeyManager().GetKeyRotation())); - tlv.SetFlags(mNetif.GetKeyManager().GetSecurityPolicyFlags()); + tlv.SetRotationTime(static_cast(netif.GetKeyManager().GetKeyRotation())); + tlv.SetFlags(netif.GetKeyManager().GetSecurityPolicyFlags()); mLocal.Set(tlv); } @@ -184,12 +185,12 @@ void ActiveDataset::StartLeader(void) mLocal.Store(); mNetwork = mLocal; - mNetif.GetCoap().AddResource(mResourceSet); + GetNetif().GetCoap().AddResource(mResourceSet); } void ActiveDataset::StopLeader(void) { - mNetif.GetCoap().RemoveResource(mResourceSet); + GetNetif().GetCoap().RemoveResource(mResourceSet); } void ActiveDataset::HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -222,12 +223,12 @@ void PendingDataset::StartLeader(void) mNetwork = mLocal; ResetDelayTimer(kFlagNetworkUpdated); - mNetif.GetCoap().AddResource(mResourceSet); + GetNetif().GetCoap().AddResource(mResourceSet); } void PendingDataset::StopLeader(void) { - mNetif.GetCoap().RemoveResource(mResourceSet); + GetNetif().GetCoap().RemoveResource(mResourceSet); } void PendingDataset::HandleSet(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -249,11 +250,12 @@ exit: void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Message &aMessage) { + ThreadNetif &netif = GetNetif(); uint16_t offset = aMessage.GetOffset(); DelayTimerTlv delayTimer; uint8_t flags; - VerifyOrExit(mNetif.GetMle().IsAttached()); + VerifyOrExit(netif.GetMle().IsAttached()); while (offset < aMessage.GetLength()) { @@ -272,7 +274,7 @@ void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Message &aM // add delay timer tlv delayTimer.Init(); - delayTimer.SetDelayTimer(mNetif.GetLeader().GetDelayTimerMinimal()); + delayTimer.SetDelayTimer(netif.GetLeader().GetDelayTimerMinimal()); mNetwork.Set(delayTimer); // add pending timestamp tlv diff --git a/src/core/meshcop/dtls.cpp b/src/core/meshcop/dtls.cpp index 64e88c800..719defb93 100644 --- a/src/core/meshcop/dtls.cpp +++ b/src/core/meshcop/dtls.cpp @@ -39,6 +39,7 @@ #include #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -53,6 +54,7 @@ namespace ot { namespace MeshCoP { Dtls::Dtls(ThreadNetif &aNetif): + ThreadNetifLocator(aNetif), mPskLength(0), mStarted(false), mTimer(aNetif.GetIp6().mTimerScheduler, &Dtls::HandleTimer, this), @@ -66,8 +68,7 @@ Dtls::Dtls(ThreadNetif &aNetif): mSendHandler(NULL), mContext(NULL), mClient(false), - mMessageSubType(0), - mNetif(aNetif) + mMessageSubType(0) { memset(mPsk, 0, sizeof(mPsk)); memset(&mEntropy, 0, sizeof(mEntropy)); @@ -78,11 +79,6 @@ Dtls::Dtls(ThreadNetif &aNetif): mProvisioningUrl.Init(); } -otInstance *Dtls::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError Dtls::Start(bool aClient, ConnectedHandler aConnectedHandler, ReceiveHandler aReceiveHandler, SendHandler aSendHandler, void *aContext) { @@ -366,7 +362,7 @@ int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsi sha256.Update(aKeyBlock, 2 * static_cast(aMacLength + aKeyLength + aIvLength)); sha256.Finish(kek); - mNetif.GetKeyManager().SetKek(kek); + GetNetif().GetKeyManager().SetKek(kek); otLogInfoMeshCoP(GetInstance(), "Generated KEK"); @@ -374,9 +370,9 @@ int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsi return 0; } -void Dtls::HandleTimer(void *aContext) +void Dtls::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void Dtls::HandleTimer(void) @@ -514,6 +510,17 @@ void Dtls::HandleMbedtlsDebug(void *ctx, int level, const char *, int, const cha } } +Dtls &Dtls::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Dtls &dtls = *static_cast(aContext.GetContext()); +#else + Dtls &dtls = otGetThreadNetif().GetDtls(); + OT_UNUSED_VARIABLE(aContext); +#endif + return dtls; +} + } // namespace MeshCoP } // namespace ot diff --git a/src/core/meshcop/dtls.hpp b/src/core/meshcop/dtls.hpp index a5a0cdc39..60d0390c1 100644 --- a/src/core/meshcop/dtls.hpp +++ b/src/core/meshcop/dtls.hpp @@ -43,6 +43,7 @@ #include #include +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "crypto/sha256.hpp" @@ -54,7 +55,7 @@ class ThreadNetif; namespace MeshCoP { -class Dtls +class Dtls: public ThreadNetifLocator { public: enum @@ -71,14 +72,6 @@ public: */ Dtls(ThreadNetif &aNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This function pointer is called when a connection is established or torn down. * @@ -224,12 +217,14 @@ private: int HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, const unsigned char *aKeyBlock, size_t aMacLength, size_t aKeyLength, size_t aIvLength); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); void Close(void); void Process(void); + static Dtls &GetOwner(const Context &aContext); + uint8_t mPsk[kPskMaxLength]; uint8_t mPskLength; @@ -255,8 +250,6 @@ private: bool mClient; uint8_t mMessageSubType; - - ThreadNetif &mNetif; }; } // namespace MeshCoP diff --git a/src/core/meshcop/energy_scan_client.cpp b/src/core/meshcop/energy_scan_client.cpp index f96b5559b..7c6bcadec 100644 --- a/src/core/meshcop/energy_scan_client.cpp +++ b/src/core/meshcop/energy_scan_client.cpp @@ -56,23 +56,19 @@ using ot::Encoding::BigEndian::HostSwap32; namespace ot { EnergyScanClient::EnergyScanClient(ThreadNetif &aThreadNetif) : - mEnergyScan(OT_URI_PATH_ENERGY_REPORT, &EnergyScanClient::HandleReport, this), - mNetif(aThreadNetif) + ThreadNetifLocator(aThreadNetif), + mEnergyScan(OT_URI_PATH_ENERGY_REPORT, &EnergyScanClient::HandleReport, this) { mContext = NULL; mCallback = NULL; - mNetif.GetCoap().AddResource(mEnergyScan); -} - -otInstance *EnergyScanClient::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mEnergyScan); } otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint16_t aPeriod, uint16_t aScanDuration, const Ip6::Address &aAddress, otCommissionerEnergyReportCallback aCallback, void *aContext) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; MeshCoP::CommissionerSessionIdTlv sessionId; @@ -83,7 +79,7 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint1 Ip6::MessageInfo messageInfo; Message *message = NULL; - VerifyOrExit(mNetif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -91,11 +87,11 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint1 header.AppendUriPathOptions(OT_URI_PATH_ENERGY_SCAN); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); sessionId.Init(); - sessionId.SetCommissionerSessionId(mNetif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -114,11 +110,11 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelMask, uint8_t aCount, uint1 scanDuration.SetScanDuration(aScanDuration); SuccessOrExit(error = message->Append(&scanDuration, sizeof(scanDuration))); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent energy scan query"); @@ -145,6 +141,7 @@ void EnergyScanClient::HandleReport(void *aContext, otCoapHeader *aHeader, otMes void EnergyScanClient::HandleReport(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); MeshCoP::ChannelMask0Tlv channelMask; Ip6::MessageInfo responseInfo(aMessageInfo); @@ -171,7 +168,7 @@ void EnergyScanClient::HandleReport(Coap::Header &aHeader, Message &aMessage, co mCallback(channelMask.GetMask(), energyList.list, energyList.tlv.GetLength(), mContext); } - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, responseInfo)); + SuccessOrExit(netif.GetCoap().SendEmptyAck(aHeader, responseInfo)); otLogInfoMeshCoP(GetInstance(), "sent energy scan report response"); diff --git a/src/core/meshcop/energy_scan_client.hpp b/src/core/meshcop/energy_scan_client.hpp index 11ec811f8..6ac24206b 100644 --- a/src/core/meshcop/energy_scan_client.hpp +++ b/src/core/meshcop/energy_scan_client.hpp @@ -38,6 +38,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" @@ -49,7 +50,7 @@ class ThreadNetif; * This class implements handling PANID Query Requests. * */ -class EnergyScanClient +class EnergyScanClient: public ThreadNetifLocator { public: /** @@ -58,14 +59,6 @@ public: */ EnergyScanClient(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method sends an Energy Scan Query message. * @@ -93,8 +86,6 @@ private: void *mContext; Coap::Resource mEnergyScan; - - ThreadNetif &mNetif; }; /** diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index a7bad90af..a551ab19a 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -61,6 +61,7 @@ namespace ot { namespace MeshCoP { Joiner::Joiner(ThreadNetif &aNetif): + ThreadNetifLocator(aNetif), mState(kStateIdle), mCallback(NULL), mContext(NULL), @@ -74,21 +75,16 @@ Joiner::Joiner(ThreadNetif &aNetif): mVendorSwVersion(NULL), mVendorData(NULL), mTimer(aNetif.GetIp6().mTimerScheduler, &Joiner::HandleTimer, this), - mJoinerEntrust(OT_URI_PATH_JOINER_ENTRUST, &Joiner::HandleJoinerEntrust, this), - mNetif(aNetif) + mJoinerEntrust(OT_URI_PATH_JOINER_ENTRUST, &Joiner::HandleJoinerEntrust, this) { - mNetif.GetCoap().AddResource(mJoinerEntrust); -} - -otInstance *Joiner::GetInstance(void) -{ - return mNetif.GetInstance(); + aNetif.GetCoap().AddResource(mJoinerEntrust); } otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, const char *aVendorName, const char *aVendorModel, const char *aVendorSwVersion, const char *aVendorData, otJoinerCallback aCallback, void *aContext) { + ThreadNetif &netif = GetNetif(); otError error; Mac::ExtAddress extAddress; Crc16 ccitt(Crc16::kCcitt); @@ -99,9 +95,9 @@ otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, VerifyOrExit(mState == kStateIdle, error = OT_ERROR_BUSY); // use extended address based on factory-assigned IEEE EUI-64 - mNetif.GetMac().GetHashMacAddress(&extAddress); - mNetif.GetMac().SetExtAddress(extAddress); - mNetif.GetMle().UpdateLinkLocalAddress(); + netif.GetMac().GetHashMacAddress(&extAddress); + netif.GetMac().SetExtAddress(extAddress); + netif.GetMle().UpdateLinkLocalAddress(); for (size_t i = 0; i < sizeof(extAddress); i++) { @@ -112,18 +108,19 @@ otError Joiner::Start(const char *aPSKd, const char *aProvisioningUrl, mCcitt = ccitt.Get(); mAnsi = ansi.Get(); - error = mNetif.GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT); + error = netif.GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT); SuccessOrExit(error); - error = mNetif.GetCoapSecure().GetDtls().SetPsk(reinterpret_cast(aPSKd), - static_cast(strlen(aPSKd))); + error = netif.GetCoapSecure().GetDtls().SetPsk(reinterpret_cast(aPSKd), + static_cast(strlen(aPSKd))); SuccessOrExit(error); - error = mNetif.GetCoapSecure().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); + error = netif.GetCoapSecure().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); SuccessOrExit(error); mJoinerRouterPanId = Mac::kPanIdBroadcast; - SuccessOrExit(error = mNetif.GetMle().Discover(0, mNetif.GetMac().GetPanId(), true, false, HandleDiscoverResult, this)); + SuccessOrExit(error = netif.GetMle().Discover(0, netif.GetMac().GetPanId(), true, false, HandleDiscoverResult, + this)); mVendorName = aVendorName; mVendorModel = aVendorModel; @@ -150,10 +147,11 @@ otError Joiner::Stop(void) void Joiner::Close(void) { + ThreadNetif &netif = GetNetif(); otLogFuncEntry(); - mNetif.GetCoapSecure().Disconnect(); - mNetif.GetIp6Filter().RemoveUnsecurePort(mNetif.GetCoapSecure().GetPort()); + netif.GetCoapSecure().Disconnect(); + netif.GetIp6Filter().RemoveUnsecurePort(netif.GetCoapSecure().GetPort()); otLogFuncExit(); } @@ -162,7 +160,7 @@ void Joiner::Complete(otError aError) { mState = kStateIdle; - mNetif.GetCoapSecure().Stop(); + GetNetif().GetCoapSecure().Stop(); if (mCallback) { @@ -179,6 +177,7 @@ void Joiner::HandleDiscoverResult(otActiveScanResult *aResult, void *aContext) void Joiner::HandleDiscoverResult(otActiveScanResult *aResult) { + ThreadNetif &netif = GetNetif(); Ip6::MessageInfo messageInfo; otLogFuncEntry(); @@ -216,16 +215,16 @@ void Joiner::HandleDiscoverResult(otActiveScanResult *aResult) { otLogFuncEntryMsg("aResult = NULL"); - mNetif.GetMac().SetPanId(mJoinerRouterPanId); - mNetif.GetMac().SetChannel(mJoinerRouterChannel); - mNetif.GetIp6Filter().AddUnsecurePort(mNetif.GetCoapSecure().GetPort()); + netif.GetMac().SetPanId(mJoinerRouterPanId); + netif.GetMac().SetChannel(mJoinerRouterChannel); + netif.GetIp6Filter().AddUnsecurePort(netif.GetCoapSecure().GetPort()); messageInfo.GetPeerAddr().mFields.m16[0] = HostSwap16(0xfe80); messageInfo.GetPeerAddr().SetIid(mJoinerRouter); messageInfo.mPeerPort = mJoinerUdpPort; messageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD; - mNetif.GetCoapSecure().Connect(messageInfo, Joiner::HandleSecureCoapClientConnect, this); + netif.GetCoapSecure().Connect(messageInfo, Joiner::HandleSecureCoapClientConnect, this); mState = kStateConnect; } else @@ -268,6 +267,7 @@ void Joiner::HandleSecureCoapClientConnect(bool aConnected) void Joiner::SendJoinerFinalize(void) { + ThreadNetif &netif = GetNetif(); Coap::Header header; otError error = OT_ERROR_NONE; Message *message = NULL; @@ -283,7 +283,7 @@ void Joiner::SendJoinerFinalize(void) header.AppendUriPathOptions(OT_URI_PATH_JOINER_FINALIZE); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoapSecure(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure(), header)) != NULL, error = OT_ERROR_NO_BUFS); stateTlv.Init(); stateTlv.SetState(MeshCoP::StateTlv::kAccept); @@ -316,10 +316,10 @@ void Joiner::SendJoinerFinalize(void) SuccessOrExit(error = message->Append(&vendorDataTlv, vendorDataTlv.GetSize())); } - if (mNetif.GetCoapSecure().GetDtls().mProvisioningUrl.GetLength() > 0) + if (netif.GetCoapSecure().GetDtls().mProvisioningUrl.GetLength() > 0) { - SuccessOrExit(error = message->Append(&mNetif.GetCoapSecure().GetDtls().mProvisioningUrl, - mNetif.GetCoapSecure().GetDtls().mProvisioningUrl.GetSize())); + SuccessOrExit(error = message->Append(&netif.GetCoapSecure().GetDtls().mProvisioningUrl, + netif.GetCoapSecure().GetDtls().mProvisioningUrl.GetSize())); } #if OPENTHREAD_ENABLE_CERT_LOG @@ -330,7 +330,7 @@ void Joiner::SendJoinerFinalize(void) message->GetLength() - header.GetLength()); #endif - SuccessOrExit(error = mNetif.GetCoapSecure().SendMessage(*message, Joiner::HandleJoinerFinalizeResponse, this)); + SuccessOrExit(error = netif.GetCoapSecure().SendMessage(*message, Joiner::HandleJoinerFinalizeResponse, this)); otLogInfoMeshCoP(GetInstance(), "Sent joiner finalize"); @@ -395,8 +395,8 @@ void Joiner::HandleJoinerEntrust(void *aContext, otCoapHeader *aHeader, otMessag void Joiner::HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error; - NetworkMasterKeyTlv masterKey; MeshLocalPrefixTlv meshLocalPrefix; ExtendedPanIdTlv extendedPanId; @@ -431,11 +431,11 @@ void Joiner::HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kNetworkKeySequence, sizeof(networkKeySeq), networkKeySeq)); VerifyOrExit(networkKeySeq.IsValid(), error = OT_ERROR_PARSE); - mNetif.GetKeyManager().SetMasterKey(masterKey.GetNetworkMasterKey()); - mNetif.GetKeyManager().SetCurrentKeySequence(networkKeySeq.GetNetworkKeySequence()); - mNetif.GetMle().SetMeshLocalPrefix(meshLocalPrefix.GetMeshLocalPrefix()); - mNetif.GetMac().SetExtendedPanId(extendedPanId.GetExtendedPanId()); - mNetif.GetMac().SetNetworkName(networkName.GetNetworkName()); + netif.GetKeyManager().SetMasterKey(masterKey.GetNetworkMasterKey()); + netif.GetKeyManager().SetCurrentKeySequence(networkKeySeq.GetNetworkKeySequence()); + netif.GetMle().SetMeshLocalPrefix(meshLocalPrefix.GetMeshLocalPrefix()); + netif.GetMac().SetExtendedPanId(extendedPanId.GetExtendedPanId()); + netif.GetMac().SetNetworkName(networkName.GetNetworkName()); otLogInfoMeshCoP(GetInstance(), "join success!"); @@ -459,6 +459,7 @@ exit: void Joiner::SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aRequestInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message; Coap::Header responseHeader; @@ -468,11 +469,11 @@ void Joiner::SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, responseHeader.SetDefaultResponseHeader(aRequestHeader); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeJoinerEntrust); memset(&responseInfo.mSockAddr, 0, sizeof(responseInfo.mSockAddr)); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, responseInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, responseInfo)); mState = kStateJoined; @@ -491,13 +492,14 @@ exit: otLogFuncExit(); } -void Joiner::HandleTimer(void *aContext) +void Joiner::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void Joiner::HandleTimer(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; switch (mState) @@ -516,9 +518,9 @@ void Joiner::HandleTimer(void) case kStateJoined: Mac::ExtAddress extAddress; - mNetif.GetMac().GenerateExtAddress(&extAddress); - mNetif.GetMac().SetExtAddress(extAddress); - mNetif.GetMle().UpdateLinkLocalAddress(); + netif.GetMac().GenerateExtAddress(&extAddress); + netif.GetMac().SetExtAddress(extAddress); + netif.GetMle().UpdateLinkLocalAddress(); error = OT_ERROR_NONE; break; @@ -528,6 +530,17 @@ void Joiner::HandleTimer(void) Complete(error); } +Joiner &Joiner::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Joiner &joiner = *static_cast(aContext.GetContext()); +#else + Joiner &joiner = otGetThreadNetif().GetJoiner(); + OT_UNUSED_VARIABLE(aContext); +#endif + return joiner; +} + } // namespace MeshCoP } // namespace ot diff --git a/src/core/meshcop/joiner.hpp b/src/core/meshcop/joiner.hpp index ca5d64331..eb7064192 100644 --- a/src/core/meshcop/joiner.hpp +++ b/src/core/meshcop/joiner.hpp @@ -40,6 +40,7 @@ #include "coap/coap_header.hpp" #include "coap/coap_secure.hpp" #include "common/crc16.hpp" +#include "common/locator.hpp" #include "common/message.hpp" #include "meshcop/dtls.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -51,7 +52,7 @@ class ThreadNetif; namespace MeshCoP { -class Joiner +class Joiner: public ThreadNetifLocator { public: /** @@ -62,14 +63,6 @@ public: */ Joiner(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method starts the Joiner service. * @@ -108,7 +101,7 @@ private: static void HandleDiscoverResult(otActiveScanResult *aResult, void *aContext); void HandleDiscoverResult(otActiveScanResult *aResult); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); void Close(void); @@ -128,6 +121,8 @@ private: void HandleJoinerEntrust(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); void SendJoinerEntrustResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aRequestInfo); + static Joiner &GetOwner(const Context &aContext); + enum State { kStateIdle = 0, @@ -157,7 +152,6 @@ private: Timer mTimer; Coap::Resource mJoinerEntrust; - ThreadNetif &mNetif; }; } // namespace MeshCoP diff --git a/src/core/meshcop/joiner_router.cpp b/src/core/meshcop/joiner_router.cpp index c01ecc747..2222dee6e 100644 --- a/src/core/meshcop/joiner_router.cpp +++ b/src/core/meshcop/joiner_router.cpp @@ -41,6 +41,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/logging.hpp" @@ -57,23 +58,18 @@ namespace ot { namespace MeshCoP { JoinerRouter::JoinerRouter(ThreadNetif &aNetif): + ThreadNetifLocator(aNetif), mSocket(aNetif.GetIp6().mUdp), mRelayTransmit(OT_URI_PATH_RELAY_TX, &JoinerRouter::HandleRelayTransmit, this), - mNetif(aNetif), mTimer(aNetif.GetIp6().mTimerScheduler, &JoinerRouter::HandleTimer, this), mJoinerUdpPort(0), mIsJoinerPortConfigured(false), mExpectJoinEntRsp(false) { mSocket.GetSockName().mPort = OPENTHREAD_CONFIG_JOINER_UDP_PORT; - mNetif.GetCoap().AddResource(mRelayTransmit); + aNetif.GetCoap().AddResource(mRelayTransmit); mNetifCallback.Set(HandleNetifStateChanged, this); - mNetif.RegisterCallback(mNetifCallback); -} - -otInstance *JoinerRouter::GetInstance(void) -{ - return mNetif.GetInstance(); + aNetif.RegisterCallback(mNetifCallback); } void JoinerRouter::HandleNetifStateChanged(uint32_t aFlags, void *aContext) @@ -83,12 +79,14 @@ void JoinerRouter::HandleNetifStateChanged(uint32_t aFlags, void *aContext) void JoinerRouter::HandleNetifStateChanged(uint32_t aFlags) { - VerifyOrExit(mNetif.GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD); + ThreadNetif &netif = GetNetif(); + + VerifyOrExit(netif.GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD); VerifyOrExit(aFlags & OT_CHANGED_THREAD_NETDATA); - mNetif.GetIp6Filter().RemoveUnsecurePort(mSocket.GetSockName().mPort); + netif.GetIp6Filter().RemoveUnsecurePort(mSocket.GetSockName().mPort); - if (mNetif.GetNetworkDataLeader().IsJoiningEnabled()) + if (netif.GetNetworkDataLeader().IsJoiningEnabled()) { Ip6::SockAddr sockaddr; @@ -96,7 +94,7 @@ void JoinerRouter::HandleNetifStateChanged(uint32_t aFlags) mSocket.Open(&JoinerRouter::HandleUdpReceive, this); mSocket.Bind(sockaddr); - mNetif.GetIp6Filter().AddUnsecurePort(sockaddr.mPort); + netif.GetIp6Filter().AddUnsecurePort(sockaddr.mPort); otLogInfoMeshCoP(GetInstance(), "Joiner Router: start"); } else @@ -113,7 +111,7 @@ otError JoinerRouter::GetBorderAgentRloc(uint16_t &aRloc) otError error = OT_ERROR_NONE; BorderAgentLocatorTlv *borderAgentLocator; - borderAgentLocator = static_cast(mNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv( + borderAgentLocator = static_cast(GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv( Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL, error = OT_ERROR_NOT_FOUND); @@ -130,7 +128,7 @@ uint16_t JoinerRouter::GetJoinerUdpPort(void) VerifyOrExit(!mIsJoinerPortConfigured, rval = mJoinerUdpPort); - joinerUdpPort = static_cast(mNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv( + joinerUdpPort = static_cast(GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv( Tlv::kJoinerUdpPort)); VerifyOrExit(joinerUdpPort != NULL); @@ -158,6 +156,7 @@ void JoinerRouter::HandleUdpReceive(void *aContext, otMessage *aMessage, const o void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error; Message *message = NULL; Coap::Header header; @@ -179,7 +178,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a header.AppendUriPathOptions(OT_URI_PATH_RELAY_RX); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); udpPort.Init(); udpPort.SetUdpPort(aMessageInfo.GetPeerPort()); @@ -190,7 +189,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(error = message->Append(&iid, sizeof(iid))); rloc.Init(); - rloc.SetJoinerRouterLocator(mNetif.GetMle().GetRloc16()); + rloc.SetJoinerRouterLocator(netif.GetMle().GetRloc16()); SuccessOrExit(error = message->Append(&rloc, sizeof(rloc))); tlv.SetType(Tlv::kJoinerDtlsEncapsulation); @@ -213,12 +212,12 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(error = message->Append(tmp, length)); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); - messageInfo.SetPeerAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(borderAgentRloc); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "Sent relay rx"); @@ -291,7 +290,7 @@ void JoinerRouter::HandleRelayTransmit(Coap::Header &aHeader, Message &aMessage, messageInfo.mPeerAddr.mFields.m16[0] = HostSwap16(0xfe80); memcpy(messageInfo.mPeerAddr.mFields.m8 + 8, joinerIid.GetIid(), 8); messageInfo.SetPeerPort(joinerPort.GetUdpPort()); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(GetNetif().GetInterfaceId()); SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); @@ -317,6 +316,7 @@ exit: otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const JoinerRouterKekTlv &aKek) { + ThreadNetif &netif = GetNetif(); otError error; Message *message = NULL; Coap::Header header; @@ -337,26 +337,26 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage header.AppendUriPathOptions(OT_URI_PATH_JOINER_ENTRUST); header.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeJoinerEntrust); masterKey.Init(); - masterKey.SetNetworkMasterKey(mNetif.GetKeyManager().GetMasterKey()); + masterKey.SetNetworkMasterKey(netif.GetKeyManager().GetMasterKey()); SuccessOrExit(error = message->Append(&masterKey, sizeof(masterKey))); meshLocalPrefix.Init(); - meshLocalPrefix.SetMeshLocalPrefix(mNetif.GetMle().GetMeshLocalPrefix()); + meshLocalPrefix.SetMeshLocalPrefix(netif.GetMle().GetMeshLocalPrefix()); SuccessOrExit(error = message->Append(&meshLocalPrefix, sizeof(meshLocalPrefix))); extendedPanId.Init(); - extendedPanId.SetExtendedPanId(mNetif.GetMac().GetExtendedPanId()); + extendedPanId.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); SuccessOrExit(error = message->Append(&extendedPanId, sizeof(extendedPanId))); networkName.Init(); - networkName.SetNetworkName(mNetif.GetMac().GetNetworkName()); + networkName.SetNetworkName(netif.GetMac().GetNetworkName()); SuccessOrExit(error = message->Append(&networkName, sizeof(Tlv) + networkName.GetLength())); - if ((tlv = mNetif.GetActiveDataset().GetNetwork().Get(Tlv::kActiveTimestamp)) != NULL) + if ((tlv = netif.GetActiveDataset().GetNetwork().Get(Tlv::kActiveTimestamp)) != NULL) { SuccessOrExit(error = message->Append(tlv, sizeof(Tlv) + tlv->GetLength())); } @@ -367,7 +367,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage SuccessOrExit(error = message->Append(&activeTimestamp, sizeof(activeTimestamp))); } - if ((tlv = mNetif.GetActiveDataset().GetNetwork().Get(Tlv::kChannelMask)) != NULL) + if ((tlv = netif.GetActiveDataset().GetNetwork().Get(Tlv::kChannelMask)) != NULL) { SuccessOrExit(error = message->Append(tlv, sizeof(Tlv) + tlv->GetLength())); } @@ -378,7 +378,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage SuccessOrExit(error = message->Append(&channelMask, sizeof(channelMask))); } - if ((tlv = mNetif.GetActiveDataset().GetNetwork().Get(Tlv::kPSKc)) != NULL) + if ((tlv = netif.GetActiveDataset().GetNetwork().Get(Tlv::kPSKc)) != NULL) { SuccessOrExit(error = message->Append(tlv, sizeof(Tlv) + tlv->GetLength())); } @@ -389,7 +389,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage SuccessOrExit(error = message->Append(&pskc, sizeof(pskc))); } - if ((tlv = mNetif.GetActiveDataset().GetNetwork().Get(Tlv::kSecurityPolicy)) != NULL) + if ((tlv = netif.GetActiveDataset().GetNetwork().Get(Tlv::kSecurityPolicy)) != NULL) { SuccessOrExit(error = message->Append(tlv, sizeof(Tlv) + tlv->GetLength())); } @@ -401,7 +401,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage } networkKeySequence.Init(); - networkKeySequence.SetNetworkKeySequence(mNetif.GetKeyManager().GetCurrentKeySequence()); + networkKeySequence.SetNetworkKeySequence(netif.GetKeyManager().GetCurrentKeySequence()); SuccessOrExit(error = message->Append(&networkKeySequence, networkKeySequence.GetSize())); messageInfo = aMessageInfo; @@ -427,9 +427,9 @@ exit: return error; } -void JoinerRouter::HandleTimer(void *aContext) +void JoinerRouter::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void JoinerRouter::HandleTimer(void) @@ -439,6 +439,7 @@ void JoinerRouter::HandleTimer(void) void JoinerRouter::SendDelayedJoinerEntrust(void) { + ThreadNetif &netif = GetNetif(); DelayedJoinEntHeader delayedJoinEnt; Message *message = mDelayedJoinEnts.GetHead(); uint32_t now = Timer::GetNow(); @@ -451,7 +452,7 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) // The message can be sent during CoAP transaction if KEK did not change (i.e. retransmission). VerifyOrExit(!mExpectJoinEntRsp || - memcmp(mNetif.GetKeyManager().GetKek(), delayedJoinEnt.GetKek(), KeyManager::kMaxKeyLength) == 0); + memcmp(netif.GetKeyManager().GetKek(), delayedJoinEnt.GetKek(), KeyManager::kMaxKeyLength) == 0); if (delayedJoinEnt.IsLater(now)) @@ -466,7 +467,7 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) DelayedJoinEntHeader::RemoveFrom(*message); // Set KEK to one used for this message. - mNetif.GetKeyManager().SetKek(delayedJoinEnt.GetKek()); + netif.GetKeyManager().SetKek(delayedJoinEnt.GetKek()); // Send the message. memcpy(&messageInfo, delayedJoinEnt.GetMessageInfo(), sizeof(messageInfo)); @@ -484,13 +485,14 @@ exit: otError JoinerRouter::SendJoinerEntrust(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error; - mNetif.GetCoap().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this); + netif.GetCoap().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this); otLogInfoMeshCoP(GetInstance(), "Sending JOIN_ENT.ntf"); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(aMessage, aMessageInfo, - &JoinerRouter::HandleJoinerEntrustResponse, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(aMessage, aMessageInfo, + &JoinerRouter::HandleJoinerEntrustResponse, this)); otLogInfoMeshCoP(GetInstance(), "Sent joiner entrust length = %d", aMessage.GetLength()); otLogCertMeshCoP(GetInstance(), "[THCI] direction=send | type=JOIN_ENT.ntf"); @@ -529,6 +531,17 @@ exit: return ; } +JoinerRouter &JoinerRouter::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + JoinerRouter &joiner = *static_cast(aContext.GetContext()); +#else + JoinerRouter &joiner = otGetThreadNetif().GetJoinerRouter(); + OT_UNUSED_VARIABLE(aContext); +#endif + return joiner; +} + } // namespace Dtls } // namespace ot diff --git a/src/core/meshcop/joiner_router.hpp b/src/core/meshcop/joiner_router.hpp index 6c298ee64..456f72647 100644 --- a/src/core/meshcop/joiner_router.hpp +++ b/src/core/meshcop/joiner_router.hpp @@ -38,6 +38,7 @@ #include "coap/coap.hpp" #include "coap/coap_header.hpp" +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" @@ -51,7 +52,7 @@ class ThreadNetif; namespace MeshCoP { -class JoinerRouter +class JoinerRouter: public ThreadNetifLocator { public: /** @@ -62,14 +63,6 @@ public: */ JoinerRouter(ThreadNetif &aNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method returns the Joiner UDP Port. * @@ -109,7 +102,7 @@ private: void HandleJoinerEntrustResponse(Coap::Header *aHeader, Message *aMessage, const Ip6::MessageInfo *aMessageInfo, otError result); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); otError DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const JoinerRouterKekTlv &aKek); @@ -118,11 +111,12 @@ private: otError GetBorderAgentRloc(uint16_t &aRloc); + static JoinerRouter &GetOwner(const Context &aContext); + Ip6::NetifCallback mNetifCallback; Ip6::UdpSocket mSocket; Coap::Resource mRelayTransmit; - ThreadNetif &mNetif; Timer mTimer; MessageQueue mDelayedJoinEnts; diff --git a/src/core/meshcop/leader.cpp b/src/core/meshcop/leader.cpp index 69d173f79..24d2ee938 100644 --- a/src/core/meshcop/leader.cpp +++ b/src/core/meshcop/leader.cpp @@ -43,6 +43,7 @@ #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/logging.hpp" @@ -56,20 +57,15 @@ namespace ot { namespace MeshCoP { Leader::Leader(ThreadNetif &aThreadNetif): + ThreadNetifLocator(aThreadNetif), mPetition(OT_URI_PATH_LEADER_PETITION, Leader::HandlePetition, this), mKeepAlive(OT_URI_PATH_LEADER_KEEP_ALIVE, Leader::HandleKeepAlive, this), mTimer(aThreadNetif.GetIp6().mTimerScheduler, HandleTimer, this), mDelayTimerMinimal(DelayTimerTlv::kDelayTimerMinimal), - mSessionId(0xffff), - mNetif(aThreadNetif) + mSessionId(0xffff) { - mNetif.GetCoap().AddResource(mPetition); - mNetif.GetCoap().AddResource(mKeepAlive); -} - -otInstance *Leader::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mPetition); + aThreadNetif.GetCoap().AddResource(mKeepAlive); } void Leader::HandlePetition(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -109,7 +105,8 @@ void Leader::HandlePetition(Coap::Header &aHeader, Message &aMessage, const Ip6: data.mSteeringData.SetLength(1); data.mSteeringData.Clear(); - SuccessOrExit(mNetif.GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&data), data.GetLength())); + SuccessOrExit(GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&data), + data.GetLength())); mCommissionerId = commissionerId; @@ -124,6 +121,7 @@ exit: otError Leader::SendPetitionResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; StateTlv state; @@ -133,7 +131,7 @@ otError Leader::SendPetitionResponse(const Coap::Header &aRequestHeader, const I responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); state.Init(); state.SetState(aState); @@ -152,7 +150,7 @@ otError Leader::SendPetitionResponse(const Coap::Header &aRequestHeader, const I SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); } - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent petition response"); @@ -212,22 +210,22 @@ exit: otError Leader::SendKeepAliveResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; StateTlv state; Message *message; - responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); state.Init(); state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent keep alive response"); @@ -243,6 +241,7 @@ exit: otError Leader::SendDatasetChanged(const Ip6::Address &aAddress) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Ip6::MessageInfo messageInfo; @@ -252,12 +251,12 @@ otError Leader::SendDatasetChanged(const Ip6::Address &aAddress) header.SetToken(Coap::Header::kDefaultTokenLength); header.AppendUriPathOptions(OT_URI_PATH_DATASET_CHANGED); - VerifyOrExit((message = NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent dataset changed"); @@ -287,14 +286,14 @@ uint32_t Leader::GetDelayTimerMinimal(void) const return mDelayTimerMinimal; } -void Leader::HandleTimer(void *aContext) +void Leader::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void Leader::HandleTimer(void) { - VerifyOrExit(mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER); + VerifyOrExit(GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER); ResignCommissioner(); @@ -309,8 +308,8 @@ void Leader::SetEmptyCommissionerData(void) mCommissionerSessionId.Init(); mCommissionerSessionId.SetCommissionerSessionId(++mSessionId); - mNetif.GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&mCommissionerSessionId), - sizeof(Tlv) + mCommissionerSessionId.GetLength()); + GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&mCommissionerSessionId), + sizeof(Tlv) + mCommissionerSessionId.GetLength()); } void Leader::ResignCommissioner(void) @@ -321,6 +320,17 @@ void Leader::ResignCommissioner(void) otLogInfoMeshCoP(GetInstance(), "commissioner inactive"); } +Leader &Leader::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Leader &leader = *static_cast(aContext.GetContext()); +#else + Leader &leader = otGetThreadNetif().GetLeader(); + OT_UNUSED_VARIABLE(aContext); +#endif + return leader; +} + } // namespace MeshCoP } // namespace ot diff --git a/src/core/meshcop/leader.hpp b/src/core/meshcop/leader.hpp index c3e2c0ce1..b9dc7b703 100644 --- a/src/core/meshcop/leader.hpp +++ b/src/core/meshcop/leader.hpp @@ -35,6 +35,7 @@ #define MESHCOP_LEADER_HPP_ #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "net/udp6.hpp" @@ -58,7 +59,7 @@ public: SteeringDataTlv mSteeringData; } OT_TOOL_PACKED_END; -class Leader +class Leader: public ThreadNetifLocator { public: /** @@ -69,14 +70,6 @@ public: */ Leader(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method sends a MGMT_DATASET_CHANGED message to commissioner. * @@ -119,7 +112,7 @@ private: kTimeoutLeaderPetition = 50, ///< TIMEOUT_LEAD_PET (seconds) }; - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); static void HandlePetition(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -138,6 +131,8 @@ private: void ResignCommissioner(void); + static Leader &GetOwner(const Context &aContext); + Coap::Resource mPetition; Coap::Resource mKeepAlive; Timer mTimer; @@ -146,7 +141,6 @@ private: CommissionerIdTlv mCommissionerId; uint16_t mSessionId; - ThreadNetif &mNetif; }; } // namespace MeshCoP diff --git a/src/core/meshcop/panid_query_client.cpp b/src/core/meshcop/panid_query_client.cpp index 947ea660f..b3f5aec9a 100644 --- a/src/core/meshcop/panid_query_client.cpp +++ b/src/core/meshcop/panid_query_client.cpp @@ -53,22 +53,18 @@ namespace ot { PanIdQueryClient::PanIdQueryClient(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mCallback(NULL), mContext(NULL), - mPanIdQuery(OT_URI_PATH_PANID_CONFLICT, &PanIdQueryClient::HandleConflict, this), - mNetif(aThreadNetif) + mPanIdQuery(OT_URI_PATH_PANID_CONFLICT, &PanIdQueryClient::HandleConflict, this) { - mNetif.GetCoap().AddResource(mPanIdQuery); -} - -otInstance *PanIdQueryClient::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mPanIdQuery); } otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, const Ip6::Address &aAddress, otCommissionerPanIdConflictCallback aCallback, void *aContext) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; MeshCoP::CommissionerSessionIdTlv sessionId; @@ -77,7 +73,7 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, cons Ip6::MessageInfo messageInfo; Message *message = NULL; - VerifyOrExit(mNetif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); header.Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); @@ -85,11 +81,11 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, cons header.AppendUriPathOptions(OT_URI_PATH_PANID_QUERY); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); sessionId.Init(); - sessionId.SetCommissionerSessionId(mNetif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -100,11 +96,11 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, uint32_t aChannelMask, cons panId.SetPanId(aPanId); SuccessOrExit(error = message->Append(&panId, sizeof(panId))); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent panid query"); @@ -131,6 +127,7 @@ void PanIdQueryClient::HandleConflict(void *aContext, otCoapHeader *aHeader, otM void PanIdQueryClient::HandleConflict(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); MeshCoP::PanIdTlv panId; MeshCoP::ChannelMask0Tlv channelMask; Ip6::MessageInfo responseInfo(aMessageInfo); @@ -151,7 +148,7 @@ void PanIdQueryClient::HandleConflict(Coap::Header &aHeader, Message &aMessage, mCallback(panId.GetPanId(), channelMask.GetMask(), mContext); } - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, responseInfo)); + SuccessOrExit(netif.GetCoap().SendEmptyAck(aHeader, responseInfo)); otLogInfoMeshCoP(GetInstance(), "sent panid query conflict response"); diff --git a/src/core/meshcop/panid_query_client.hpp b/src/core/meshcop/panid_query_client.hpp index fb6f62a75..dba6806c4 100644 --- a/src/core/meshcop/panid_query_client.hpp +++ b/src/core/meshcop/panid_query_client.hpp @@ -38,6 +38,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" @@ -49,7 +50,7 @@ class ThreadNetif; * This class implements handling PANID Query Requests. * */ -class PanIdQueryClient +class PanIdQueryClient: public ThreadNetifLocator { public: /** @@ -58,14 +59,6 @@ public: */ PanIdQueryClient(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method sends a PAN ID Query message. * @@ -91,8 +84,6 @@ private: void *mContext; Coap::Resource mPanIdQuery; - - ThreadNetif &mNetif; }; /** diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index 0b371338a..ce3b28a50 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -58,9 +58,9 @@ namespace ot { namespace Dhcp6 { Dhcp6Client::Dhcp6Client(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mTrickleTimer(aThreadNetif.GetIp6().mTimerScheduler, &Dhcp6Client::HandleTrickleTimer, NULL, this), mSocket(aThreadNetif.GetIp6().mUdp), - mNetif(aThreadNetif), mStartTime(0), mAddresses(NULL), mNumAddresses(0) @@ -76,11 +76,6 @@ Dhcp6Client::Dhcp6Client(ThreadNetif &aThreadNetif) : mIdentityAssociationAvail = &mIdentityAssociations[0]; } -otInstance *Dhcp6Client::GetInstance(void) -{ - return mNetif.GetInstance(); -} - void Dhcp6Client::UpdateAddresses(otInstance *aInstance, otDhcpAddress *aAddresses, uint32_t aNumAddresses, void *aContext) { @@ -336,10 +331,9 @@ exit: return rval; } -bool Dhcp6Client::HandleTrickleTimer(void *aContext) +bool Dhcp6Client::HandleTrickleTimer(TrickleTimer &aTrickleTimer) { - Dhcp6Client *obj = static_cast(aContext); - return obj->HandleTrickleTimer(); + return GetOwner(aTrickleTimer).HandleTrickleTimer(); } bool Dhcp6Client::HandleTrickleTimer(void) @@ -380,6 +374,7 @@ exit: otError Dhcp6Client::Solicit(uint16_t aRloc16) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message; Ip6::MessageInfo messageInfo; @@ -395,14 +390,14 @@ otError Dhcp6Client::Solicit(uint16_t aRloc16) SuccessOrExit(error = AppendRapidCommit(*message)); memset(&messageInfo, 0, sizeof(messageInfo)); - memcpy(messageInfo.GetPeerAddr().mFields.m8, mNetif.GetMle().GetMeshLocalPrefix(), 8); + memcpy(messageInfo.GetPeerAddr().mFields.m8, netif.GetMle().GetMeshLocalPrefix(), 8); messageInfo.GetPeerAddr().mFields.m16[4] = HostSwap16(0x0000); messageInfo.GetPeerAddr().mFields.m16[5] = HostSwap16(0x00ff); messageInfo.GetPeerAddr().mFields.m16[6] = HostSwap16(0xfe00); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aRloc16); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.mPeerPort = kDhcpServerPort; - messageInfo.mInterfaceId = mNetif.GetInterfaceId(); + messageInfo.mInterfaceId = netif.GetInterfaceId(); SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); otLogInfoIp6(GetInstance(), "solicit"); @@ -443,7 +438,7 @@ otError Dhcp6Client::AppendClientIdentifier(Message &aMessage) option.Init(); option.SetDuidType(kDuidLL); option.SetDuidHardwareType(kHardwareTypeEui64); - option.SetDuidLinkLayerAddress(mNetif.GetMac().GetExtAddress()); + option.SetDuidLinkLayerAddress(GetNetif().GetMac().GetExtAddress()); return aMessage.Append(&option, sizeof(option)); } @@ -614,7 +609,7 @@ otError Dhcp6Client::ProcessClientIdentifier(Message &aMessage, uint16_t aOffset (option.GetLength() == (sizeof(option) - sizeof(Dhcp6Option))) && (option.GetDuidType() == kDuidLL) && (option.GetDuidHardwareType() == kHardwareTypeEui64)) && - (!memcmp(option.GetDuidLinkLayerAddress(), mNetif.GetMac().GetExtAddress(), + (!memcmp(option.GetDuidLinkLayerAddress(), GetNetif().GetMac().GetExtAddress(), sizeof(Mac::ExtAddress)))), error = OT_ERROR_PARSE); exit: @@ -700,7 +695,7 @@ otError Dhcp6Client::ProcessIaAddress(Message &aMessage, uint16_t aOffset) address->mValidLifetime = option.GetValidLifetime(); address->mAddress.mPreferred = address->mPreferredLifetime != 0; address->mAddress.mValid = address->mValidLifetime != 0; - otIp6AddUnicastAddress(mNetif.GetInstance(), &address->mAddress); + otIp6AddUnicastAddress(GetNetif().GetInstance(), &address->mAddress); break; } } @@ -722,6 +717,17 @@ exit: return error; } +Dhcp6Client &Dhcp6Client::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Dhcp6Client &client = *static_cast(aContext.GetContext()); +#else + Dhcp6Client &client = otGetThreadNetif().GetDhcp6Client(); + OT_UNUSED_VARIABLE(aContext); +#endif + return client; +} + } // namespace Dhcp6 } // namespace ot diff --git a/src/core/net/dhcp6_client.hpp b/src/core/net/dhcp6_client.hpp index f467dcddc..4c6919089 100644 --- a/src/core/net/dhcp6_client.hpp +++ b/src/core/net/dhcp6_client.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "common/trickle_timer.hpp" @@ -167,7 +168,7 @@ private: * This class implements DHCPv6 Client. * */ -class Dhcp6Client +class Dhcp6Client: public ThreadNetifLocator { public: /** @@ -178,14 +179,6 @@ public: */ explicit Dhcp6Client(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method update addresses that shall be automatically created using DHCP. * @@ -226,13 +219,14 @@ private: otError ProcessStatusCode(Message &aMessage, uint16_t aOffset); otError ProcessIaAddress(Message &aMessage, uint16_t aOffset); - static bool HandleTrickleTimer(void *aContext); + static bool HandleTrickleTimer(TrickleTimer &aTrickleTimer); bool HandleTrickleTimer(void); + static Dhcp6Client &GetOwner(const Context &aContext); + TrickleTimer mTrickleTimer; Ip6::UdpSocket mSocket; - ThreadNetif &mNetif; uint8_t mTransactionId[kTransactionIdSize]; uint32_t mStartTime; diff --git a/src/core/net/dhcp6_server.cpp b/src/core/net/dhcp6_server.cpp index 8eb5c7fad..15c47707f 100644 --- a/src/core/net/dhcp6_server.cpp +++ b/src/core/net/dhcp6_server.cpp @@ -54,8 +54,8 @@ namespace ot { namespace Dhcp6 { Dhcp6Server::Dhcp6Server(ThreadNetif &aThreadNetif): - mSocket(aThreadNetif.GetIp6().mUdp), - mNetif(aThreadNetif) + ThreadNetifLocator(aThreadNetif), + mSocket(aThreadNetif.GetIp6().mUdp) { for (uint8_t i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) { @@ -69,10 +69,11 @@ Dhcp6Server::Dhcp6Server(ThreadNetif &aThreadNetif): otError Dhcp6Server::UpdateService(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; bool found; uint8_t i; - uint16_t rloc16 = mNetif.GetMle().GetRloc16(); + uint16_t rloc16 = netif.GetMle().GetRloc16(); Ip6::Address *address = NULL; otNetworkDataIterator iterator; otBorderRouterConfig config; @@ -91,15 +92,15 @@ otError Dhcp6Server::UpdateService(void) address = &(mAgentsAloc[i].GetAddress()); iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (mNetif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) + while (netif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) { if (!config.mDhcp) { continue; } - mNetif.GetNetworkDataLeader().GetContext(*static_cast(&(config.mPrefix.mPrefix)), - lowpanContext); + netif.GetNetworkDataLeader().GetContext(*static_cast(&(config.mPrefix.mPrefix)), + lowpanContext); if (address->mFields.m8[15] == lowpanContext.mContextId) { @@ -111,8 +112,8 @@ otError Dhcp6Server::UpdateService(void) if (!found) { - mNetif.GetNetworkDataLeader().GetContext(address->mFields.m8[15], lowpanContext); - mNetif.RemoveUnicastAddress(mAgentsAloc[i]); + netif.GetNetworkDataLeader().GetContext(address->mFields.m8[15], lowpanContext); + netif.RemoveUnicastAddress(mAgentsAloc[i]); mAgentsAloc[i].mValid = false; RemovePrefixAgent(lowpanContext.mPrefix); } @@ -121,7 +122,7 @@ otError Dhcp6Server::UpdateService(void) // add dhcp agent aloc and prefix delegation iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (mNetif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) + while (netif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) { found = false; @@ -130,8 +131,8 @@ otError Dhcp6Server::UpdateService(void) continue; } - mNetif.GetNetworkDataLeader().GetContext(*static_cast(&config.mPrefix.mPrefix), - lowpanContext); + netif.GetNetworkDataLeader().GetContext(*static_cast(&config.mPrefix.mPrefix), + lowpanContext); for (i = 0; i < OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES; i++) { @@ -155,7 +156,7 @@ otError Dhcp6Server::UpdateService(void) if (!mAgentsAloc[i].mValid) { address = &(mAgentsAloc[i].GetAddress()); - memcpy(address, mNetif.GetMle().GetMeshLocalPrefix(), 8); + memcpy(address, netif.GetMle().GetMeshLocalPrefix(), 8); address->mFields.m16[4] = HostSwap16(0x0000); address->mFields.m16[5] = HostSwap16(0x00ff); address->mFields.m16[6] = HostSwap16(0xfe00); @@ -164,7 +165,7 @@ otError Dhcp6Server::UpdateService(void) mAgentsAloc[i].mPrefixLength = 128; mAgentsAloc[i].mPreferred = true; mAgentsAloc[i].mValid = true; - mNetif.AddUnicastAddress(mAgentsAloc[i]); + netif.AddUnicastAddress(mAgentsAloc[i]); AddPrefixAgent(config.mPrefix); break; } @@ -466,7 +467,7 @@ otError Dhcp6Server::AppendServerIdentifier(Message &aMessage) option.Init(); option.SetDuidType(kDuidLL); option.SetDuidHardwareType(kHardwareTypeEui64); - option.SetDuidLinkLayerAddress(mNetif.GetMac().GetExtAddress()); + option.SetDuidLinkLayerAddress(GetNetif().GetMac().GetExtAddress()); SuccessOrExit(error = aMessage.Append(&option, sizeof(option))); exit: diff --git a/src/core/net/dhcp6_server.hpp b/src/core/net/dhcp6_server.hpp index 5d356532f..a89c4a632 100644 --- a/src/core/net/dhcp6_server.hpp +++ b/src/core/net/dhcp6_server.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "mac/mac_frame.hpp" #include "mac/mac.hpp" #include "net/dhcp6.hpp" @@ -99,7 +100,7 @@ private: otIp6Prefix mIp6Prefix; ///< prefix } OT_TOOL_PACKED_END; -class Dhcp6Server +class Dhcp6Server: public ThreadNetifLocator { public: /** @@ -149,8 +150,6 @@ private: Ip6::UdpSocket mSocket; - ThreadNetif &mNetif; - Ip6::NetifUnicastAddress mAgentsAloc[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; PrefixAgent mPrefixAgents[OPENTHREAD_CONFIG_NUM_DHCP_PREFIXES]; uint8_t mPrefixAgentsMask; diff --git a/src/core/net/dns_client.cpp b/src/core/net/dns_client.cpp index e40654efa..fc0c34ad9 100644 --- a/src/core/net/dns_client.cpp +++ b/src/core/net/dns_client.cpp @@ -35,6 +35,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "net/udp6.hpp" +#include "thread/thread_netif.hpp" #if OPENTHREAD_ENABLE_DNS_CLIENT @@ -381,9 +382,9 @@ void Client::FinalizeDnsTransaction(Message &aQuery, const QueryMetadata &aQuery } } -void Client::HandleRetransmissionTimer(void *aContext) +void Client::HandleRetransmissionTimer(Timer &aTimer) { - static_cast(aContext)->HandleRetransmissionTimer(); + GetOwner(aTimer).HandleRetransmissionTimer(); } void Client::HandleRetransmissionTimer(void) @@ -518,6 +519,17 @@ exit: return; } +Client &Client::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Client &client = *static_cast(aContext.GetContext()); +#else + Client &client = otGetThreadNetif().GetDnsClient(); + OT_UNUSED_VARIABLE(aContext); +#endif + return client; +} + } // namespace Coap } // namespace ot diff --git a/src/core/net/dns_client.hpp b/src/core/net/dns_client.hpp index d9947b404..8b6ab8283 100644 --- a/src/core/net/dns_client.hpp +++ b/src/core/net/dns_client.hpp @@ -46,7 +46,6 @@ namespace ot { namespace Dns { - /** * This class implements metadata required for DNS retransmission. * @@ -245,12 +244,14 @@ private: otIp6Address *aAddress, uint32_t aTtl, otError aResult); - static void HandleRetransmissionTimer(void *aContext); + static void HandleRetransmissionTimer(Timer &aTimer); void HandleRetransmissionTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); + static Client &GetOwner(const Context &aContext); + Ip6::UdpSocket mSocket; uint16_t mMessageId; diff --git a/src/core/net/icmp6.cpp b/src/core/net/icmp6.cpp index 7b59affda..13eda2373 100644 --- a/src/core/net/icmp6.cpp +++ b/src/core/net/icmp6.cpp @@ -51,21 +51,16 @@ namespace ot { namespace Ip6 { Icmp::Icmp(Ip6 &aIp6): + Ip6Locator(aIp6), mHandlers(NULL), mEchoSequence(1), - mIsEchoEnabled(true), - mIp6(aIp6) + mIsEchoEnabled(true) { } -otInstance *Icmp::GetInstance(void) -{ - return mIp6.GetInstance(); -} - Message *Icmp::NewMessage(uint16_t aReserved) { - return mIp6.NewMessage(sizeof(IcmpHeader) + aReserved); + return GetIp6().NewMessage(sizeof(IcmpHeader) + aReserved); } otError Icmp::RegisterHandler(IcmpHandler &aHandler) @@ -103,7 +98,7 @@ otError Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo SuccessOrExit(error = aMessage.Prepend(&icmpHeader, sizeof(icmpHeader))); aMessage.SetOffset(0); - SuccessOrExit(error = mIp6.SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6)); + SuccessOrExit(error = GetIp6().SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6)); otLogInfoIcmp(GetInstance(), "Sent echo request: (seq = %d)", icmpHeader.GetSequence()); @@ -121,7 +116,7 @@ otError Icmp::SendError(IcmpHeader::Type aType, IcmpHeader::Code aCode, const Me messageInfoLocal = aMessageInfo; - VerifyOrExit((message = mIp6.NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = GetIp6().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(sizeof(icmp6Header) + sizeof(aHeader))); message->Write(sizeof(icmp6Header), sizeof(aHeader), &aHeader); @@ -131,7 +126,7 @@ otError Icmp::SendError(IcmpHeader::Type aType, IcmpHeader::Code aCode, const Me icmp6Header.SetCode(aCode); message->Write(0, sizeof(icmp6Header), &icmp6Header); - SuccessOrExit(error = mIp6.SendDatagram(*message, messageInfoLocal, kProtoIcmp6)); + SuccessOrExit(error = GetIp6().SendDatagram(*message, messageInfoLocal, kProtoIcmp6)); otLogInfoIcmp(GetInstance(), "Sent ICMPv6 Error"); @@ -191,7 +186,7 @@ otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMe icmp6Header.Init(); icmp6Header.SetType(IcmpHeader::kTypeEchoReply); - if ((replyMessage = mIp6.NewMessage(0)) == NULL) + if ((replyMessage = GetIp6().NewMessage(0)) == NULL) { otLogDebgIcmp(GetInstance(), "Failed to allocate a new message"); ExitNow(); @@ -213,7 +208,7 @@ otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMe replyMessageInfo.SetInterfaceId(aMessageInfo.mInterfaceId); - SuccessOrExit(error = mIp6.SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6)); + SuccessOrExit(error = GetIp6().SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6)); replyMessage->Read(replyMessage->GetOffset(), sizeof(icmp6Header), &icmp6Header); otLogInfoIcmp(GetInstance(), "Sent Echo Reply (seq = %d)", icmp6Header.GetSequence()); diff --git a/src/core/net/icmp6.hpp b/src/core/net/icmp6.hpp index d17492de2..63fe7c5e0 100644 --- a/src/core/net/icmp6.hpp +++ b/src/core/net/icmp6.hpp @@ -37,6 +37,7 @@ #include #include "common/encoding.hpp" +#include "common/locator.hpp" #include "net/ip6_headers.hpp" using ot::Encoding::BigEndian::HostSwap16; @@ -219,7 +220,7 @@ private: * This class implements ICMPv6. * */ -class Icmp +class Icmp: public Ip6Locator { public: /** @@ -230,14 +231,6 @@ public: */ Icmp(Ip6 &aIp6); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method returns a new ICMP message with sufficient header space reserved. * @@ -337,8 +330,6 @@ private: uint16_t mEchoSequence; bool mIsEchoEnabled; - - Ip6 &mIp6; }; /** diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index 9a6d213c8..d0dc0cd7a 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -421,9 +421,9 @@ exit: return error; } -void Ip6::HandleSendQueue(void *aContext) +void Ip6::HandleSendQueue(Tasklet &aTasklet) { - static_cast(aContext)->HandleSendQueue(); + GetOwner(aTasklet).HandleSendQueue(); } void Ip6::HandleSendQueue(void) @@ -1119,6 +1119,17 @@ otInstance *Ip6::GetInstance(void) return otInstanceFromIp6(this); } +Ip6 &Ip6::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Ip6 &ip6 = *static_cast(aContext.GetContext()); +#else + Ip6 &ip6 = otGetIp6(); + OT_UNUSED_VARIABLE(aContext); +#endif + return ip6; +} + const char *Ip6::IpProtoToString(IpProto aIpProto) { const char *retval; diff --git a/src/core/net/ip6.hpp b/src/core/net/ip6.hpp index 615e751b1..002a16eae 100644 --- a/src/core/net/ip6.hpp +++ b/src/core/net/ip6.hpp @@ -377,7 +377,7 @@ public: TimerScheduler mTimerScheduler; private: - static void HandleSendQueue(void *aContext); + static void HandleSendQueue(Tasklet &aTasklet); void HandleSendQueue(void); otError ProcessReceiveCallback(const Message &aMessage, const MessageInfo &aMessageInfo, uint8_t aIpProto, @@ -393,6 +393,8 @@ private: otError HandlePayload(Message &aMessage, MessageInfo &aMessageInfo, uint8_t aIpProto); int8_t FindForwardInterfaceId(const MessageInfo &aMessageInfo); + static Ip6 &GetOwner(const Context &aContext); + bool mForwardingEnabled; PriorityQueue mSendQueue; diff --git a/src/core/net/ip6_mpl.cpp b/src/core/net/ip6_mpl.cpp index 4393f66b8..ef718d964 100644 --- a/src/core/net/ip6_mpl.cpp +++ b/src/core/net/ip6_mpl.cpp @@ -37,6 +37,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/message.hpp" #include "net/ip6.hpp" @@ -55,7 +56,7 @@ void MplBufferedMessageMetadata::GenerateNextTransmissionTime(uint32_t aCurrentT } Mpl::Mpl(Ip6 &aIp6): - mIp6(aIp6), + Ip6Locator(aIp6), mSeedSetTimer(aIp6.mTimerScheduler, &Mpl::HandleSeedSetTimer, this), mRetransmissionTimer(aIp6.mTimerScheduler, &Mpl::HandleRetransmissionTimer, this), mTimerExpirations(0), @@ -250,12 +251,12 @@ exit: return error; } -void Mpl::HandleRetransmissionTimer(void *aContext) +void Mpl::HandleRetransmissionTimer(Timer &aTimer) { - static_cast(aContext)->HandleRetransmissionTimer(); + GetOwner(aTimer).HandleRetransmissionTimer(); } -void Mpl::HandleRetransmissionTimer() +void Mpl::HandleRetransmissionTimer(void) { uint32_t now = Timer::GetNow(); uint32_t nextDelta = 0xffffffff; @@ -293,7 +294,7 @@ void Mpl::HandleRetransmissionTimer() messageCopy->SetSubType(Message::kSubTypeMplRetransmission); } - mIp6.EnqueueDatagram(*messageCopy); + GetIp6().EnqueueDatagram(*messageCopy); } messageMetadata.GenerateNextTransmissionTime(now, kDataMessageInterval); @@ -318,7 +319,7 @@ void Mpl::HandleRetransmissionTimer() // Remove the extra metadata from the MPL Data Message. messageMetadata.RemoveFrom(*message); - mIp6.EnqueueDatagram(*message); + GetIp6().EnqueueDatagram(*message); } else { @@ -337,12 +338,12 @@ void Mpl::HandleRetransmissionTimer() } } -void Mpl::HandleSeedSetTimer(void *aContext) +void Mpl::HandleSeedSetTimer(Timer &aTimer) { - static_cast(aContext)->HandleSeedSetTimer(); + GetOwner(aTimer).HandleSeedSetTimer(); } -void Mpl::HandleSeedSetTimer() +void Mpl::HandleSeedSetTimer(void) { bool startTimer = false; @@ -361,5 +362,16 @@ void Mpl::HandleSeedSetTimer() } } +Mpl &Mpl::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Mpl &mpl = *static_cast(aContext.GetContext()); +#else + Mpl &mpl = otGetIp6().mMpl; + OT_UNUSED_VARIABLE(aContext); +#endif + return mpl; +} + } // namespace Ip6 } // namespace ot diff --git a/src/core/net/ip6_mpl.hpp b/src/core/net/ip6_mpl.hpp index 617197813..a035cfdaa 100644 --- a/src/core/net/ip6_mpl.hpp +++ b/src/core/net/ip6_mpl.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "net/ip6_headers.hpp" @@ -427,7 +428,7 @@ private: * This class implements MPL message processing. * */ -class Mpl +class Mpl: public Ip6Locator { public: /** @@ -526,13 +527,13 @@ private: void UpdateBufferedSet(uint16_t aSeedId, uint8_t aSequence); void AddBufferedMessage(Message &aMessage, uint16_t aSeedId, uint8_t aSequence, bool aIsOutbound); - static void HandleSeedSetTimer(void *aContext); + static void HandleSeedSetTimer(Timer &aTimer); void HandleSeedSetTimer(void); - static void HandleRetransmissionTimer(void *aContext); + static void HandleRetransmissionTimer(Timer &aTimer); void HandleRetransmissionTimer(void); - Ip6 &mIp6; + static Mpl &GetOwner(const Context &aContext); Timer mSeedSetTimer; Timer mRetransmissionTimer; diff --git a/src/core/net/ip6_routes.cpp b/src/core/net/ip6_routes.cpp index 076ce67a1..3305b518c 100644 --- a/src/core/net/ip6_routes.cpp +++ b/src/core/net/ip6_routes.cpp @@ -44,8 +44,8 @@ namespace ot { namespace Ip6 { Routes::Routes(Ip6 &aIp6): - mRoutes(NULL), - mIp6(aIp6) + Ip6Locator(aIp6), + mRoutes(NULL) { } @@ -117,7 +117,7 @@ int8_t Routes::Lookup(const Address &aSource, const Address &aDestination) rval = cur->mInterfaceId; } - for (Netif *netif = mIp6.GetNetifList(); netif; netif = netif->GetNext()) + for (Netif *netif = GetIp6().GetNetifList(); netif; netif = netif->GetNext()) { if (netif->RouteLookup(aSource, aDestination, &prefixMatch) == OT_ERROR_NONE && static_cast(prefixMatch) > maxPrefixMatch) diff --git a/src/core/net/ip6_routes.hpp b/src/core/net/ip6_routes.hpp index 999d828b2..a22a1585b 100644 --- a/src/core/net/ip6_routes.hpp +++ b/src/core/net/ip6_routes.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "common/message.hpp" #include "net/ip6_address.hpp" #include "net/ip6_routes.hpp" @@ -68,7 +69,7 @@ struct Route * This class implements IPv6 route management. * */ -class Routes +class Routes: public Ip6Locator { public: /** @@ -114,7 +115,6 @@ public: private: Route *mRoutes; - Ip6 &mIp6; }; /** diff --git a/src/core/net/netif.cpp b/src/core/net/netif.cpp index e79f1af34..6652b1993 100644 --- a/src/core/net/netif.cpp +++ b/src/core/net/netif.cpp @@ -34,6 +34,7 @@ #include "netif.hpp" +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/message.hpp" @@ -43,7 +44,7 @@ namespace ot { namespace Ip6 { Netif::Netif(Ip6 &aIp6, int8_t aInterfaceId): - mIp6(aIp6), + Ip6Locator(aIp6), mCallbacks(NULL), mUnicastAddresses(NULL), mMulticastAddresses(NULL), @@ -444,9 +445,9 @@ void Netif::SetStateChangedFlags(uint32_t aFlags) mStateChangedTask.Post(); } -void Netif::HandleStateChangedTask(void *aContext) +void Netif::HandleStateChangedTask(Tasklet &aTasklet) { - static_cast(aContext)->HandleStateChangedTask(); + GetOwner(aTasklet).HandleStateChangedTask(); } void Netif::HandleStateChangedTask(void) @@ -461,5 +462,16 @@ void Netif::HandleStateChangedTask(void) } } +Netif &Netif::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Netif &netif = *static_cast(aContext.GetContext()); +#else + Netif &netif = otGetThreadNetif(); + OT_UNUSED_VARIABLE(aContext); +#endif + return netif; +} + } // namespace Ip6 } // namespace ot diff --git a/src/core/net/netif.hpp b/src/core/net/netif.hpp index 5a38abafa..c865c9fff 100644 --- a/src/core/net/netif.hpp +++ b/src/core/net/netif.hpp @@ -34,6 +34,7 @@ #ifndef NET_NETIF_HPP_ #define NET_NETIF_HPP_ +#include "common/locator.hpp" #include "common/message.hpp" #include "common/tasklet.hpp" #include "mac/mac_frame.hpp" @@ -247,7 +248,7 @@ private: * This class implements an IPv6 network interface. * */ -class Netif +class Netif: public Ip6Locator { friend class Ip6; @@ -261,14 +262,6 @@ public: */ Netif(Ip6 &aIp6, int8_t aInterfaceId); - /** - * This method returns a reference to the IPv6 network object. - * - * @returns A reference to the IPv6 network object. - * - */ - Ip6 &GetIp6(void) { return mIp6; } - /** * This method returns the next network interface in the list. * @@ -527,12 +520,10 @@ public: virtual otError RouteLookup(const Address &aSource, const Address &aDestination, uint8_t *aPrefixMatch) = 0; -protected: - Ip6 &mIp6; - private: - static void HandleStateChangedTask(void *aContext); + static void HandleStateChangedTask(Tasklet &aTasklet); void HandleStateChangedTask(void); + static Netif &GetOwner(const Context &aContext); NetifCallback *mCallbacks; NetifUnicastAddress *mUnicastAddresses; diff --git a/src/core/net/udp6.cpp b/src/core/net/udp6.cpp index 9a497c67a..1b38cc43d 100644 --- a/src/core/net/udp6.cpp +++ b/src/core/net/udp6.cpp @@ -128,9 +128,9 @@ exit: } Udp::Udp(Ip6 &aIp6): + Ip6Locator(aIp6), mEphemeralPort(kDynamicPortMin), - mSockets(NULL), - mIp6(aIp6) + mSockets(NULL) { } @@ -192,12 +192,12 @@ uint16_t Udp::GetEphemeralPort(void) Message *Udp::NewMessage(uint16_t aReserved) { - return mIp6.NewMessage(sizeof(UdpHeader) + aReserved); + return GetIp6().NewMessage(sizeof(UdpHeader) + aReserved); } otError Udp::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto) { - return mIp6.SendDatagram(aMessage, aMessageInfo, aIpProto); + return GetIp6().SendDatagram(aMessage, aMessageInfo, aIpProto); } otError Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo) diff --git a/src/core/net/udp6.hpp b/src/core/net/udp6.hpp index 5c383b572..4cd538b7c 100644 --- a/src/core/net/udp6.hpp +++ b/src/core/net/udp6.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "net/ip6_headers.hpp" namespace ot { @@ -160,7 +161,7 @@ private: * This class implements core UDP message handling. * */ -class Udp +class Udp: public Ip6Locator { friend class UdpSocket; @@ -256,8 +257,6 @@ private: }; uint16_t mEphemeralPort; UdpSocket *mSockets; - - Ip6 &mIp6; }; OT_TOOL_PACKED_BEGIN diff --git a/src/core/openthread-instance.h b/src/core/openthread-instance.h index 2df21cc55..429afb541 100644 --- a/src/core/openthread-instance.h +++ b/src/core/openthread-instance.h @@ -44,11 +44,10 @@ #include #include "openthread-core-config.h" - +#include "openthread-single-instance.h" #if OPENTHREAD_ENABLE_RAW_LINK_API #include "api/link_raw.hpp" #endif - #include "coap/coap.hpp" #include "crypto/mbedtls.hpp" #include "net/ip6.hpp" @@ -78,7 +77,7 @@ typedef struct otInstance // State // -#ifndef OPENTHREAD_MULTIPLE_INSTANCE +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES ot::Crypto::MbedTls mMbedTls; #endif ot::Ip6::Ip6 mIp6; diff --git a/src/core/openthread-single-instance.h b/src/core/openthread-single-instance.h new file mode 100644 index 000000000..32ca540d3 --- /dev/null +++ b/src/core/openthread-single-instance.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2017, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * @brief + * This file defines the getter functions for single instance OpenThread objects. + */ + +#ifndef SINGLE_OPENTHREAD_INSTANCE_H_ +#define SINGLE_OPENTHREAD_INSTANCE_H_ + +#include + +#include + +#include "openthread-core-config.h" + + +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + +namespace ot { + +class ThreadNetif; +class MeshForwarder; +class TimerScheduler; +class TaskletScheduler; +namespace Ip6 { class Ip6; } + +} // namespace ot + +/** + * This function returns a pointer to the single otInstance (if initialized and ready). + * + * @returns A pointer to single otInstance structure, or NULL if the instance is not ready, i.e. either it is not yet + * initialized (no call to `otInstanceInitSingle()`) or it is finalized (call to `otInstanceFinalize()`). + * + */ +otInstance *otGetInstance(void); + +/** + * This function returns a reference to the single thread network interface instance. + * + * @returns A reference to the thread network interface instance. + * + */ +ot::ThreadNetif &otGetThreadNetif(void); + +/** + * This function returns a reference to the single MeshForwarder instance. + * + * @returns A reference to the MeshForwarder instance. + * + */ +ot::MeshForwarder &otGetMeshForwarder(void); + +/** + * This function returns a reference to the single TimerScheduler instance. + * + * @returns A reference to the TimerScheduler instance. + * + */ +ot::TimerScheduler &otGetTimerScheduler(void); + +/** + * This function returns a reference to the single TaskletShceduler instance. + * + * @returns A reference to the TaskletShceduler instance. + * + */ +ot::TaskletScheduler &otGetTaskletScheduler(void); + +/** + * This function returns a reference to the single Ip6 instance. + * + * @returns A reference to the Ip6 instance. + * + */ +ot::Ip6::Ip6 &otGetIp6(void); + +#endif // #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + +#endif // SINGLE_OPENTHREAD_INSTANCE_H_ diff --git a/src/core/thread/address_resolver.cpp b/src/core/thread/address_resolver.cpp index e41569be4..fbac186d3 100644 --- a/src/core/thread/address_resolver.cpp +++ b/src/core/thread/address_resolver.cpp @@ -41,6 +41,7 @@ #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -58,25 +59,20 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { AddressResolver::AddressResolver(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mAddressError(OT_URI_PATH_ADDRESS_ERROR, &AddressResolver::HandleAddressError, this), mAddressQuery(OT_URI_PATH_ADDRESS_QUERY, &AddressResolver::HandleAddressQuery, this), mAddressNotification(OT_URI_PATH_ADDRESS_NOTIFY, &AddressResolver::HandleAddressNotification, this), mIcmpHandler(&AddressResolver::HandleIcmpReceive, this), - mTimer(aThreadNetif.GetIp6().mTimerScheduler, &AddressResolver::HandleTimer, this), - mNetif(aThreadNetif) + mTimer(aThreadNetif.GetIp6().mTimerScheduler, &AddressResolver::HandleTimer, this) { Clear(); - mNetif.GetCoap().AddResource(mAddressError); - mNetif.GetCoap().AddResource(mAddressQuery); - mNetif.GetCoap().AddResource(mAddressNotification); + aThreadNetif.GetCoap().AddResource(mAddressError); + aThreadNetif.GetCoap().AddResource(mAddressQuery); + aThreadNetif.GetCoap().AddResource(mAddressNotification); - mNetif.GetIp6().mIcmp.RegisterHandler(mIcmpHandler); -} - -otInstance *AddressResolver::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetIp6().mIcmp.RegisterHandler(mIcmpHandler); } void AddressResolver::Clear() @@ -233,6 +229,7 @@ exit: otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) { + ThreadNetif &netif = GetNetif(); otError error; Message *message; Coap::Header header; @@ -243,7 +240,7 @@ otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_QUERY); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); targetTlv.Init(); targetTlv.SetTarget(aEid); @@ -251,11 +248,11 @@ otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) messageInfo.GetPeerAddr().mFields.m16[0] = HostSwap16(0xff03); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(0x0002); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoArp(GetInstance(), "Sent address query"); @@ -285,6 +282,7 @@ void AddressResolver::HandleAddressNotification(void *aContext, otCoapHeader *aH void AddressResolver::HandleAddressNotification(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; ThreadRloc16Tlv rloc16Tlv; @@ -351,12 +349,12 @@ void AddressResolver::HandleAddressNotification(Coap::Header &aHeader, Message & mCache[i].mState = Cache::kStateCached; MarkCacheEntryAsUsed(mCache[i]); - if (mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) + if (netif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) { otLogInfoArp(GetInstance(), "Sent address notification acknowledgment"); } - mNetif.GetMeshForwarder().HandleResolved(*targetTlv.GetTarget(), OT_ERROR_NONE); + netif.GetMeshForwarder().HandleResolved(*targetTlv.GetTarget(), OT_ERROR_NONE); break; } } @@ -368,6 +366,7 @@ exit: otError AddressResolver::SendAddressError(const ThreadTargetTlv &aTarget, const ThreadMeshLocalEidTlv &aEid, const Ip6::Address *aDestination) { + ThreadNetif &netif = GetNetif(); otError error; Message *message; Coap::Header header; @@ -378,7 +377,7 @@ otError AddressResolver::SendAddressError(const ThreadTargetTlv &aTarget, const header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_ERROR); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Append(&aTarget, sizeof(aTarget))); SuccessOrExit(error = message->Append(&aEid, sizeof(aEid))); @@ -393,11 +392,11 @@ otError AddressResolver::SendAddressError(const ThreadTargetTlv &aTarget, const memcpy(&messageInfo.GetPeerAddr(), aDestination, sizeof(messageInfo.GetPeerAddr())); } - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoArp(GetInstance(), "Sent address error"); @@ -422,6 +421,7 @@ void AddressResolver::HandleAddressError(void *aContext, otCoapHeader *aHeader, void AddressResolver::HandleAddressError(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; @@ -437,7 +437,7 @@ void AddressResolver::HandleAddressError(Coap::Header &aHeader, Message &aMessag if (aHeader.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - if (mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) + if (netif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) { otLogInfoArp(GetInstance(), "Sent address error notification acknowledgment"); } @@ -449,18 +449,18 @@ void AddressResolver::HandleAddressError(Coap::Header &aHeader, Message &aMessag SuccessOrExit(error = ThreadTlv::GetTlv(aMessage, ThreadTlv::kMeshLocalEid, sizeof(mlIidTlv), mlIidTlv)); VerifyOrExit(mlIidTlv.IsValid(), error = OT_ERROR_PARSE); - for (const Ip6::NetifUnicastAddress *address = mNetif.GetUnicastAddresses(); address; address = address->GetNext()) + for (const Ip6::NetifUnicastAddress *address = netif.GetUnicastAddresses(); address; address = address->GetNext()) { if (memcmp(&address->mAddress, targetTlv.GetTarget(), sizeof(address->mAddress)) == 0 && - memcmp(mNetif.GetMle().GetMeshLocal64().GetIid(), mlIidTlv.GetIid(), 8)) + memcmp(netif.GetMle().GetMeshLocal64().GetIid(), mlIidTlv.GetIid(), 8)) { // Target EID matches address and Mesh Local EID differs - mNetif.RemoveUnicastAddress(*address); + netif.RemoveUnicastAddress(*address); ExitNow(); } } - children = mNetif.GetMle().GetChildren(&numChildren); + children = netif.GetMle().GetChildren(&numChildren); memcpy(&macAddr, mlIidTlv.GetIid(), sizeof(macAddr)); macAddr.m8[0] ^= 0x2; @@ -512,6 +512,7 @@ void AddressResolver::HandleAddressQuery(void *aContext, otCoapHeader *aHeader, void AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; ThreadLastTransactionTimeTlv lastTransactionTimeTlv; @@ -530,14 +531,14 @@ void AddressResolver::HandleAddressQuery(Coap::Header &aHeader, Message &aMessag lastTransactionTimeTlv.Init(); - if (mNetif.IsUnicastAddress(*targetTlv.GetTarget())) + if (netif.IsUnicastAddress(*targetTlv.GetTarget())) { - mlIidTlv.SetIid(mNetif.GetMle().GetMeshLocal64().GetIid()); + mlIidTlv.SetIid(netif.GetMle().GetMeshLocal64().GetIid()); SendAddressQueryResponse(targetTlv, mlIidTlv, NULL, aMessageInfo.GetPeerAddr()); ExitNow(); } - children = mNetif.GetMle().GetChildren(&numChildren); + children = netif.GetMle().GetChildren(&numChildren); for (int i = 0; i < numChildren; i++) { @@ -571,6 +572,7 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv, const Ip6::Address &aDestination) { + ThreadNetif &netif = GetNetif(); otError error; Message *message; Coap::Header header; @@ -581,13 +583,13 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_NOTIFY); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Append(&aTargetTlv, sizeof(aTargetTlv))); SuccessOrExit(error = message->Append(&aMlIidTlv, sizeof(aMlIidTlv))); rloc16Tlv.Init(); - rloc16Tlv.SetRloc16(mNetif.GetMle().GetRloc16()); + rloc16Tlv.SetRloc16(netif.GetMle().GetRloc16()); SuccessOrExit(error = message->Append(&rloc16Tlv, sizeof(rloc16Tlv))); if (aLastTransactionTimeTlv != NULL) @@ -596,10 +598,10 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv &aTargetTlv } messageInfo.SetPeerAddr(aDestination); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoArp(GetInstance(), "Sent address notification"); @@ -611,9 +613,9 @@ exit: } } -void AddressResolver::HandleTimer(void *aContext) +void AddressResolver::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void AddressResolver::HandleTimer() @@ -647,7 +649,7 @@ void AddressResolver::HandleTimer() mCache[i].mRetryTimeout = kAddressQueryMaxRetryDelay; } - mNetif.GetMeshForwarder().HandleResolved(mCache[i].mTarget, OT_ERROR_DROP); + GetNetif().GetMeshForwarder().HandleResolved(mCache[i].mTarget, OT_ERROR_DROP); } } else if (mCache[i].mRetryTimeout > 0) @@ -695,6 +697,17 @@ exit: OT_UNUSED_VARIABLE(aMessageInfo); } +AddressResolver &AddressResolver::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + AddressResolver &resolver = *static_cast(aContext.GetContext()); +#else + AddressResolver &resolver = otGetThreadNetif().GetAddressResolver(); + OT_UNUSED_VARIABLE(aContext); +#endif + return resolver; +} + } // namespace ot #endif // OPENTHREAD_FTD diff --git a/src/core/thread/address_resolver.hpp b/src/core/thread/address_resolver.hpp index 711ac28dd..99daa6982 100644 --- a/src/core/thread/address_resolver.hpp +++ b/src/core/thread/address_resolver.hpp @@ -38,6 +38,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "mac/mac.hpp" #include "net/icmp6.hpp" @@ -64,7 +65,7 @@ class ThreadTargetTlv; * This class implements the EID-to-RLOC mapping and caching. * */ -class AddressResolver +class AddressResolver: public ThreadNetifLocator { public: /** @@ -73,14 +74,6 @@ public: */ explicit AddressResolver(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method clears the EID-to-RLOC cache. * @@ -186,17 +179,17 @@ private: const otIcmp6Header *aIcmpHeader); void HandleIcmpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo, const Ip6::IcmpHeader &aIcmpHeader); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); + static AddressResolver &GetOwner(const Context &aContext); + Coap::Resource mAddressError; Coap::Resource mAddressQuery; Coap::Resource mAddressNotification; Cache mCache[kCacheEntries]; Ip6::IcmpHandler mIcmpHandler; Timer mTimer; - - ThreadNetif &mNetif; }; /** diff --git a/src/core/thread/announce_begin_server.cpp b/src/core/thread/announce_begin_server.cpp index 7920bcf43..d3add4ae4 100644 --- a/src/core/thread/announce_begin_server.cpp +++ b/src/core/thread/announce_begin_server.cpp @@ -39,6 +39,7 @@ #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -52,20 +53,15 @@ using ot::Encoding::BigEndian::HostSwap32; namespace ot { AnnounceBeginServer::AnnounceBeginServer(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mChannelMask(0), mPeriod(0), mCount(0), mChannel(0), mTimer(aThreadNetif.GetIp6().mTimerScheduler, &AnnounceBeginServer::HandleTimer, this), - mAnnounceBegin(OT_URI_PATH_ANNOUNCE_BEGIN, &AnnounceBeginServer::HandleRequest, this), - mNetif(aThreadNetif) + mAnnounceBegin(OT_URI_PATH_ANNOUNCE_BEGIN, &AnnounceBeginServer::HandleRequest, this) { - mNetif.GetCoap().AddResource(mAnnounceBegin); -} - -otInstance *AnnounceBeginServer::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mAnnounceBegin); } otError AnnounceBeginServer::SendAnnounce(uint32_t aChannelMask) @@ -123,7 +119,7 @@ void AnnounceBeginServer::HandleRequest(Coap::Header &aHeader, Message &aMessage if (aHeader.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, responseInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, responseInfo)); otLogInfoMeshCoP(GetInstance(), "sent announce begin response"); } @@ -131,14 +127,14 @@ exit: return; } -void AnnounceBeginServer::HandleTimer(void *aContext) +void AnnounceBeginServer::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void AnnounceBeginServer::HandleTimer(void) { - mNetif.GetMle().SendAnnounce(mChannel++, false); + GetNetif().GetMle().SendAnnounce(mChannel++, false); while (mCount > 0) { @@ -158,4 +154,15 @@ void AnnounceBeginServer::HandleTimer(void) } } +AnnounceBeginServer &AnnounceBeginServer::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + AnnounceBeginServer &server = *static_cast(aContext.GetContext()); +#else + AnnounceBeginServer &server = otGetThreadNetif().GetAnnounceBeginServer(); + OT_UNUSED_VARIABLE(aContext); +#endif + return server; +} + } // namespace ot diff --git a/src/core/thread/announce_begin_server.hpp b/src/core/thread/announce_begin_server.hpp index a2370e72b..9845ac8c4 100644 --- a/src/core/thread/announce_begin_server.hpp +++ b/src/core/thread/announce_begin_server.hpp @@ -38,18 +38,17 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "net/ip6_address.hpp" namespace ot { -class ThreadNetif; - /** * This class implements handling Announce Begin Requests. * */ -class AnnounceBeginServer +class AnnounceBeginServer: public ThreadNetifLocator { public: /** @@ -58,14 +57,6 @@ public: */ AnnounceBeginServer(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method begins the MLE Announce transmission process using Count=3 and Period=1s. * @@ -99,9 +90,11 @@ private: const otMessageInfo *aMessageInfo); void HandleRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); + static AnnounceBeginServer &GetOwner(const Context &aContext); + uint32_t mChannelMask; uint16_t mPeriod; uint8_t mCount; @@ -110,7 +103,6 @@ private: Timer mTimer; Coap::Resource mAnnounceBegin; - ThreadNetif &mNetif; }; /** diff --git a/src/core/thread/data_poll_manager.cpp b/src/core/thread/data_poll_manager.cpp index bffc0d38a..9151eeb12 100644 --- a/src/core/thread/data_poll_manager.cpp +++ b/src/core/thread/data_poll_manager.cpp @@ -37,6 +37,7 @@ #include "data_poll_manager.hpp" #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/logging.hpp" #include "common/message.hpp" @@ -49,7 +50,7 @@ namespace ot { DataPollManager::DataPollManager(MeshForwarder &aMeshForwarder): - mMeshForwarder(aMeshForwarder), + MeshForwarderLocator(aMeshForwarder), mTimer(aMeshForwarder.GetNetif().GetIp6().mTimerScheduler, &DataPollManager::HandlePollTimer, this), mTimerStartTime(0), mExternalPollPeriod(0), @@ -64,17 +65,12 @@ DataPollManager::DataPollManager(MeshForwarder &aMeshForwarder): { } -otInstance *DataPollManager::GetInstance(void) -{ - return mMeshForwarder.GetInstance(); -} - otError DataPollManager::StartPolling(void) { otError error = OT_ERROR_NONE; VerifyOrExit(!mEnabled, error = OT_ERROR_ALREADY); - VerifyOrExit((mMeshForwarder.GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) == 0, + VerifyOrExit((GetMeshForwarder().GetNetif().GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) == 0, error = OT_ERROR_INVALID_STATE); mEnabled = true; @@ -98,23 +94,24 @@ void DataPollManager::StopPolling(void) otError DataPollManager::SendDataPoll(void) { + MeshForwarder &meshForwarder = GetMeshForwarder(); otError error; Message *message; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(!mMeshForwarder.GetNetif().GetMac().GetRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(!meshForwarder.GetNetif().GetMac().GetRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); mTimer.Stop(); - for (message = mMeshForwarder.GetSendQueue().GetHead(); message; message = message->GetNext()) + for (message = meshForwarder.GetSendQueue().GetHead(); message; message = message->GetNext()) { VerifyOrExit(message->GetType() != Message::kTypeMacDataPoll, error = OT_ERROR_ALREADY); } - message = mMeshForwarder.GetNetif().GetIp6().mMessagePool.New(Message::kTypeMacDataPoll, 0); + message = meshForwarder.GetNetif().GetIp6().mMessagePool.New(Message::kTypeMacDataPoll, 0); VerifyOrExit(message != NULL, error = OT_ERROR_NO_BUFS); - error = mMeshForwarder.SendMessage(*message); + error = meshForwarder.SendMessage(*message); if (error != OT_ERROR_NONE) { @@ -380,7 +377,7 @@ uint32_t DataPollManager::CalculatePollPeriod(void) const if (period == 0) { - period = Timer::SecToMsec(mMeshForwarder.GetNetif().GetMle().GetTimeout()) - + period = Timer::SecToMsec(GetMeshForwarder().GetNetif().GetMle().GetTimeout()) - static_cast(kRetxPollPeriod) * kMaxPollRetxAttempts; if (period == 0) @@ -392,9 +389,20 @@ uint32_t DataPollManager::CalculatePollPeriod(void) const return period; } -void DataPollManager::HandlePollTimer(void *aContext) +void DataPollManager::HandlePollTimer(Timer &aTimer) { - static_cast(aContext)->SendDataPoll(); + GetOwner(aTimer).SendDataPoll(); +} + +DataPollManager &DataPollManager::GetOwner(Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + DataPollManager &manager = *static_cast(aContext.GetContext()); +#else + DataPollManager &manager = otGetMeshForwarder().GetDataPollManager(); + OT_UNUSED_VARIABLE(aContext); +#endif + return manager; } } // namespace ot diff --git a/src/core/thread/data_poll_manager.hpp b/src/core/thread/data_poll_manager.hpp index af9ed9dd1..ac689279a 100644 --- a/src/core/thread/data_poll_manager.hpp +++ b/src/core/thread/data_poll_manager.hpp @@ -38,13 +38,12 @@ #include "openthread-core-config.h" #include "common/code_utils.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" namespace ot { -class MeshForwarder; - /** * @addtogroup core-data-poll-manager * @@ -59,7 +58,7 @@ class MeshForwarder; * */ -class DataPollManager +class DataPollManager: public MeshForwarderLocator { public: enum @@ -76,14 +75,6 @@ public: */ explicit DataPollManager(MeshForwarder &aMeshForwarder); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method instructs the data poll manager to start sending periodic data polls. * @@ -218,9 +209,9 @@ private: void ScheduleNextPoll(PollPeriodSelector aPollPeriodSelector); uint32_t CalculatePollPeriod(void) const; - static void HandlePollTimer(void *aContext); + static void HandlePollTimer(Timer &aTimer); + static DataPollManager &GetOwner(Context &aContext); - MeshForwarder &mMeshForwarder; Timer mTimer; uint32_t mTimerStartTime; uint32_t mExternalPollPeriod; diff --git a/src/core/thread/energy_scan_server.cpp b/src/core/thread/energy_scan_server.cpp index fb8c3a3ad..bcf5b4b3c 100644 --- a/src/core/thread/energy_scan_server.cpp +++ b/src/core/thread/energy_scan_server.cpp @@ -34,14 +34,11 @@ #define WPP_NAME "energy_scan_server.tmh" #include - - #include "energy_scan_server.hpp" - - #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -54,6 +51,7 @@ namespace ot { EnergyScanServer::EnergyScanServer(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mChannelMask(0), mChannelMaskCurrent(0), mPeriod(0), @@ -62,18 +60,12 @@ EnergyScanServer::EnergyScanServer(ThreadNetif &aThreadNetif) : mActive(false), mScanResultsLength(0), mTimer(aThreadNetif.GetIp6().mTimerScheduler, &EnergyScanServer::HandleTimer, this), - mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this), - mNetif(aThreadNetif) + mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this) { mNetifCallback.Set(&EnergyScanServer::HandleNetifStateChanged, this); - mNetif.RegisterCallback(mNetifCallback); + aThreadNetif.RegisterCallback(mNetifCallback); - mNetif.GetCoap().AddResource(mEnergyScan); -} - -otInstance *EnergyScanServer::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mEnergyScan); } void EnergyScanServer::HandleRequest(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -119,7 +111,7 @@ void EnergyScanServer::HandleRequest(Coap::Header &aHeader, Message &aMessage, c if (aHeader.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, responseInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, responseInfo)); otLogInfoMeshCoP(GetInstance(), "sent energy scan query response"); } @@ -127,9 +119,9 @@ exit: return; } -void EnergyScanServer::HandleTimer(void *aContext) +void EnergyScanServer::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void EnergyScanServer::HandleTimer(void) @@ -140,7 +132,7 @@ void EnergyScanServer::HandleTimer(void) { // grab the lowest channel to scan uint32_t channelMask = mChannelMaskCurrent & ~(mChannelMaskCurrent - 1); - mNetif.GetMac().EnergyScan(channelMask, mScanDuration, HandleScanResult, this); + GetNetif().GetMac().EnergyScan(channelMask, mScanDuration, HandleScanResult, this); } else { @@ -203,7 +195,7 @@ otError EnergyScanServer::SendReport(void) header.AppendUriPathOptions(OT_URI_PATH_ENERGY_REPORT); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(GetNetif().GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); channelMask.Init(); @@ -215,10 +207,10 @@ otError EnergyScanServer::SendReport(void) SuccessOrExit(error = message->Append(&energyList, sizeof(energyList))); SuccessOrExit(error = message->Append(mScanResults, mScanResultsLength)); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(mCommissioner); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = GetNetif().GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent scan results"); @@ -243,11 +235,22 @@ void EnergyScanServer::HandleNetifStateChanged(uint32_t aFlags) { if ((aFlags & OT_CHANGED_THREAD_NETDATA) != 0 && !mActive && - mNetif.GetNetworkDataLeader().GetCommissioningData() == NULL) + GetNetif().GetNetworkDataLeader().GetCommissioningData() == NULL) { mActive = false; mTimer.Stop(); } } +EnergyScanServer &EnergyScanServer::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + EnergyScanServer &server = *static_cast(aContext.GetContext()); +#else + EnergyScanServer &server = otGetThreadNetif().GetEnergyScanServer(); + OT_UNUSED_VARIABLE(aContext); +#endif + return server; +} + } // namespace ot diff --git a/src/core/thread/energy_scan_server.hpp b/src/core/thread/energy_scan_server.hpp index 52a0dad76..b2e210465 100644 --- a/src/core/thread/energy_scan_server.hpp +++ b/src/core/thread/energy_scan_server.hpp @@ -38,6 +38,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" @@ -54,7 +55,7 @@ class ThreadTargetTlv; * This class implements handling Energy Scan Requests. * */ -class EnergyScanServer +class EnergyScanServer: public ThreadNetifLocator { public: /** @@ -63,14 +64,6 @@ public: */ EnergyScanServer(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - private: enum { @@ -85,7 +78,7 @@ private: static void HandleScanResult(void *aContext, otEnergyScanResult *aResult); void HandleScanResult(otEnergyScanResult *aResult); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); static void HandleNetifStateChanged(uint32_t aFlags, void *aContext); @@ -93,6 +86,8 @@ private: otError SendReport(void); + static EnergyScanServer &GetOwner(const Context &aContext); + Ip6::Address mCommissioner; uint32_t mChannelMask; uint32_t mChannelMaskCurrent; @@ -109,8 +104,6 @@ private: Ip6::NetifCallback mNetifCallback; Coap::Resource mEnergyScan; - - ThreadNetif &mNetif; }; /** diff --git a/src/core/thread/key_manager.cpp b/src/core/thread/key_manager.cpp index 4d2df0afc..19ce0075e 100644 --- a/src/core/thread/key_manager.cpp +++ b/src/core/thread/key_manager.cpp @@ -36,6 +36,7 @@ #include "key_manager.hpp" +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/timer.hpp" #include "crypto/hmac_sha256.hpp" @@ -50,7 +51,7 @@ static const uint8_t kThreadString[] = }; KeyManager::KeyManager(ThreadNetif &aThreadNetif): - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mKeySequence(0), mMacFrameCounter(0), mMleFrameCounter(0), @@ -108,13 +109,13 @@ otError KeyManager::SetMasterKey(const otMasterKey &aKey) ComputeKey(mKeySequence, mKey); // reset parent frame counters - routers = mNetif.GetMle().GetParent(); + routers = GetNetif().GetMle().GetParent(); routers->SetKeySequence(0); routers->SetLinkFrameCounter(0); routers->SetMleFrameCounter(0); // reset router frame counters - routers = mNetif.GetMle().GetRouters(&num); + routers = GetNetif().GetMle().GetRouters(&num); for (uint8_t i = 0; i < num; i++) { @@ -124,7 +125,7 @@ otError KeyManager::SetMasterKey(const otMasterKey &aKey) } // reset child frame counters - children = mNetif.GetMle().GetChildren(&num); + children = GetNetif().GetMle().GetChildren(&num); for (uint8_t i = 0; i < num; i++) { @@ -133,7 +134,7 @@ otError KeyManager::SetMasterKey(const otMasterKey &aKey) children[i].SetMleFrameCounter(0); } - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); exit: return error; @@ -186,7 +187,7 @@ void KeyManager::SetCurrentKeySequence(uint32_t aKeySequence) StartKeyRotationTimer(); } - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); exit: return; @@ -210,7 +211,7 @@ void KeyManager::IncrementMacFrameCounter(void) if (mMacFrameCounter >= mStoredMacFrameCounter) { - mNetif.GetMle().Store(); + GetNetif().GetMle().Store(); } } @@ -220,7 +221,7 @@ void KeyManager::IncrementMleFrameCounter(void) if (mMleFrameCounter >= mStoredMleFrameCounter) { - mNetif.GetMle().Store(); + GetNetif().GetMle().Store(); } } @@ -248,9 +249,9 @@ void KeyManager::StartKeyRotationTimer(void) mKeyRotationTimer.Start(kOneHourIntervalInMsec); } -void KeyManager::HandleKeyRotationTimer(void *aContext) +void KeyManager::HandleKeyRotationTimer(Timer &aTimer) { - static_cast(aContext)->HandleKeyRotationTimer(); + GetOwner(aTimer).HandleKeyRotationTimer(); } void KeyManager::HandleKeyRotationTimer(void) @@ -272,4 +273,15 @@ void KeyManager::HandleKeyRotationTimer(void) } } +KeyManager &KeyManager::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + KeyManager &keyManager = *static_cast(aContext.GetContext()); +#else + KeyManager &keyManager = otGetThreadNetif().GetKeyManager(); + OT_UNUSED_VARIABLE(aContext); +#endif + return keyManager; +} + } // namespace ot diff --git a/src/core/thread/key_manager.hpp b/src/core/thread/key_manager.hpp index 3cec3c210..b403fea2a 100644 --- a/src/core/thread/key_manager.hpp +++ b/src/core/thread/key_manager.hpp @@ -38,13 +38,12 @@ #include +#include "common/locator.hpp" #include "common/timer.hpp" #include "crypto/hmac_sha256.hpp" namespace ot { -class ThreadNetif; - /** * @addtogroup core-security * @@ -54,7 +53,7 @@ class ThreadNetif; * @{ */ -class KeyManager +class KeyManager: public ThreadNetifLocator { public: enum @@ -337,10 +336,10 @@ private: otError ComputeKey(uint32_t aKeySequence, uint8_t *aKey); void StartKeyRotationTimer(void); - static void HandleKeyRotationTimer(void *aContext); + static void HandleKeyRotationTimer(Timer &aTimer); void HandleKeyRotationTimer(void); - ThreadNetif &mNetif; + static KeyManager &GetOwner(const Context &aContext); otMasterKey mMasterKey; diff --git a/src/core/thread/lowpan.cpp b/src/core/thread/lowpan.cpp index 6407d1ce2..f3bc718b6 100644 --- a/src/core/thread/lowpan.cpp +++ b/src/core/thread/lowpan.cpp @@ -49,7 +49,7 @@ namespace ot { namespace Lowpan { Lowpan::Lowpan(ThreadNetif &aThreadNetif): - mNetworkData(aThreadNetif.GetNetworkDataLeader()) + ThreadNetifLocator(aThreadNetif) { } @@ -176,6 +176,7 @@ int Lowpan::CompressDestinationIid(const Mac::Address &aMacAddr, const Ip6::Addr int Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uint8_t *aBuf) { + NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); uint8_t *cur = aBuf; Context multicastContext; @@ -211,7 +212,7 @@ int Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uin else { // Check if multicast address can be compressed using Context ID 0. - if (mNetworkData.GetContext(0, multicastContext) == OT_ERROR_NONE && + if (networkData.GetContext(0, multicastContext) == OT_ERROR_NONE && multicastContext.mPrefixLength == aIpAddr.mFields.m8[3] && memcmp(multicastContext.mPrefix, aIpAddr.mFields.m8 + 4, 8) == 0) { @@ -236,6 +237,7 @@ int Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, uin int Lowpan::Compress(Message &aMessage, const Mac::Address &aMacSource, const Mac::Address &aMacDest, uint8_t *aBuf) { + NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); uint8_t *cur = aBuf; uint16_t hcCtl = 0; Ip6::Header ip6Header; @@ -248,17 +250,17 @@ int Lowpan::Compress(Message &aMessage, const Mac::Address &aMacSource, const Ma aMessage.Read(aMessage.GetOffset(), sizeof(ip6Header), &ip6Header); - if (mNetworkData.GetContext(ip6Header.GetSource(), srcContext) != OT_ERROR_NONE || + if (networkData.GetContext(ip6Header.GetSource(), srcContext) != OT_ERROR_NONE || srcContext.mCompressFlag == false) { - mNetworkData.GetContext(0, srcContext); + networkData.GetContext(0, srcContext); srcContextValid = false; } - if (mNetworkData.GetContext(ip6Header.GetDestination(), dstContext) != OT_ERROR_NONE || + if (networkData.GetContext(ip6Header.GetDestination(), dstContext) != OT_ERROR_NONE || dstContext.mCompressFlag == false) { - mNetworkData.GetContext(0, dstContext); + networkData.GetContext(0, dstContext); dstContextValid = false; } @@ -595,6 +597,7 @@ exit: int Lowpan::DecompressBaseHeader(Ip6::Header &ip6Header, const Mac::Address &aMacSource, const Mac::Address &aMacDest, const uint8_t *aBuf, uint16_t aBufLength) { + NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); otError error = OT_ERROR_PARSE; const uint8_t *cur = aBuf; uint16_t remaining = aBufLength; @@ -620,12 +623,12 @@ int Lowpan::DecompressBaseHeader(Ip6::Header &ip6Header, const Mac::Address &aMa { VerifyOrExit(remaining >= 1); - if (mNetworkData.GetContext(cur[0] >> 4, srcContext) != OT_ERROR_NONE) + if (networkData.GetContext(cur[0] >> 4, srcContext) != OT_ERROR_NONE) { srcContextValid = false; } - if (mNetworkData.GetContext(cur[0] & 0xf, dstContext) != OT_ERROR_NONE) + if (networkData.GetContext(cur[0] & 0xf, dstContext) != OT_ERROR_NONE) { dstContextValid = false; } @@ -635,8 +638,8 @@ int Lowpan::DecompressBaseHeader(Ip6::Header &ip6Header, const Mac::Address &aMa } else { - mNetworkData.GetContext(0, srcContext); - mNetworkData.GetContext(0, dstContext); + networkData.GetContext(0, srcContext); + networkData.GetContext(0, dstContext); } memset(&ip6Header, 0, sizeof(ip6Header)); diff --git a/src/core/thread/lowpan.hpp b/src/core/thread/lowpan.hpp index d5e5330f9..197dc2f40 100644 --- a/src/core/thread/lowpan.hpp +++ b/src/core/thread/lowpan.hpp @@ -34,6 +34,7 @@ #ifndef LOWPAN_HPP_ #define LOWPAN_HPP_ +#include "common/locator.hpp" #include "common/message.hpp" #include "mac/mac_frame.hpp" #include "net/ip6.hpp" @@ -41,10 +42,6 @@ namespace ot { -class ThreadNetif; - -namespace NetworkData { class Leader; } - /** * @addtogroup core-6lowpan * @@ -79,7 +76,7 @@ struct Context * This class implements LOWPAN_IPHC header compression. * */ -class Lowpan +class Lowpan: public ThreadNetifLocator { public: /** @@ -209,8 +206,6 @@ private: static otError CopyContext(const Context &aContext, Ip6::Address &aAddress); static otError ComputeIid(const Mac::Address &aMacAddr, const Context &aContext, Ip6::Address &aIpAddress); - - NetworkData::Leader &mNetworkData; }; /** diff --git a/src/core/thread/mesh_forwarder.cpp b/src/core/thread/mesh_forwarder.cpp index be8a9b2e1..551d2f447 100644 --- a/src/core/thread/mesh_forwarder.cpp +++ b/src/core/thread/mesh_forwarder.cpp @@ -39,6 +39,7 @@ #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -58,7 +59,7 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { MeshForwarder::MeshForwarder(ThreadNetif &aThreadNetif): - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mMacReceiver(&MeshForwarder::HandleReceivedFrame, &MeshForwarder::HandleDataPollTimeout, this), mMacSender(&MeshForwarder::HandleFrameRequest, &MeshForwarder::HandleSentFrame, this), mDiscoverTimer(aThreadNetif.GetIp6().mTimerScheduler, &MeshForwarder::HandleDiscoverTimer, this), @@ -86,7 +87,7 @@ MeshForwarder::MeshForwarder(ThreadNetif &aThreadNetif): mSourceMatchController(*this) { mFragTag = static_cast(otPlatRandomGet()); - mNetif.GetMac().RegisterReceiver(mMacReceiver); + aThreadNetif.GetMac().RegisterReceiver(mMacReceiver); mMacSource.mLength = 0; mMacDest.mLength = 0; @@ -96,18 +97,13 @@ MeshForwarder::MeshForwarder(ThreadNetif &aThreadNetif): mIpCounters.mRxFailure = 0; } -otInstance *MeshForwarder::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError MeshForwarder::Start(void) { otError error = OT_ERROR_NONE; if (mEnabled == false) { - mNetif.GetMac().SetRxOnWhenIdle(true); + GetNetif().GetMac().SetRxOnWhenIdle(true); mEnabled = true; } @@ -116,6 +112,7 @@ otError MeshForwarder::Start(void) otError MeshForwarder::Stop(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message; @@ -126,9 +123,9 @@ otError MeshForwarder::Stop(void) if (mScanning) { - mNetif.GetMac().SetChannel(mRestoreChannel); + netif.GetMac().SetChannel(mRestoreChannel); mScanning = false; - mNetif.GetMle().HandleDiscoverComplete(); + netif.GetMle().HandleDiscoverComplete(); } while ((message = mSendQueue.GetHead()) != NULL) @@ -145,7 +142,7 @@ otError MeshForwarder::Stop(void) mEnabled = false; mSendMessage = NULL; - mNetif.GetMac().SetRxOnWhenIdle(false); + netif.GetMac().SetRxOnWhenIdle(false); exit: return error; @@ -200,7 +197,7 @@ void MeshForwarder::ClearChildIndirectMessages(Child &aChild) { nextMessage = message->GetNext(); - message->ClearChildMask(mNetif.GetMle().GetChildIndex(aChild)); + message->ClearChildMask(GetNetif().GetMle().GetChildIndex(aChild)); if (!message->IsChildPending() && !message->GetDirectTransmission()) { @@ -225,7 +222,7 @@ void MeshForwarder::UpdateIndirectMessages(void) Child *children; uint8_t numChildren; - children = mNetif.GetMle().GetChildren(&numChildren); + children = GetNetif().GetMle().GetChildren(&numChildren); for (uint8_t i = 0; i < numChildren; i++) { @@ -240,13 +237,14 @@ void MeshForwarder::UpdateIndirectMessages(void) } } -void MeshForwarder::ScheduleTransmissionTask(void *aContext) +void MeshForwarder::ScheduleTransmissionTask(Tasklet &aTasklet) { - static_cast(aContext)->ScheduleTransmissionTask(); + GetOwner(aTasklet).ScheduleTransmissionTask(); } void MeshForwarder::ScheduleTransmissionTask(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; uint8_t numChildren; uint8_t childIndex; @@ -259,7 +257,7 @@ void MeshForwarder::ScheduleTransmissionTask(void) mSendMessageIsARetransmission = false; - children = mNetif.GetMle().GetChildren(&numChildren); + children = netif.GetMle().GetChildren(&numChildren); if (mStartChildIndex >= numChildren) { @@ -301,12 +299,12 @@ void MeshForwarder::ScheduleTransmissionTask(void) if (child.IsIndirectSourceMatchShort()) { mMacSource.mLength = sizeof(mMacSource.mShortAddress); - mMacSource.mShortAddress = mNetif.GetMac().GetShortAddress(); + mMacSource.mShortAddress = netif.GetMac().GetShortAddress(); } else { mMacSource.mLength = sizeof(mMacSource.mExtAddress); - memcpy(mMacSource.mExtAddress.m8, mNetif.GetMac().GetExtAddress(), sizeof(mMacDest.mExtAddress)); + memcpy(mMacSource.mExtAddress.m8, netif.GetMac().GetExtAddress(), sizeof(mMacDest.mExtAddress)); } child.GetMacAddress(mMacDest); @@ -321,13 +319,13 @@ void MeshForwarder::ScheduleTransmissionTask(void) mStartChildIndex = nextIndex; - mNetif.GetMac().SendFrameRequest(mMacSender); + netif.GetMac().SendFrameRequest(mMacSender); ExitNow(); } if ((mSendMessage = GetDirectTransmission()) != NULL) { - mNetif.GetMac().SendFrameRequest(mMacSender); + netif.GetMac().SendFrameRequest(mMacSender); mSendMessageMaxMacTxAttempts = Mac::kDirectFrameMacTxAttempts; ExitNow(); } @@ -343,6 +341,7 @@ exit: otError MeshForwarder::SendMessage(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Neighbor *neighbor; @@ -357,9 +356,9 @@ otError MeshForwarder::SendMessage(Message &aMessage) aMessage.Read(0, sizeof(ip6Header), &ip6Header); - if (!memcmp(&ip6Header.GetDestination(), mNetif.GetMle().GetLinkLocalAllThreadNodesAddress(), + if (!memcmp(&ip6Header.GetDestination(), netif.GetMle().GetLinkLocalAllThreadNodesAddress(), sizeof(ip6Header.GetDestination())) || - !memcmp(&ip6Header.GetDestination(), mNetif.GetMle().GetRealmLocalAllThreadNodesAddress(), + !memcmp(&ip6Header.GetDestination(), netif.GetMle().GetRealmLocalAllThreadNodesAddress(), sizeof(ip6Header.GetDestination()))) { // schedule direct transmission @@ -368,7 +367,7 @@ otError MeshForwarder::SendMessage(Message &aMessage) if (aMessage.GetSubType() != Message::kSubTypeMplRetransmission) { // destined for all sleepy children - child = mNetif.GetMle().GetChildren(&numChildren); + child = netif.GetMle().GetChildren(&numChildren); for (uint8_t i = 0; i < numChildren; i++, child++) { @@ -380,13 +379,13 @@ otError MeshForwarder::SendMessage(Message &aMessage) } } } - else if ((neighbor = mNetif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL && + else if ((neighbor = netif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL && !neighbor->IsRxOnWhenIdle() && !aMessage.GetDirectTransmission()) { // destined for a sleepy child child = static_cast(neighbor); - aMessage.SetChildMask(mNetif.GetMle().GetChildIndex(*child)); + aMessage.SetChildMask(netif.GetMle().GetChildIndex(*child)); mSourceMatchController.IncrementMessageCount(*child); } else @@ -404,12 +403,12 @@ otError MeshForwarder::SendMessage(Message &aMessage) IgnoreReturnValue(meshHeader.Init(aMessage)); - if ((neighbor = mNetif.GetMle().GetNeighbor(meshHeader.GetDestination())) != NULL && + if ((neighbor = netif.GetMle().GetNeighbor(meshHeader.GetDestination())) != NULL && !neighbor->IsRxOnWhenIdle()) { // destined for a sleepy child child = static_cast(neighbor); - aMessage.SetChildMask(mNetif.GetMle().GetChildIndex(*child)); + aMessage.SetChildMask(netif.GetMle().GetChildIndex(*child)); mSourceMatchController.IncrementMessageCount(*child); } else @@ -426,11 +425,11 @@ otError MeshForwarder::SendMessage(Message &aMessage) break; case Message::kTypeSupervision: - child = mNetif.GetChildSupervisor().GetDestination(aMessage); + child = netif.GetChildSupervisor().GetDestination(aMessage); VerifyOrExit(child != NULL, error = OT_ERROR_DROP); VerifyOrExit(!child->IsRxOnWhenIdle(), error = OT_ERROR_DROP); - aMessage.SetChildMask(mNetif.GetMle().GetChildIndex(*child)); + aMessage.SetChildMask(netif.GetMle().GetChildIndex(*child)); mSourceMatchController.IncrementMessageCount(*child); break; } @@ -446,14 +445,15 @@ exit: otError MeshForwarder::PrepareDiscoverRequest(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; VerifyOrExit(!mScanning); mScanChannel = OT_RADIO_CHANNEL_MIN; mScanChannels >>= OT_RADIO_CHANNEL_MIN; - mRestoreChannel = mNetif.GetMac().GetChannel(); - mRestorePanId = mNetif.GetMac().GetPanId(); + mRestoreChannel = netif.GetMac().GetChannel(); + mRestorePanId = netif.GetMac().GetPanId(); while ((mScanChannels & 1) == 0) { @@ -462,7 +462,7 @@ otError MeshForwarder::PrepareDiscoverRequest(void) if (mScanChannel > OT_RADIO_CHANNEL_MAX) { - mNetif.GetMle().HandleDiscoverComplete(); + netif.GetMle().HandleDiscoverComplete(); ExitNow(error = OT_ERROR_DROP); } } @@ -541,7 +541,7 @@ Message *MeshForwarder::GetIndirectTransmission(Child &aChild) { Message *message = NULL; Message *next; - uint8_t childIndex = mNetif.GetMle().GetChildIndex(aChild); + uint8_t childIndex = GetNetif().GetMle().GetChildIndex(aChild); for (message = mSendQueue.GetHead(); message; message = next) { @@ -622,7 +622,7 @@ void MeshForwarder::PrepareIndirectTransmission(Message &aMessage, const Child & mMeshDest = meshHeader.GetDestination(); mMeshSource = meshHeader.GetSource(); mMacSource.mLength = sizeof(mMacSource.mShortAddress); - mMacSource.mShortAddress = mNetif.GetMac().GetShortAddress(); + mMacSource.mShortAddress = GetNetif().GetMac().GetShortAddress(); mMacDest.mLength = sizeof(mMacDest.mShortAddress); mMacDest.mShortAddress = meshHeader.GetDestination(); break; @@ -640,6 +640,7 @@ void MeshForwarder::PrepareIndirectTransmission(Message &aMessage, const Child & otError MeshForwarder::UpdateMeshRoute(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Lowpan::MeshHeader meshHeader; Neighbor *neighbor; @@ -647,15 +648,15 @@ otError MeshForwarder::UpdateMeshRoute(Message &aMessage) IgnoreReturnValue(meshHeader.Init(aMessage)); - nextHop = mNetif.GetMle().GetNextHop(meshHeader.GetDestination()); + nextHop = netif.GetMle().GetNextHop(meshHeader.GetDestination()); if (nextHop != Mac::kShortAddrInvalid) { - neighbor = mNetif.GetMle().GetNeighbor(nextHop); + neighbor = netif.GetMle().GetNeighbor(nextHop); } else { - neighbor = mNetif.GetMle().GetNeighbor(meshHeader.GetDestination()); + neighbor = netif.GetMle().GetNeighbor(meshHeader.GetDestination()); } if (neighbor == NULL) @@ -666,7 +667,7 @@ otError MeshForwarder::UpdateMeshRoute(Message &aMessage) mMacDest.mLength = sizeof(mMacDest.mShortAddress); mMacDest.mShortAddress = neighbor->GetRloc16(); mMacSource.mLength = sizeof(mMacSource.mShortAddress); - mMacSource.mShortAddress = mNetif.GetMac().GetShortAddress(); + mMacSource.mShortAddress = netif.GetMac().GetShortAddress(); mAddMeshHeader = true; mMeshDest = meshHeader.GetDestination(); @@ -678,6 +679,7 @@ exit: otError MeshForwarder::UpdateIp6Route(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Header ip6Header; @@ -685,7 +687,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) aMessage.Read(0, sizeof(ip6Header), &ip6Header); - switch (mNetif.GetMle().GetRole()) + switch (netif.GetMle().GetRole()) { case OT_DEVICE_ROLE_DISABLED: case OT_DEVICE_ROLE_DETACHED: @@ -704,7 +706,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) case OT_DEVICE_ROLE_CHILD: case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - if (mNetif.GetMle().IsMinimalEndDevice()) + if (netif.GetMle().IsMinimalEndDevice()) { if (aMessage.IsLinkSecurityEnabled()) { @@ -716,7 +718,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) } else { - mMacDest.mShortAddress = mNetif.GetMle().GetNextHop(Mac::kShortAddrBroadcast); + mMacDest.mShortAddress = netif.GetMle().GetNextHop(Mac::kShortAddrBroadcast); } GetMacSourceAddress(ip6Header.GetSource(), mMacSource); @@ -746,20 +748,20 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) } else { - if (mNetif.GetMle().IsRoutingLocator(ip6Header.GetDestination())) + if (netif.GetMle().IsRoutingLocator(ip6Header.GetDestination())) { rloc16 = HostSwap16(ip6Header.GetDestination().mFields.m16[7]); - VerifyOrExit(mNetif.GetMle().IsRouterIdValid(mNetif.GetMle().GetRouterId(rloc16)), + VerifyOrExit(netif.GetMle().IsRouterIdValid(netif.GetMle().GetRouterId(rloc16)), error = OT_ERROR_DROP); mMeshDest = rloc16; } - else if (mNetif.GetMle().IsAnycastLocator(ip6Header.GetDestination())) + else if (netif.GetMle().IsAnycastLocator(ip6Header.GetDestination())) { aloc16 = HostSwap16(ip6Header.GetDestination().mFields.m16[7]); if (aloc16 == Mle::kAloc16Leader) { - mMeshDest = mNetif.GetMle().GetRloc16(mNetif.GetMle().GetLeaderId()); + mMeshDest = netif.GetMle().GetRloc16(netif.GetMle().GetLeaderId()); } #if OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT @@ -767,23 +769,23 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) { uint16_t agentRloc16; uint8_t routerId; - VerifyOrExit((mNetif.GetNetworkDataLeader().GetRlocByContextId( + VerifyOrExit((netif.GetNetworkDataLeader().GetRlocByContextId( static_cast(aloc16 & Mle::kAloc16DhcpAgentMask), agentRloc16) == OT_ERROR_NONE), error = OT_ERROR_DROP); - routerId = mNetif.GetMle().GetRouterId(agentRloc16); + routerId = netif.GetMle().GetRouterId(agentRloc16); // if agent is active router or the child of the device - if ((mNetif.GetMle().IsActiveRouter(agentRloc16)) || - (mNetif.GetMle().GetRloc16(routerId) == mNetif.GetMle().GetRloc16())) + if ((netif.GetMle().IsActiveRouter(agentRloc16)) || + (netif.GetMle().GetRloc16(routerId) == netif.GetMle().GetRloc16())) { mMeshDest = agentRloc16; } else { // use the parent of the ED Agent as Dest - mMeshDest = mNetif.GetMle().GetRloc16(routerId); + mMeshDest = netif.GetMle().GetRloc16(routerId); } } @@ -794,17 +796,17 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) ExitNow(error = OT_ERROR_DROP); } } - else if ((neighbor = mNetif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL) + else if ((neighbor = netif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL) { mMeshDest = neighbor->GetRloc16(); } - else if (mNetif.GetNetworkDataLeader().IsOnMesh(ip6Header.GetDestination())) + else if (netif.GetNetworkDataLeader().IsOnMesh(ip6Header.GetDestination())) { - SuccessOrExit(error = mNetif.GetAddressResolver().Resolve(ip6Header.GetDestination(), mMeshDest)); + SuccessOrExit(error = netif.GetAddressResolver().Resolve(ip6Header.GetDestination(), mMeshDest)); } else { - mNetif.GetNetworkDataLeader().RouteLookup( + netif.GetNetworkDataLeader().RouteLookup( ip6Header.GetSource(), ip6Header.GetDestination(), NULL, @@ -814,7 +816,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) VerifyOrExit(mMeshDest != Mac::kShortAddrInvalid, error = OT_ERROR_DROP); - if (mNetif.GetMle().GetNeighbor(mMeshDest) != NULL) + if (netif.GetMle().GetNeighbor(mMeshDest) != NULL) { // destination is neighbor mMacDest.mLength = sizeof(mMacDest.mShortAddress); @@ -824,12 +826,12 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) else { // destination is not neighbor - mMeshSource = mNetif.GetMac().GetShortAddress(); + mMeshSource = netif.GetMac().GetShortAddress(); - SuccessOrExit(error = mNetif.GetMle().CheckReachability(mMeshSource, mMeshDest, ip6Header)); + SuccessOrExit(error = netif.GetMle().CheckReachability(mMeshSource, mMeshDest, ip6Header)); mMacDest.mLength = sizeof(mMacDest.mShortAddress); - mMacDest.mShortAddress = mNetif.GetMle().GetNextHop(mMeshDest); + mMacDest.mShortAddress = netif.GetMle().GetNextHop(mMeshDest); mMacSource.mLength = sizeof(mMacSource.mShortAddress); mMacSource.mShortAddress = mMeshSource; mAddMeshHeader = true; @@ -850,41 +852,47 @@ exit: void MeshForwarder::SetRxOff(void) { - mNetif.GetMac().SetRxOnWhenIdle(false); + ThreadNetif &netif = GetNetif(); + + netif.GetMac().SetRxOnWhenIdle(false); mDataPollManager.StopPolling(); - mNetif.GetSupervisionListener().Stop(); + netif.GetSupervisionListener().Stop(); } bool MeshForwarder::GetRxOnWhenIdle(void) { - return mNetif.GetMac().GetRxOnWhenIdle(); + return GetNetif().GetMac().GetRxOnWhenIdle(); } void MeshForwarder::SetRxOnWhenIdle(bool aRxOnWhenIdle) { - mNetif.GetMac().SetRxOnWhenIdle(aRxOnWhenIdle); + ThreadNetif &netif = GetNetif(); + + netif.GetMac().SetRxOnWhenIdle(aRxOnWhenIdle); if (aRxOnWhenIdle) { mDataPollManager.StopPolling(); - mNetif.GetSupervisionListener().Stop(); + netif.GetSupervisionListener().Stop(); } else { mDataPollManager.StartPolling(); - mNetif.GetSupervisionListener().Start(); + netif.GetSupervisionListener().Start(); } } otError MeshForwarder::GetMacSourceAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr) { + ThreadNetif &netif = GetNetif(); + aMacAddr.mLength = sizeof(aMacAddr.mExtAddress); aMacAddr.mExtAddress.Set(aIp6Addr); - if (memcmp(&aMacAddr.mExtAddress, mNetif.GetMac().GetExtAddress(), sizeof(aMacAddr.mExtAddress)) != 0) + if (memcmp(&aMacAddr.mExtAddress, netif.GetMac().GetExtAddress(), sizeof(aMacAddr.mExtAddress)) != 0) { aMacAddr.mLength = sizeof(aMacAddr.mShortAddress); - aMacAddr.mShortAddress = mNetif.GetMac().GetShortAddress(); + aMacAddr.mShortAddress = netif.GetMac().GetShortAddress(); } return OT_ERROR_NONE; @@ -908,7 +916,7 @@ otError MeshForwarder::GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Ma aMacAddr.mLength = sizeof(aMacAddr.mShortAddress); aMacAddr.mShortAddress = HostSwap16(aIp6Addr.mFields.m16[7]); } - else if (mNetif.GetMle().IsRoutingLocator(aIp6Addr)) + else if (GetNetif().GetMle().IsRoutingLocator(aIp6Addr)) { aMacAddr.mLength = sizeof(aMacAddr.mShortAddress); aMacAddr.mShortAddress = HostSwap16(aIp6Addr.mFields.m16[7]); @@ -922,13 +930,14 @@ otError MeshForwarder::GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Ma return OT_ERROR_NONE; } -otError MeshForwarder::HandleFrameRequest(void *aContext, Mac::Frame &aFrame) +otError MeshForwarder::HandleFrameRequest(Mac::Sender &aSender, Mac::Frame &aFrame) { - return static_cast(aContext)->HandleFrameRequest(aFrame); + return GetOwner(aSender).HandleFrameRequest(aFrame); } otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Mac::Address macDest; Child *child = NULL; @@ -950,7 +959,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) case Message::kTypeIp6: if (mSendMessage->GetSubType() == Message::kSubTypeMleDiscoverRequest) { - mNetif.GetMac().SetChannel(mScanChannel); + netif.GetMac().SetChannel(mScanChannel); aFrame.SetChannel(mScanChannel); // In case a specific PAN ID of a Thread Network to be discovered is not known, Discovery @@ -958,7 +967,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // to be the Broadcast PAN ID (0xFFFF) and the Source PAN ID set to a randomly generated // value. if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && - mNetif.GetMac().GetPanId() == Mac::kPanIdBroadcast) + netif.GetMac().GetPanId() == Mac::kPanIdBroadcast) { uint16_t panid; @@ -968,7 +977,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) } while (panid == Mac::kPanIdBroadcast); - mNetif.GetMac().SetPanId(panid); + netif.GetMac().SetPanId(panid); } } @@ -1009,7 +1018,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // The case where the current message requires fragmentation is // already checked and handled in `SendFragment()` method. - if (((child = mNetif.GetMle().GetChild(macDest)) != NULL) + if (((child = netif.GetMle().GetChild(macDest)) != NULL) && !child->IsRxOnWhenIdle() && (child->GetIndirectMessageCount() > 1)) { @@ -1040,11 +1049,12 @@ exit: otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) { + ThreadNetif &netif = GetNetif(); Mac::Address macSource; uint16_t fcf; Neighbor *neighbor; - macSource.mShortAddress = mNetif.GetMac().GetShortAddress(); + macSource.mShortAddress = netif.GetMac().GetShortAddress(); if (macSource.mShortAddress != Mac::kShortAddrInvalid) { @@ -1053,7 +1063,7 @@ otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) else { macSource.mLength = sizeof(macSource.mExtAddress); - memcpy(&macSource.mExtAddress, mNetif.GetMac().GetExtAddress(), sizeof(macSource.mExtAddress)); + memcpy(&macSource.mExtAddress, netif.GetMac().GetExtAddress(), sizeof(macSource.mExtAddress)); } // initialize MAC header @@ -1071,9 +1081,9 @@ otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) fcf |= Mac::Frame::kFcfAckRequest | Mac::Frame::kFcfSecurityEnabled; aFrame.InitMacHeader(fcf, Mac::Frame::kKeyIdMode1 | Mac::Frame::kSecEncMic32); - aFrame.SetDstPanId(mNetif.GetMac().GetPanId()); + aFrame.SetDstPanId(netif.GetMac().GetPanId()); - neighbor = mNetif.GetMle().GetParent(); + neighbor = netif.GetMle().GetParent(); assert(neighbor != NULL); if (macSource.mLength == 2) @@ -1096,6 +1106,7 @@ otError MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) otError MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) { + ThreadNetif &netif = GetNetif(); uint16_t fcf; // initialize MAC header @@ -1104,7 +1115,7 @@ otError MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) Mac::Frame::kFcfAckRequest | Mac::Frame::kFcfSecurityEnabled; aFrame.InitMacHeader(fcf, Mac::Frame::kKeyIdMode1 | Mac::Frame::kSecEncMic32); - aFrame.SetDstPanId(mNetif.GetMac().GetPanId()); + aFrame.SetDstPanId(netif.GetMac().GetPanId()); aFrame.SetDstAddr(mMacDest.mShortAddress); aFrame.SetSrcAddr(mMacSource.mShortAddress); @@ -1120,6 +1131,7 @@ otError MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) { + ThreadNetif &netif = GetNetif(); Mac::Address meshDest, meshSource; uint16_t fcf; Lowpan::FragmentHeader *fragmentHeader; @@ -1180,7 +1192,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) secCtl |= Mac::Frame::kSecEncMic32; } - dstpan = mNetif.GetMac().GetPanId(); + dstpan = netif.GetMac().GetPanId(); switch (aMessage.GetSubType()) { @@ -1198,14 +1210,14 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) break; } - if (dstpan == mNetif.GetMac().GetPanId()) + if (dstpan == netif.GetMac().GetPanId()) { fcf |= Mac::Frame::kFcfPanidCompression; } aFrame.InitMacHeader(fcf, secCtl); aFrame.SetDstPanId(dstpan); - aFrame.SetSrcPanId(mNetif.GetMac().GetPanId()); + aFrame.SetSrcPanId(netif.GetMac().GetPanId()); if (mMacDest.mLength == 2) { @@ -1232,7 +1244,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) // initialize Mesh header if (mAddMeshHeader) { - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) + if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) { // REED sets hopsLeft to max (16) + 1. It does not know the route cost. hopsLeft = Mle::kMaxRouteCost + 1; @@ -1240,24 +1252,24 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) else { // Calculate the number of predicted hops. - hopsLeft = mNetif.GetMle().GetRouteCost(mMeshDest); + hopsLeft = netif.GetMle().GetRouteCost(mMeshDest); if (hopsLeft != Mle::kMaxRouteCost) { - hopsLeft += mNetif.GetMle().GetLinkCost( - mNetif.GetMle().GetRouterId(mNetif.GetMle().GetNextHop(mMeshDest))); + hopsLeft += netif.GetMle().GetLinkCost( + netif.GetMle().GetRouterId(netif.GetMle().GetNextHop(mMeshDest))); } else { // In case there is no route to the destination router (only link). - hopsLeft = mNetif.GetMle().GetLinkCost(mNetif.GetMle().GetRouterId(mMeshDest)); + hopsLeft = netif.GetMle().GetLinkCost(netif.GetMle().GetRouterId(mMeshDest)); } } // The hopsLft field MUST be incremented by one if the destination RLOC16 // is not that of an active Router. - if (!mNetif.GetMle().IsActiveRouter(mMeshDest)) + if (!netif.GetMle().IsActiveRouter(mMeshDest)) { hopsLeft += 1; } @@ -1274,7 +1286,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) // copy IPv6 Header if (aMessage.GetOffset() == 0) { - hcLength = mNetif.GetLowpan().Compress(aMessage, meshSource, meshDest, payload); + hcLength = netif.GetLowpan().Compress(aMessage, meshSource, meshDest, payload); assert(hcLength > 0); headerLength += static_cast(hcLength); @@ -1365,11 +1377,12 @@ exit: otError MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) { + ThreadNetif &netif = GetNetif(); uint16_t fcf; uint8_t secCtl; Mac::Address macSource; - macSource.mShortAddress = mNetif.GetMac().GetShortAddress(); + macSource.mShortAddress = netif.GetMac().GetShortAddress(); if (macSource.mShortAddress != Mac::kShortAddrInvalid) { @@ -1378,7 +1391,7 @@ otError MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) else { macSource.mLength = sizeof(macSource.mExtAddress); - memcpy(&macSource.mExtAddress, mNetif.GetMac().GetExtAddress(), sizeof(macSource.mExtAddress)); + memcpy(&macSource.mExtAddress, netif.GetMac().GetExtAddress(), sizeof(macSource.mExtAddress)); } fcf = Mac::Frame::kFcfFrameData | Mac::Frame::kFcfFrameVersion2006; @@ -1398,8 +1411,8 @@ otError MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) aFrame.InitMacHeader(fcf, secCtl); - aFrame.SetDstPanId(mNetif.GetMac().GetPanId()); - aFrame.SetSrcPanId(mNetif.GetMac().GetPanId()); + aFrame.SetDstPanId(netif.GetMac().GetPanId()); + aFrame.SetSrcPanId(netif.GetMac().GetPanId()); if (mMacDest.mLength == 2) { @@ -1425,13 +1438,14 @@ otError MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) return OT_ERROR_NONE; } -void MeshForwarder::HandleSentFrame(void *aContext, Mac::Frame &aFrame, otError aError) +void MeshForwarder::HandleSentFrame(Mac::Sender &aSender, Mac::Frame &aFrame, otError aError) { - static_cast(aContext)->HandleSentFrame(aFrame, aError); + GetOwner(aSender).HandleSentFrame(aFrame, aError); } void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) { + ThreadNetif &netif = GetNetif(); Mac::Address macDest; Child *child; Neighbor *neighbor; @@ -1448,7 +1462,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) aFrame.GetDstAddr(macDest); - if ((neighbor = mNetif.GetMle().GetNeighbor(macDest)) != NULL) + if ((neighbor = netif.GetMle().GetNeighbor(macDest)) != NULL) { switch (aError) { @@ -1467,11 +1481,11 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) case OT_ERROR_NO_ACK: neighbor->IncrementLinkFailures(); - if (mNetif.GetMle().IsActiveRouter(neighbor->GetRloc16())) + if (netif.GetMle().IsActiveRouter(neighbor->GetRloc16())) { if (neighbor->GetLinkFailures() >= Mle::kFailedRouterTransmissions) { - mNetif.GetMle().RemoveNeighbor(*neighbor); + netif.GetMle().RemoveNeighbor(*neighbor); } } @@ -1483,7 +1497,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) } } - if ((child = mNetif.GetMle().GetChild(macDest)) != NULL) + if ((child = netif.GetMle().GetChild(macDest)) != NULL) { child->SetDataRequestPending(false); @@ -1561,7 +1575,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) mSourceMatchController.SetSrcMatchAsShort(*child, true); } - childIndex = mNetif.GetMle().GetChildIndex(*child); + childIndex = netif.GetMle().GetChildIndex(*child); if (mSendMessage->GetChildMask(childIndex)) { @@ -1572,7 +1586,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) if (aError == OT_ERROR_NONE) { - mNetif.GetChildSupervisor().UpdateOnSend(*child); + netif.GetChildSupervisor().UpdateOnSend(*child); } } @@ -1613,12 +1627,12 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) if (mSendMessage->GetType() == Message::kTypeMacDataPoll) { - neighbor = mNetif.GetMle().GetParent(); + neighbor = netif.GetMle().GetParent(); if (neighbor->GetState() == Neighbor::kStateInvalid) { mDataPollManager.StopPolling(); - mNetif.GetMle().BecomeDetached(); + netif.GetMle().BecomeDetached(); } else { @@ -1661,14 +1675,15 @@ void MeshForwarder::SetDiscoverParameters(uint32_t aScanChannels) mScanChannels = (aScanChannels == 0) ? static_cast(Mac::kScanChannelsAll) : aScanChannels; } -void MeshForwarder::HandleDiscoverTimer(void *aContext) +void MeshForwarder::HandleDiscoverTimer(Timer &aTimer) { - MeshForwarder *obj = static_cast(aContext); - obj->HandleDiscoverTimer(); + GetOwner(aTimer).HandleDiscoverTimer(); } void MeshForwarder::HandleDiscoverTimer(void) { + ThreadNetif &netif = GetNetif(); + do { mScanChannels >>= 1; @@ -1679,10 +1694,10 @@ void MeshForwarder::HandleDiscoverTimer(void) mSendQueue.Dequeue(*mSendMessage); mSendMessage->Free(); mSendMessage = NULL; - mNetif.GetMac().SetChannel(mRestoreChannel); - mNetif.GetMac().SetPanId(mRestorePanId); + netif.GetMac().SetChannel(mRestoreChannel); + netif.GetMac().SetPanId(mRestorePanId); mScanning = false; - mNetif.GetMle().HandleDiscoverComplete(); + netif.GetMle().HandleDiscoverComplete(); ExitNow(); } } @@ -1695,13 +1710,14 @@ exit: mScheduleTransmissionTask.Post(); } -void MeshForwarder::HandleReceivedFrame(void *aContext, Mac::Frame &aFrame) +void MeshForwarder::HandleReceivedFrame(Mac::Receiver &aReceiver, Mac::Frame &aFrame) { - static_cast(aContext)->HandleReceivedFrame(aFrame); + GetOwner(aReceiver).HandleReceivedFrame(aFrame); } void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) { + ThreadNetif &netif = GetNetif(); ThreadMessageInfo messageInfo; Mac::Address macDest; Mac::Address macSource; @@ -1727,7 +1743,7 @@ void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) payload = aFrame.GetPayload(); payloadLength = aFrame.GetPayloadLength(); - mNetif.GetSupervisionListener().UpdateOnReceive(macSource, messageInfo.mLinkSecurity); + netif.GetSupervisionListener().UpdateOnReceive(macSource, messageInfo.mLinkSecurity); mDataPollManager.CheckFramePending(aFrame); @@ -1790,6 +1806,7 @@ exit: void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMacSource, const ThreadMessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message = NULL; Mac::Address meshDest; @@ -1807,7 +1824,7 @@ void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac: meshDest.mLength = sizeof(meshDest.mShortAddress); meshDest.mShortAddress = meshHeader.GetDestination(); - if (meshDest.mShortAddress == mNetif.GetMac().GetShortAddress()) + if (meshDest.mShortAddress == netif.GetMac().GetShortAddress()) { aFrame += meshHeader.GetHeaderLength(); aFrameLength -= meshHeader.GetHeaderLength(); @@ -1827,14 +1844,14 @@ void MeshForwarder::HandleMesh(uint8_t *aFrame, uint8_t aFrameLength, const Mac: } else if (meshHeader.GetHopsLeft() > 0) { - mNetif.GetMle().ResolveRoutingLoops(aMacSource.mShortAddress, meshDest.mShortAddress); + netif.GetMle().ResolveRoutingLoops(aMacSource.mShortAddress, meshDest.mShortAddress); SuccessOrExit(error = CheckReachability(aFrame, aFrameLength, meshSource, meshDest)); meshHeader.SetHopsLeft(meshHeader.GetHopsLeft() - 1); meshHeader.AppendTo(aFrame); - VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kType6lowpan, 0)) != NULL, + VerifyOrExit((message = netif.GetIp6().mMessagePool.New(Message::kType6lowpan, 0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(aFrameLength)); message->Write(0, aFrameLength, aFrame); @@ -1871,6 +1888,7 @@ exit: otError MeshForwarder::CheckReachability(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMeshSource, const Mac::Address &aMeshDest) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Header ip6Header; Lowpan::MeshHeader meshHeader; @@ -1895,10 +1913,10 @@ otError MeshForwarder::CheckReachability(uint8_t *aFrame, uint8_t aFrameLength, // only process IPv6 packets VerifyOrExit(aFrameLength >= 1 && Lowpan::Lowpan::IsLowpanHc(aFrame)); - VerifyOrExit(mNetif.GetLowpan().DecompressBaseHeader(ip6Header, aMeshSource, aMeshDest, aFrame, aFrameLength) > 0, + VerifyOrExit(netif.GetLowpan().DecompressBaseHeader(ip6Header, aMeshSource, aMeshDest, aFrame, aFrameLength) > 0, error = OT_ERROR_DROP); - error = mNetif.GetMle().CheckReachability(aMeshSource.mShortAddress, aMeshDest.mShortAddress, ip6Header); + error = netif.GetMle().CheckReachability(aMeshSource.mShortAddress, aMeshDest.mShortAddress, ip6Header); exit: return error; @@ -1908,6 +1926,7 @@ void MeshForwarder::HandleFragment(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMacSource, const Mac::Address &aMacDest, const ThreadMessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Lowpan::FragmentHeader *fragmentHeader = reinterpret_cast(aFrame); uint16_t datagramLength = fragmentHeader->GetDatagramSize(); @@ -1920,12 +1939,12 @@ void MeshForwarder::HandleFragment(uint8_t *aFrame, uint8_t aFrameLength, aFrame += fragmentHeader->GetHeaderLength(); aFrameLength -= fragmentHeader->GetHeaderLength(); - VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, + VerifyOrExit((message = netif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(aMessageInfo.mLinkSecurity); message->SetPanId(aMessageInfo.mPanId); - headerLength = mNetif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, - datagramLength); + headerLength = netif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, + datagramLength); VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE); aFrame += headerLength; @@ -1943,7 +1962,7 @@ void MeshForwarder::HandleFragment(uint8_t *aFrame, uint8_t aFrameLength, message->MoveOffset(aFrameLength); // Security Check - VerifyOrExit(mNetif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); + VerifyOrExit(netif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); // Allow re-assembly of only one message at a time on a SED by clearing // any remaining fragments in reassembly list upon receiving of a new @@ -2054,12 +2073,12 @@ void MeshForwarder::ClearReassemblyList(void) } } -void MeshForwarder::HandleReassemblyTimer(void *aContext) +void MeshForwarder::HandleReassemblyTimer(Timer &aTimer) { - static_cast(aContext)->HandleReassemblyTimer(); + GetOwner(aTimer).HandleReassemblyTimer(); } -void MeshForwarder::HandleReassemblyTimer() +void MeshForwarder::HandleReassemblyTimer(void) { Message *next = NULL; uint8_t timeout; @@ -2094,16 +2113,17 @@ void MeshForwarder::HandleLowpanHC(uint8_t *aFrame, uint8_t aFrameLength, const Mac::Address &aMacSource, const Mac::Address &aMacDest, const ThreadMessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message; int headerLength; - VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, + VerifyOrExit((message = netif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(aMessageInfo.mLinkSecurity); message->SetPanId(aMessageInfo.mPanId); - headerLength = mNetif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, 0); + headerLength = netif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, 0); VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE); aFrame += headerLength; @@ -2113,7 +2133,7 @@ void MeshForwarder::HandleLowpanHC(uint8_t *aFrame, uint8_t aFrameLength, message->Write(message->GetOffset(), aFrameLength, aFrame); // Security Check - VerifyOrExit(mNetif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); + VerifyOrExit(netif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); exit: @@ -2149,23 +2169,26 @@ exit: otError MeshForwarder::HandleDatagram(Message &aMessage, const ThreadMessageInfo &aMessageInfo, const Mac::Address &aMacSource) { + ThreadNetif &netif = GetNetif(); + LogIp6Message(kMessageReceive, aMessage, &aMacSource, OT_ERROR_NONE); mIpCounters.mRxSuccess++; - return mNetif.GetIp6().HandleDatagram(aMessage, &mNetif, mNetif.GetInterfaceId(), &aMessageInfo, false); + return netif.GetIp6().HandleDatagram(aMessage, &netif, netif.GetInterfaceId(), &aMessageInfo, false); } void MeshForwarder::HandleDataRequest(const Mac::Address &aMacSource, const ThreadMessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); Child *child; uint16_t indirectMsgCount; // Security Check: only process secure Data Poll frames. VerifyOrExit(aMessageInfo.mLinkSecurity); - VerifyOrExit(mNetif.GetMle().GetRole() != OT_DEVICE_ROLE_DETACHED); + VerifyOrExit(netif.GetMle().GetRole() != OT_DEVICE_ROLE_DETACHED); - VerifyOrExit((child = mNetif.GetMle().GetChild(aMacSource)) != NULL); + VerifyOrExit((child = netif.GetMle().GetChild(aMacSource)) != NULL); child->SetLastHeard(Timer::GetNow()); child->ResetLinkFailures(); indirectMsgCount = child->GetIndirectMessageCount(); @@ -2183,9 +2206,20 @@ exit: return; } -void MeshForwarder::HandleDataPollTimeout(void *aContext) +void MeshForwarder::HandleDataPollTimeout(Mac::Receiver &aReceiver) { - static_cast(aContext)->GetDataPollManager().HandlePollTimeout(); + GetOwner(aReceiver).GetDataPollManager().HandlePollTimeout(); +} + +MeshForwarder &MeshForwarder::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + MeshForwarder &meshForwader = *static_cast(aContext.GetContext()); +#else + MeshForwarder &meshForwader = otGetMeshForwarder(); + OT_UNUSED_VARIABLE(aContext); +#endif + return meshForwader; } #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_INFO) && (OPENTHREAD_CONFIG_LOG_MAC == 1) diff --git a/src/core/thread/mesh_forwarder.hpp b/src/core/thread/mesh_forwarder.hpp index c3c016d7f..b688b2c3b 100644 --- a/src/core/thread/mesh_forwarder.hpp +++ b/src/core/thread/mesh_forwarder.hpp @@ -37,6 +37,7 @@ #include #include "openthread-core-config.h" +#include "common/locator.hpp" #include "common/tasklet.hpp" #include "mac/mac.hpp" #include "net/ip6.hpp" @@ -70,7 +71,7 @@ struct ThreadMessageInfo; * This class implements mesh forwarding within Thread. * */ -class MeshForwarder +class MeshForwarder: public ThreadNetifLocator { public: /** @@ -81,14 +82,6 @@ public: */ explicit MeshForwarder(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method enables mesh forwarding and the IEEE 802.15.4 MAC layer. * @@ -171,13 +164,6 @@ public: */ void UpdateIndirectMessages(void); - /** - * This method returns a reference to the thread network interface instance. - * - * @ returns A reference to the thread network interface instance. - */ - ThreadNetif &GetNetif(void) { return mNetif; } - /** * This method returns a reference to the send queue. * @@ -285,30 +271,29 @@ private: const Mac::Address &aMacSource); void ClearReassemblyList(void); - static void HandleReceivedFrame(void *aContext, Mac::Frame &aFrame); + static void HandleReceivedFrame(Mac::Receiver &aReceiver, Mac::Frame &aFrame); void HandleReceivedFrame(Mac::Frame &aFrame); - static otError HandleFrameRequest(void *aContext, Mac::Frame &aFrame); + static otError HandleFrameRequest(Mac::Sender &aSender, Mac::Frame &aFrame); otError HandleFrameRequest(Mac::Frame &aFrame); - static void HandleSentFrame(void *aContext, Mac::Frame &aFrame, otError aError); + static void HandleSentFrame(Mac::Sender &aSender, Mac::Frame &aFrame, otError aError); void HandleSentFrame(Mac::Frame &aFrame, otError aError); - static void HandleDiscoverTimer(void *aContext); + static void HandleDiscoverTimer(Timer &aTimer); void HandleDiscoverTimer(void); - static void HandleReassemblyTimer(void *aContext); + static void HandleReassemblyTimer(Timer &aTimer); void HandleReassemblyTimer(void); - static void ScheduleTransmissionTask(void *aContext); + static void ScheduleTransmissionTask(Tasklet &aTasklet); void ScheduleTransmissionTask(void); - static void HandleDataPollTimeout(void *aContext); + static void HandleDataPollTimeout(Mac::Receiver &aReceiver); otError AddPendingSrcMatchEntries(void); otError AddSrcMatchEntry(Child &aChild); void ClearSrcMatchEntry(Child &aChild); + static MeshForwarder &GetOwner(const Context &aContext); + void LogIp6Message(MessageAction aAction, const Message &aMessage, const Mac::Address *aMacAddress, otError aError); - - ThreadNetif &mNetif; - Mac::Receiver mMacReceiver; Mac::Sender mMacSender; Timer mDiscoverTimer; diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index 4407ec2d8..edf7b5b29 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -40,6 +40,7 @@ #include #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -61,14 +62,13 @@ namespace ot { namespace Mle { Mle::Mle(ThreadNetif &aThreadNetif) : - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mRetrieveNewNetworkData(false), mRole(OT_DEVICE_ROLE_DISABLED), mDeviceMode(ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeSecureDataRequest), isAssignLinkQuality(false), mAssignLinkQuality(0), mAssignLinkMargin(0), - mParentRequestState(kParentIdle), mReattachState(kReattachStop), mParentRequestTimer(aThreadNetif.GetIp6().mTimerScheduler, &Mle::HandleParentRequestTimer, this), @@ -110,11 +110,11 @@ Mle::Mle(ThreadNetif &aThreadNetif) : // link-local 64 mLinkLocal64.GetAddress().mFields.m16[0] = HostSwap16(0xfe80); - mLinkLocal64.GetAddress().SetIid(*mNetif.GetMac().GetExtAddress()); + mLinkLocal64.GetAddress().SetIid(*aThreadNetif.GetMac().GetExtAddress()); mLinkLocal64.mPrefixLength = 64; mLinkLocal64.mPreferred = true; mLinkLocal64.mValid = true; - mNetif.AddUnicastAddress(mLinkLocal64); + aThreadNetif.AddUnicastAddress(mLinkLocal64); // Leader Aloc mLeaderAloc.mPrefixLength = 128; @@ -125,7 +125,7 @@ Mle::Mle(ThreadNetif &aThreadNetif) : // initialize Mesh Local Prefix meshLocalPrefix[0] = 0xfd; - memcpy(meshLocalPrefix + 1, mNetif.GetMac().GetExtendedPanId(), 5); + memcpy(meshLocalPrefix + 1, aThreadNetif.GetMac().GetExtendedPanId(), 5); meshLocalPrefix[6] = 0x00; meshLocalPrefix[7] = 0x00; @@ -154,31 +154,26 @@ Mle::Mle(ThreadNetif &aThreadNetif) : mMeshLocal16.mRloc = true; // Store RLOC address reference in MPL module. - mNetif.GetIp6().mMpl.SetMatchingAddress(mMeshLocal16.GetAddress()); + aThreadNetif.GetIp6().mMpl.SetMatchingAddress(mMeshLocal16.GetAddress()); // link-local all thread nodes mLinkLocalAllThreadNodes.GetAddress().mFields.m16[0] = HostSwap16(0xff32); mLinkLocalAllThreadNodes.GetAddress().mFields.m16[6] = HostSwap16(0x0000); mLinkLocalAllThreadNodes.GetAddress().mFields.m16[7] = HostSwap16(0x0001); - mNetif.SubscribeMulticast(mLinkLocalAllThreadNodes); + aThreadNetif.SubscribeMulticast(mLinkLocalAllThreadNodes); // realm-local all thread nodes mRealmLocalAllThreadNodes.GetAddress().mFields.m16[0] = HostSwap16(0xff33); mRealmLocalAllThreadNodes.GetAddress().mFields.m16[6] = HostSwap16(0x0000); mRealmLocalAllThreadNodes.GetAddress().mFields.m16[7] = HostSwap16(0x0001); - mNetif.SubscribeMulticast(mRealmLocalAllThreadNodes); + aThreadNetif.SubscribeMulticast(mRealmLocalAllThreadNodes); mNetifCallback.Set(&Mle::HandleNetifStateChanged, this); - mNetif.RegisterCallback(mNetifCallback); + aThreadNetif.RegisterCallback(mNetifCallback); memset(&mAddr64, 0, sizeof(mAddr64)); } -otInstance *Mle::GetInstance(void) -{ - return mNetif.GetInstance(); -} - otError Mle::Enable(void) { otError error = OT_ERROR_NONE; @@ -206,19 +201,20 @@ exit: otError Mle::Start(bool aEnableReattach, bool aAnnounceAttach) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; otLogFuncEntry(); // cannot bring up the interface if IEEE 802.15.4 promiscuous mode is enabled - VerifyOrExit(otPlatRadioGetPromiscuous(mNetif.GetInstance()) == false, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(mNetif.IsUp(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(otPlatRadioGetPromiscuous(netif.GetInstance()) == false, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(netif.IsUp(), error = OT_ERROR_INVALID_STATE); mRole = OT_DEVICE_ROLE_DETACHED; - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); SetStateDetached(); - mNetif.GetKeyManager().Start(); + netif.GetKeyManager().Start(); if (aEnableReattach) { @@ -231,7 +227,7 @@ otError Mle::Start(bool aEnableReattach, bool aAnnounceAttach) } else if (IsActiveRouter(GetRloc16())) { - if (mNetif.GetMle().BecomeRouter(ThreadStatusTlv::kTooFewRouters) != OT_ERROR_NONE) + if (netif.GetMle().BecomeRouter(ThreadStatusTlv::kTooFewRouters) != OT_ERROR_NONE) { BecomeChild(kAttachAny); } @@ -250,20 +246,22 @@ exit: otError Mle::Stop(bool aClearNetworkDatasets) { + ThreadNetif &netif = GetNetif(); + otLogFuncEntry(); - mNetif.GetKeyManager().Stop(); + netif.GetKeyManager().Stop(); SetStateDetached(); - mNetif.RemoveUnicastAddress(mMeshLocal16); + netif.RemoveUnicastAddress(mMeshLocal16); #if OPENTHREAD_ENABLE_BORDER_ROUTER - mNetif.GetNetworkDataLocal().Clear(); + netif.GetNetworkDataLocal().Clear(); #endif - mNetif.GetNetworkDataLeader().Clear(); + netif.GetNetworkDataLeader().Clear(); memset(&mLeaderData, 0, sizeof(mLeaderData)); if (aClearNetworkDatasets) { - mNetif.GetActiveDataset().Clear(true); - mNetif.GetPendingDataset().Clear(true); + netif.GetActiveDataset().Clear(true); + netif.GetPendingDataset().Clear(true); } mRole = OT_DEVICE_ROLE_DISABLED; @@ -273,26 +271,27 @@ otError Mle::Stop(bool aClearNetworkDatasets) otError Mle::Restore(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; Settings::ParentInfo parentInfo; uint16_t length; - mNetif.GetActiveDataset().Restore(); - mNetif.GetPendingDataset().Restore(); + netif.GetActiveDataset().Restore(); + netif.GetPendingDataset().Restore(); length = sizeof(networkInfo); - SuccessOrExit(error = otPlatSettingsGet(mNetif.GetInstance(), Settings::kKeyNetworkInfo, 0, + SuccessOrExit(error = otPlatSettingsGet(netif.GetInstance(), Settings::kKeyNetworkInfo, 0, reinterpret_cast(&networkInfo), &length)); VerifyOrExit(length == sizeof(networkInfo), error = OT_ERROR_NOT_FOUND); VerifyOrExit(networkInfo.mRole >= OT_DEVICE_ROLE_CHILD, error = OT_ERROR_NOT_FOUND); mDeviceMode = networkInfo.mDeviceMode; SetRloc16(networkInfo.mRloc16); - mNetif.GetKeyManager().SetCurrentKeySequence(networkInfo.mKeySequence); - mNetif.GetKeyManager().SetMleFrameCounter(networkInfo.mMleFrameCounter); - mNetif.GetKeyManager().SetMacFrameCounter(networkInfo.mMacFrameCounter); - mNetif.GetMac().SetExtAddress(networkInfo.mExtAddress); + netif.GetKeyManager().SetCurrentKeySequence(networkInfo.mKeySequence); + netif.GetKeyManager().SetMleFrameCounter(networkInfo.mMleFrameCounter); + netif.GetKeyManager().SetMacFrameCounter(networkInfo.mMacFrameCounter); + netif.GetMac().SetExtAddress(networkInfo.mExtAddress); UpdateLinkLocalAddress(); memcpy(&mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], @@ -307,7 +306,7 @@ otError Mle::Restore(void) if (!IsActiveRouter(networkInfo.mRloc16)) { length = sizeof(parentInfo); - SuccessOrExit(error = otPlatSettingsGet(mNetif.GetInstance(), Settings::kKeyParentInfo, 0, + SuccessOrExit(error = otPlatSettingsGet(netif.GetInstance(), Settings::kKeyParentInfo, 0, reinterpret_cast(&parentInfo), &length)); VerifyOrExit(length >= sizeof(parentInfo), error = OT_ERROR_PARSE); @@ -320,10 +319,10 @@ otError Mle::Restore(void) } else { - mNetif.GetMle().SetRouterId(GetRouterId(GetRloc16())); - mNetif.GetMle().SetPreviousPartitionId(networkInfo.mPreviousPartitionId); + netif.GetMle().SetRouterId(GetRouterId(GetRloc16())); + netif.GetMle().SetPreviousPartitionId(networkInfo.mPreviousPartitionId); - switch (mNetif.GetMle().RestoreChildren()) + switch (netif.GetMle().RestoreChildren()) { // If there are more saved children in non-volatile settings // than could be restored or the values in the settings are @@ -333,7 +332,7 @@ otError Mle::Restore(void) case OT_ERROR_FAILED: case OT_ERROR_NO_BUFS: - mNetif.GetMle().RefreshStoredChildren(); + netif.GetMle().RefreshStoredChildren(); break; default: @@ -347,16 +346,17 @@ exit: otError Mle::Store(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; Settings::ParentInfo parentInfo; VerifyOrExit(IsAttached(), error = OT_ERROR_INVALID_STATE); - if (mNetif.GetActiveDataset().GetLocal().GetTimestamp() == NULL) + if (netif.GetActiveDataset().GetLocal().GetTimestamp() == NULL) { - mNetif.GetActiveDataset().GenerateLocal(); - mNetif.GetActiveDataset().GetLocal().Store(); + netif.GetActiveDataset().GenerateLocal(); + netif.GetActiveDataset().GetLocal().Store(); } memset(&networkInfo, 0, sizeof(networkInfo)); @@ -364,13 +364,13 @@ otError Mle::Store(void) networkInfo.mDeviceMode = mDeviceMode; networkInfo.mRole = mRole; networkInfo.mRloc16 = GetRloc16(); - networkInfo.mKeySequence = mNetif.GetKeyManager().GetCurrentKeySequence(); - networkInfo.mMleFrameCounter = mNetif.GetKeyManager().GetMleFrameCounter() + + networkInfo.mKeySequence = netif.GetKeyManager().GetCurrentKeySequence(); + networkInfo.mMleFrameCounter = netif.GetKeyManager().GetMleFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; - networkInfo.mMacFrameCounter = mNetif.GetKeyManager().GetMacFrameCounter() + + networkInfo.mMacFrameCounter = netif.GetKeyManager().GetMacFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; networkInfo.mPreviousPartitionId = mLeaderData.GetPartitionId(); - memcpy(networkInfo.mExtAddress.m8, mNetif.GetMac().GetExtAddress(), sizeof(networkInfo.mExtAddress)); + memcpy(networkInfo.mExtAddress.m8, netif.GetMac().GetExtAddress(), sizeof(networkInfo.mExtAddress)); memcpy(networkInfo.mMlIid, &mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); @@ -381,15 +381,15 @@ otError Mle::Store(void) memset(&parentInfo, 0, sizeof(parentInfo)); memcpy(&parentInfo.mExtAddress, &mParent.GetExtAddress(), sizeof(parentInfo.mExtAddress)); - SuccessOrExit(error = otPlatSettingsSet(mNetif.GetInstance(), Settings::kKeyParentInfo, + SuccessOrExit(error = otPlatSettingsSet(netif.GetInstance(), Settings::kKeyParentInfo, reinterpret_cast(&parentInfo), sizeof(parentInfo))); } - SuccessOrExit(error = otPlatSettingsSet(mNetif.GetInstance(), Settings::kKeyNetworkInfo, + SuccessOrExit(error = otPlatSettingsSet(netif.GetInstance(), Settings::kKeyNetworkInfo, reinterpret_cast(&networkInfo), sizeof(networkInfo))); - mNetif.GetKeyManager().SetStoredMleFrameCounter(networkInfo.mMleFrameCounter); - mNetif.GetKeyManager().SetStoredMacFrameCounter(networkInfo.mMacFrameCounter); + netif.GetKeyManager().SetStoredMleFrameCounter(networkInfo.mMleFrameCounter); + netif.GetKeyManager().SetStoredMacFrameCounter(networkInfo.mMacFrameCounter); otLogDebgMle(GetInstance(), "Store Network Information"); @@ -413,7 +413,7 @@ otError Mle::Discover(uint32_t aScanChannels, uint16_t aPanId, bool aJoiner, boo mDiscoverHandler = aCallback; mDiscoverContext = aContext; - mNetif.GetMeshForwarder().SetDiscoverParameters(aScanChannels); + GetNetif().GetMeshForwarder().SetDiscoverParameters(aScanChannels); VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeMleDiscoverRequest); @@ -468,6 +468,7 @@ void Mle::HandleDiscoverComplete(void) otError Mle::BecomeDetached(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; otLogFuncEntry(); @@ -476,8 +477,8 @@ otError Mle::BecomeDetached(void) if (mReattachState == kReattachStop) { - mNetif.GetPendingDataset().UpdateDelayTimer(); - mNetif.GetPendingDataset().Set(mNetif.GetPendingDataset().GetLocal()); + netif.GetPendingDataset().UpdateDelayTimer(); + netif.GetPendingDataset().Set(netif.GetPendingDataset().GetLocal()); } SetStateDetached(); @@ -491,6 +492,7 @@ exit: otError Mle::BecomeChild(AttachMode aMode) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; otLogFuncEntry(); @@ -500,7 +502,7 @@ otError Mle::BecomeChild(AttachMode aMode) if (mReattachState == kReattachStart) { - if (mNetif.GetActiveDataset().Restore() == OT_ERROR_NONE) + if (netif.GetActiveDataset().Restore() == OT_ERROR_NONE) { mReattachState = kReattachActive; } @@ -520,18 +522,18 @@ otError Mle::BecomeChild(AttachMode aMode) if (mDeviceMode & ModeTlv::kModeFFD) { - mNetif.GetMle().StopAdvertiseTimer(); + netif.GetMle().StopAdvertiseTimer(); } } if (aMode == kAttachAny) { mParent.SetState(Neighbor::kStateInvalid); - mLastPartitionId = mNetif.GetMle().GetPreviousPartitionId(); - mLastPartitionRouterIdSequence = mNetif.GetMle().GetRouterIdSequence(); + mLastPartitionId = netif.GetMle().GetPreviousPartitionId(); + mLastPartitionRouterIdSequence = netif.GetMle().GetRouterIdSequence(); } - mNetif.GetMeshForwarder().SetRxOnWhenIdle(true); + netif.GetMeshForwarder().SetRxOnWhenIdle(true); mParentRequestTimer.Start((otPlatRandomGet() % kParentRequestRouterTimeout) + 1); @@ -547,24 +549,26 @@ bool Mle::IsAttached(void) const otError Mle::SetStateDetached(void) { + ThreadNetif &netif = GetNetif(); + if (mRole != OT_DEVICE_ROLE_DETACHED) { - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); } if (mRole == OT_DEVICE_ROLE_LEADER) { - mNetif.RemoveUnicastAddress(mLeaderAloc); + netif.RemoveUnicastAddress(mLeaderAloc); } mRole = OT_DEVICE_ROLE_DETACHED; mParentRequestState = kParentIdle; mParentRequestTimer.Stop(); - mNetif.GetMeshForwarder().SetRxOff(); - mNetif.GetMac().SetBeaconEnabled(false); - mNetif.GetMle().HandleDetachStart(); - mNetif.GetIp6().SetForwardingEnabled(false); - mNetif.GetIp6().mMpl.SetTimerExpirations(0); + netif.GetMeshForwarder().SetRxOff(); + netif.GetMac().SetBeaconEnabled(false); + netif.GetMle().HandleDetachStart(); + netif.GetIp6().SetForwardingEnabled(false); + netif.GetIp6().mMpl.SetTimerExpirations(0); otLogInfoMle(GetInstance(), "Mode -> Detached"); return OT_ERROR_NONE; @@ -572,21 +576,23 @@ otError Mle::SetStateDetached(void) otError Mle::SetStateChild(uint16_t aRloc16) { + ThreadNetif &netif = GetNetif(); + if (mRole != OT_DEVICE_ROLE_CHILD) { - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); } if (mRole == OT_DEVICE_ROLE_LEADER) { - mNetif.RemoveUnicastAddress(mLeaderAloc); + netif.RemoveUnicastAddress(mLeaderAloc); } SetRloc16(aRloc16); mRole = OT_DEVICE_ROLE_CHILD; mParentRequestState = kParentIdle; mChildUpdateAttempts = 0; - mNetif.GetMac().SetBeaconEnabled(false); + netif.GetMac().SetBeaconEnabled(false); if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) != 0) { @@ -596,21 +602,21 @@ otError Mle::SetStateChild(uint16_t aRloc16) if ((mDeviceMode & ModeTlv::kModeFFD) != 0) { - mNetif.GetMle().HandleChildStart(mParentRequestMode); + netif.GetMle().HandleChildStart(mParentRequestMode); } #if OPENTHREAD_ENABLE_BORDER_ROUTER - mNetif.GetNetworkDataLocal().ClearResubmitDelayTimer(); + netif.GetNetworkDataLocal().ClearResubmitDelayTimer(); #endif - mNetif.GetIp6().SetForwardingEnabled(false); - mNetif.GetIp6().mMpl.SetTimerExpirations(kMplChildDataMessageTimerExpirations); + netif.GetIp6().SetForwardingEnabled(false); + netif.GetIp6().mMpl.SetTimerExpirations(kMplChildDataMessageTimerExpirations); // Once the Thread device receives the new Active Commissioning Dataset, the device MUST // transmit its own Announce messages on the channel it was on prior to the attachment. if (mPreviousPanId != Mac::kPanIdBroadcast) { mPreviousPanId = Mac::kPanIdBroadcast; - mNetif.GetAnnounceBeginServer().SendAnnounce(1 << mPreviousChannel); + netif.GetAnnounceBeginServer().SendAnnounce(1 << mPreviousChannel); } otLogInfoMle(GetInstance(), "Mode -> Child"); @@ -628,7 +634,7 @@ otError Mle::SetTimeout(uint32_t aTimeout) mTimeout = aTimeout; - mNetif.GetMeshForwarder().GetDataPollManager().RecalculatePollPeriod(); + GetNetif().GetMeshForwarder().GetDataPollManager().RecalculatePollPeriod(); if (mRole == OT_DEVICE_ROLE_CHILD) { @@ -682,11 +688,13 @@ const Ip6::Address &Mle::GetLinkLocalAddress(void) const otError Mle::UpdateLinkLocalAddress(void) { - mNetif.RemoveUnicastAddress(mLinkLocal64); - mLinkLocal64.GetAddress().SetIid(*mNetif.GetMac().GetExtAddress()); - mNetif.AddUnicastAddress(mLinkLocal64); + ThreadNetif &netif = GetNetif(); - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_LL_ADDR); + netif.RemoveUnicastAddress(mLinkLocal64); + mLinkLocal64.GetAddress().SetIid(*netif.GetMac().GetExtAddress()); + netif.AddUnicastAddress(mLinkLocal64); + + netif.SetStateChangedFlags(OT_CHANGED_THREAD_LL_ADDR); return OT_ERROR_NONE; } @@ -698,14 +706,16 @@ const uint8_t *Mle::GetMeshLocalPrefix(void) const otError Mle::SetMeshLocalPrefix(const uint8_t *aMeshLocalPrefix) { + ThreadNetif &netif = GetNetif(); + if (memcmp(mMeshLocal64.GetAddress().mFields.m8, aMeshLocalPrefix, 8) == 0) { ExitNow(); } // We must remove the old address before adding the new one. - mNetif.RemoveUnicastAddress(mMeshLocal64); - mNetif.RemoveUnicastAddress(mMeshLocal16); + netif.RemoveUnicastAddress(mMeshLocal64); + netif.RemoveUnicastAddress(mMeshLocal16); memcpy(mMeshLocal64.GetAddress().mFields.m8, aMeshLocalPrefix, 8); memcpy(mMeshLocal16.GetAddress().mFields.m8, mMeshLocal64.GetAddress().mFields.m8, 8); @@ -717,22 +727,22 @@ otError Mle::SetMeshLocalPrefix(const uint8_t *aMeshLocalPrefix) memcpy(mRealmLocalAllThreadNodes.GetAddress().mFields.m8 + 4, mMeshLocal64.GetAddress().mFields.m8, 8); // Add the address back into the table. - mNetif.AddUnicastAddress(mMeshLocal64); + netif.AddUnicastAddress(mMeshLocal64); if (mRole >= OT_DEVICE_ROLE_CHILD) { - mNetif.AddUnicastAddress(mMeshLocal16); + netif.AddUnicastAddress(mMeshLocal16); } // update Leader ALOC if (mRole == OT_DEVICE_ROLE_LEADER) { - mNetif.RemoveUnicastAddress(mLeaderAloc); + netif.RemoveUnicastAddress(mLeaderAloc); AddLeaderAloc(); } // Changing the prefix also causes the mesh local address to be different. - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ML_ADDR); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ML_ADDR); exit: return OT_ERROR_NONE; @@ -750,22 +760,24 @@ const Ip6::Address *Mle::GetRealmLocalAllThreadNodesAddress(void) const uint16_t Mle::GetRloc16(void) const { - return mNetif.GetMac().GetShortAddress(); + return GetNetif().GetMac().GetShortAddress(); } otError Mle::SetRloc16(uint16_t aRloc16) { - mNetif.RemoveUnicastAddress(mMeshLocal16); + ThreadNetif &netif = GetNetif(); + + netif.RemoveUnicastAddress(mMeshLocal16); if (aRloc16 != Mac::kShortAddrInvalid) { // mesh-local 16 mMeshLocal16.GetAddress().mFields.m16[7] = HostSwap16(aRloc16); - mNetif.AddUnicastAddress(mMeshLocal16); + netif.AddUnicastAddress(mMeshLocal16); } - mNetif.GetMac().SetShortAddress(aRloc16); - mNetif.GetIp6().mMpl.SetSeedId(aRloc16); + netif.GetMac().SetShortAddress(aRloc16); + netif.GetIp6().mMpl.SetSeedId(aRloc16); return OT_ERROR_NONE; } @@ -779,7 +791,7 @@ void Mle::SetLeaderData(uint32_t aPartitionId, uint8_t aWeighting, uint8_t aLead { if (mLeaderData.GetPartitionId() != aPartitionId) { - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_PARTITION_ID); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_PARTITION_ID); } mLeaderData.SetPartitionId(aPartitionId); @@ -837,7 +849,7 @@ otError Mle::AddLeaderAloc(void) SuccessOrExit(error = GetLeaderAloc(mLeaderAloc.GetAddress())); - error = mNetif.AddUnicastAddress(mLeaderAloc); + error = GetNetif().AddUnicastAddress(mLeaderAloc); exit: return error; @@ -845,8 +857,10 @@ exit: const LeaderDataTlv &Mle::GetLeaderDataTlv(void) { - mLeaderData.SetDataVersion(mNetif.GetNetworkDataLeader().GetVersion()); - mLeaderData.SetStableDataVersion(mNetif.GetNetworkDataLeader().GetStableVersion()); + ThreadNetif &netif = GetNetif(); + + mLeaderData.SetDataVersion(netif.GetNetworkDataLeader().GetVersion()); + mLeaderData.SetStableDataVersion(netif.GetNetworkDataLeader().GetStableVersion()); return mLeaderData; } @@ -1042,7 +1056,7 @@ otError Mle::AppendLinkFrameCounter(Message &aMessage) LinkFrameCounterTlv tlv; tlv.Init(); - tlv.SetFrameCounter(mNetif.GetKeyManager().GetMacFrameCounter()); + tlv.SetFrameCounter(GetNetif().GetKeyManager().GetMacFrameCounter()); return aMessage.Append(&tlv, sizeof(tlv)); } @@ -1052,7 +1066,7 @@ otError Mle::AppendMleFrameCounter(Message &aMessage) MleFrameCounterTlv tlv; tlv.Init(); - tlv.SetFrameCounter(mNetif.GetKeyManager().GetMleFrameCounter()); + tlv.SetFrameCounter(GetNetif().GetKeyManager().GetMleFrameCounter()); return aMessage.Append(&tlv, sizeof(tlv)); } @@ -1070,8 +1084,8 @@ otError Mle::AppendAddress16(Message &aMessage, uint16_t aRloc16) otError Mle::AppendLeaderData(Message &aMessage) { mLeaderData.Init(); - mLeaderData.SetDataVersion(mNetif.GetNetworkDataLeader().GetVersion()); - mLeaderData.SetStableDataVersion(mNetif.GetNetworkDataLeader().GetStableVersion()); + mLeaderData.SetDataVersion(GetNetif().GetNetworkDataLeader().GetVersion()); + mLeaderData.SetStableDataVersion(GetNetif().GetNetworkDataLeader().GetStableVersion()); return aMessage.Append(&mLeaderData, sizeof(mLeaderData)); } @@ -1079,7 +1093,7 @@ otError Mle::AppendLeaderData(Message &aMessage) void Mle::FillNetworkDataTlv(NetworkDataTlv &aTlv, bool aStableOnly) { uint8_t length; - mNetif.GetNetworkDataLeader().GetNetworkData(aStableOnly, aTlv.GetNetworkData(), length); + GetNetif().GetNetworkDataLeader().GetNetworkData(aStableOnly, aTlv.GetNetworkData(), length); aTlv.SetLength(length); } @@ -1144,6 +1158,7 @@ otError Mle::AppendVersion(Message &aMessage) otError Mle::AppendAddressRegistration(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error; Tlv tlv; AddressRegistrationEntry entry; @@ -1155,14 +1170,14 @@ otError Mle::AppendAddressRegistration(Message &aMessage) SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); // write entries to message - for (const Ip6::NetifUnicastAddress *addr = mNetif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) { if (addr->GetAddress().IsLinkLocal() || addr->GetAddress() == mMeshLocal16.GetAddress()) { continue; } - if (mNetif.GetNetworkDataLeader().GetContext(addr->GetAddress(), context) == OT_ERROR_NONE) + if (netif.GetNetworkDataLeader().GetContext(addr->GetAddress(), context) == OT_ERROR_NONE) { // compressed entry entry.SetContextId(context.mContextId); @@ -1188,13 +1203,14 @@ exit: otError Mle::AppendActiveTimestamp(Message &aMessage, bool aCouldUseLocal) { + ThreadNetif &netif = GetNetif(); otError error; ActiveTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; - if ((timestamp = mNetif.GetActiveDataset().GetNetwork().GetTimestamp()) == NULL && aCouldUseLocal) + if ((timestamp = netif.GetActiveDataset().GetNetwork().GetTimestamp()) == NULL && aCouldUseLocal) { - timestamp = mNetif.GetActiveDataset().GetLocal().GetTimestamp(); + timestamp = netif.GetActiveDataset().GetLocal().GetTimestamp(); } VerifyOrExit(timestamp, error = OT_ERROR_NONE); @@ -1213,7 +1229,7 @@ otError Mle::AppendPendingTimestamp(Message &aMessage) PendingTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; - timestamp = mNetif.GetPendingDataset().GetNetwork().GetTimestamp(); + timestamp = GetNetif().GetPendingDataset().GetNetwork().GetTimestamp(); VerifyOrExit(timestamp && timestamp->GetSeconds() != 0, error = OT_ERROR_NONE); timestampTlv.Init(); @@ -1231,11 +1247,12 @@ void Mle::HandleNetifStateChanged(uint32_t aFlags, void *aContext) void Mle::HandleNetifStateChanged(uint32_t aFlags) { + ThreadNetif &netif = GetNetif(); VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED); if ((aFlags & (OT_CHANGED_IP6_ADDRESS_ADDED | OT_CHANGED_IP6_ADDRESS_REMOVED)) != 0) { - if (!mNetif.IsUnicastAddress(mMeshLocal64.GetAddress())) + if (!netif.IsUnicastAddress(mMeshLocal64.GetAddress())) { // Mesh Local EID was removed, choose a new one and add it back for (int i = 8; i < 16; i++) @@ -1243,8 +1260,8 @@ void Mle::HandleNetifStateChanged(uint32_t aFlags) mMeshLocal64.GetAddress().mFields.m8[i] = static_cast(otPlatRandomGet()); } - mNetif.AddUnicastAddress(mMeshLocal64); - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ML_ADDR); + netif.AddUnicastAddress(mMeshLocal64); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ML_ADDR); } if (mRole == OT_DEVICE_ROLE_CHILD && (mDeviceMode & ModeTlv::kModeFFD) == 0) @@ -1257,7 +1274,7 @@ void Mle::HandleNetifStateChanged(uint32_t aFlags) { if (mDeviceMode & ModeTlv::kModeFFD) { - mNetif.GetMle().HandleNetworkDataUpdateRouter(); + netif.GetMle().HandleNetworkDataUpdateRouter(); } else if ((aFlags & OT_CHANGED_THREAD_ROLE) == 0) { @@ -1265,7 +1282,7 @@ void Mle::HandleNetifStateChanged(uint32_t aFlags) } #if OPENTHREAD_ENABLE_BORDER_ROUTER - mNetif.GetNetworkDataLocal().SendServerDataNotification(); + netif.GetNetworkDataLocal().SendServerDataNotification(); #endif } @@ -1278,13 +1295,15 @@ exit: return; } -void Mle::HandleParentRequestTimer(void *aContext) +void Mle::HandleParentRequestTimer(Timer &aTimer) { - static_cast(aContext)->HandleParentRequestTimer(); + GetOwner(aTimer).HandleParentRequestTimer(); } void Mle::HandleParentRequestTimer(void) { + ThreadNetif &netif = GetNetif(); + switch (mParentRequestState) { case kParentIdle: @@ -1341,9 +1360,9 @@ void Mle::HandleParentRequestTimer(void) if (mReattachState == kReattachActive) { - if (mNetif.GetPendingDataset().Restore() == OT_ERROR_NONE) + if (netif.GetPendingDataset().Restore() == OT_ERROR_NONE) { - mNetif.GetPendingDataset().ApplyConfiguration(); + netif.GetPendingDataset().ApplyConfiguration(); mReattachState = kReattachPending; mParentRequestState = kParentRequestStart; mParentRequestTimer.Start(kParentRequestRouterTimeout); @@ -1356,8 +1375,8 @@ void Mle::HandleParentRequestTimer(void) else if (mReattachState == kReattachPending) { mReattachState = kReattachStop; - mNetif.GetActiveDataset().Restore(); - mNetif.GetPendingDataset().Set(mNetif.GetPendingDataset().GetLocal()); + netif.GetActiveDataset().Restore(); + netif.GetPendingDataset().Set(netif.GetPendingDataset().GetLocal()); } if (mReattachState == kReattachStop) @@ -1367,8 +1386,8 @@ void Mle::HandleParentRequestTimer(void) case kAttachAny: if (mPreviousPanId != Mac::kPanIdBroadcast) { - mNetif.GetMac().SetChannel(mPreviousChannel); - mNetif.GetMac().SetPanId(mPreviousPanId); + netif.GetMac().SetChannel(mPreviousChannel); + netif.GetMac().SetPanId(mPreviousPanId); mPreviousPanId = Mac::kPanIdBroadcast; BecomeDetached(); } @@ -1377,7 +1396,7 @@ void Mle::HandleParentRequestTimer(void) SendOrphanAnnounce(); BecomeDetached(); } - else if (mNetif.GetMle().BecomeLeader() != OT_ERROR_NONE) + else if (netif.GetMle().BecomeLeader() != OT_ERROR_NONE) { mParentRequestState = kParentIdle; BecomeDetached(); @@ -1434,9 +1453,9 @@ void Mle::HandleParentRequestTimer(void) } } -void Mle::HandleDelayedResponseTimer(void *aContext) +void Mle::HandleDelayedResponseTimer(Timer &aTimer) { - static_cast(aContext)->HandleDelayedResponseTimer(); + GetOwner(aTimer).HandleDelayedResponseTimer(); } void Mle::HandleDelayedResponseTimer(void) @@ -1594,8 +1613,8 @@ otError Mle::SendChildIdRequest(void) if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - mNetif.GetMeshForwarder().GetDataPollManager().SetAttachMode(true); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(false); + GetNetif().GetMeshForwarder().GetDataPollManager().SetAttachMode(true); + GetNetif().GetMeshForwarder().SetRxOnWhenIdle(false); } exit: @@ -1630,7 +1649,7 @@ otError Mle::SendDataRequest(const Ip6::Address &aDestination, const uint8_t *aT if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - mNetif.GetMeshForwarder().GetDataPollManager().SendFastPolls(DataPollManager::kDefaultFastPolls); + GetNetif().GetMeshForwarder().GetDataPollManager().SendFastPolls(DataPollManager::kDefaultFastPolls); } } @@ -1646,16 +1665,16 @@ exit: return error; } -void Mle::HandleSendChildUpdateRequest(void *aContext) +void Mle::HandleSendChildUpdateRequest(Tasklet &aTasklet) { - static_cast(aContext)->HandleSendChildUpdateRequest(); + GetOwner(aTasklet).HandleSendChildUpdateRequest(); } void Mle::HandleSendChildUpdateRequest(void) { - // a Network Data udpate can cause a change to the IPv6 address configuration + // a Network Data update can cause a change to the IPv6 address configuration // only send a Child Update Request after we know there are no more pending changes - if (mNetif.IsStateChangedCallbackPending()) + if (GetNetif().IsStateChangedCallbackPending()) { mSendChildUpdateRequest.Post(); } @@ -1667,6 +1686,7 @@ void Mle::HandleSendChildUpdateRequest(void) otError Mle::SendChildUpdateRequest(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Address destination; Message *message = NULL; @@ -1725,12 +1745,12 @@ otError Mle::SendChildUpdateRequest(void) if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - mNetif.GetMeshForwarder().GetDataPollManager().SetAttachMode(true); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(false); + netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(true); + netif.GetMeshForwarder().SetRxOnWhenIdle(false); } else { - mNetif.GetMeshForwarder().SetRxOnWhenIdle(true); + netif.GetMeshForwarder().SetRxOnWhenIdle(true); } exit: @@ -1803,6 +1823,7 @@ exit: otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; ChannelTlv channel; PanIdTlv panid; @@ -1818,7 +1839,7 @@ otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce) channel.Init(); channel.SetChannelPage(0); - channel.SetChannel(mNetif.GetMac().GetChannel()); + channel.SetChannel(netif.GetMac().GetChannel()); SuccessOrExit(error = message->Append(&channel, sizeof(channel))); if (aOrphanAnnounce) @@ -1836,7 +1857,7 @@ otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce) } panid.Init(); - panid.SetPanId(mNetif.GetMac().GetPanId()); + panid.SetPanId(netif.GetMac().GetPanId()); SuccessOrExit(error = message->Append(&panid, sizeof(panid))); memset(&destination, 0, sizeof(destination)); @@ -1861,7 +1882,7 @@ void Mle::SendOrphanAnnounce(void) MeshCoP::ChannelMask0Tlv *channelMask; uint8_t channel; - channelMask = static_cast(mNetif.GetActiveDataset().GetNetwork().Get( + channelMask = static_cast(GetNetif().GetActiveDataset().GetNetwork().Get( MeshCoP::Tlv::kChannelMask)); VerifyOrExit(channelMask != NULL); @@ -1898,6 +1919,7 @@ exit: otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Header header; uint32_t keySequence; @@ -1913,19 +1935,19 @@ otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) if (header.GetSecuritySuite() == Header::k154Security) { - header.SetFrameCounter(mNetif.GetKeyManager().GetMleFrameCounter()); + header.SetFrameCounter(netif.GetKeyManager().GetMleFrameCounter()); - keySequence = mNetif.GetKeyManager().GetCurrentKeySequence(); + keySequence = netif.GetKeyManager().GetCurrentKeySequence(); header.SetKeyId(keySequence); aMessage.Write(0, header.GetLength(), &header); - GenerateNonce(*mNetif.GetMac().GetExtAddress(), - mNetif.GetKeyManager().GetMleFrameCounter(), + GenerateNonce(*netif.GetMac().GetExtAddress(), + netif.GetKeyManager().GetMleFrameCounter(), Mac::Frame::kSecEncMic32, nonce); - aesCcm.SetKey(mNetif.GetKeyManager().GetCurrentMleKey(), 16); + aesCcm.SetKey(netif.GetKeyManager().GetCurrentMleKey(), 16); aesCcm.Init(16 + 16 + header.GetHeaderLength(), aMessage.GetLength() - (header.GetLength() - 1), sizeof(tag), nonce, sizeof(nonce)); @@ -1947,13 +1969,13 @@ otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) aesCcm.Finalize(tag, &tagLength); SuccessOrExit(error = aMessage.Append(tag, tagLength)); - mNetif.GetKeyManager().IncrementMleFrameCounter(); + netif.GetKeyManager().IncrementMleFrameCounter(); } messageInfo.SetPeerAddr(aDestination); messageInfo.SetSockAddr(mLinkLocal64.GetAddress()); messageInfo.SetPeerPort(kUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); messageInfo.SetHopLimit(255); SuccessOrExit(error = mSocket.SendTo(aMessage, messageInfo)); @@ -2001,6 +2023,8 @@ void Mle::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageI void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); + MleRouter &mle = netif.GetMle(); Header header; uint32_t keySequence; const uint8_t *mleKey; @@ -2030,7 +2054,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn switch (header.GetCommand()) { case Header::kCommandDiscoveryRequest: - mNetif.GetMle().HandleDiscoveryRequest(aMessage, aMessageInfo); + mle.HandleDiscoveryRequest(aMessage, aMessageInfo); break; case Header::kCommandDiscoveryResponse: @@ -2048,13 +2072,13 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn keySequence = header.GetKeyId(); - if (keySequence == mNetif.GetKeyManager().GetCurrentKeySequence()) + if (keySequence == netif.GetKeyManager().GetCurrentKeySequence()) { - mleKey = mNetif.GetKeyManager().GetCurrentMleKey(); + mleKey = netif.GetKeyManager().GetCurrentMleKey(); } else { - mleKey = mNetif.GetKeyManager().GetTemporaryMleKey(keySequence); + mleKey = netif.GetKeyManager().GetTemporaryMleKey(keySequence); } aMessage.MoveOffset(header.GetLength() - 1); @@ -2089,9 +2113,9 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn aesCcm.Finalize(tag, &tagLength); VerifyOrExit(messageTagLength == tagLength && memcmp(messageTag, tag, tagLength) == 0); - if (keySequence > mNetif.GetKeyManager().GetCurrentKeySequence()) + if (keySequence > netif.GetKeyManager().GetCurrentKeySequence()) { - mNetif.GetKeyManager().SetCurrentKeySequence(keySequence); + netif.GetKeyManager().SetCurrentKeySequence(keySequence); } aMessage.SetOffset(mleOffset); @@ -2114,7 +2138,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn } else { - neighbor = mNetif.GetMle().GetNeighbor(macAddr); + neighbor = mle.GetNeighbor(macAddr); } break; @@ -2169,15 +2193,15 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn switch (command) { case Header::kCommandLinkRequest: - mNetif.GetMle().HandleLinkRequest(aMessage, aMessageInfo); + mle.HandleLinkRequest(aMessage, aMessageInfo); break; case Header::kCommandLinkAccept: - mNetif.GetMle().HandleLinkAccept(aMessage, aMessageInfo, keySequence); + mle.HandleLinkAccept(aMessage, aMessageInfo, keySequence); break; case Header::kCommandLinkAcceptAndRequest: - mNetif.GetMle().HandleLinkAcceptAndRequest(aMessage, aMessageInfo, keySequence); + mle.HandleLinkAcceptAndRequest(aMessage, aMessageInfo, keySequence); break; case Header::kCommandAdvertisement: @@ -2185,7 +2209,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandDataRequest: - mNetif.GetMle().HandleDataRequest(aMessage, aMessageInfo); + mle.HandleDataRequest(aMessage, aMessageInfo); break; case Header::kCommandDataResponse: @@ -2193,7 +2217,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandParentRequest: - mNetif.GetMle().HandleParentRequest(aMessage, aMessageInfo); + mle.HandleParentRequest(aMessage, aMessageInfo); break; case Header::kCommandParentResponse: @@ -2201,7 +2225,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandChildIdRequest: - mNetif.GetMle().HandleChildIdRequest(aMessage, aMessageInfo, keySequence); + mle.HandleChildIdRequest(aMessage, aMessageInfo, keySequence); break; case Header::kCommandChildIdResponse: @@ -2211,7 +2235,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn case Header::kCommandChildUpdateRequest: if (mRole == OT_DEVICE_ROLE_LEADER || mRole == OT_DEVICE_ROLE_ROUTER) { - mNetif.GetMle().HandleChildUpdateRequest(aMessage, aMessageInfo, keySequence); + mle.HandleChildUpdateRequest(aMessage, aMessageInfo, keySequence); } else { @@ -2223,7 +2247,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn case Header::kCommandChildUpdateResponse: if (mRole == OT_DEVICE_ROLE_LEADER || mRole == OT_DEVICE_ROLE_ROUTER) { - mNetif.GetMle().HandleChildUpdateResponse(aMessage, aMessageInfo, keySequence); + mle.HandleChildUpdateResponse(aMessage, aMessageInfo, keySequence); } else { @@ -2243,6 +2267,7 @@ exit: otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Mac::ExtAddress macAddr; bool isNeighbor; @@ -2265,7 +2290,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo if (mRole != OT_DEVICE_ROLE_DETACHED) { - SuccessOrExit(error = mNetif.GetMle().HandleAdvertisement(aMessage, aMessageInfo)); + SuccessOrExit(error = netif.GetMle().HandleAdvertisement(aMessage, aMessageInfo)); } macAddr.Set(aMessageInfo.GetPeerAddr()); @@ -2295,7 +2320,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo route.IsValid()) { // Overwrite Route Data - mNetif.GetMle().ProcessRouteTlv(route); + netif.GetMle().ProcessRouteTlv(route); } mRetrieveNewNetworkData = true; @@ -2307,7 +2332,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - if ((neighbor = mNetif.GetMle().GetNeighbor(macAddr)) != NULL && + if ((neighbor = netif.GetMle().GetNeighbor(macAddr)) != NULL && neighbor->GetState() == Neighbor::kStateValid) { isNeighbor = true; @@ -2319,7 +2344,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo if (isNeighbor) { if (mRetrieveNewNetworkData || - (static_cast(leaderData.GetDataVersion() - mNetif.GetNetworkDataLeader().GetVersion()) > 0)) + (static_cast(leaderData.GetDataVersion() - netif.GetNetworkDataLeader().GetVersion()) > 0)) { delay = otPlatRandomGet() % kMleMaxResponseDelay; SendDataRequest(aMessageInfo.GetPeerAddr(), tlvs, sizeof(tlvs), delay); @@ -2354,6 +2379,7 @@ otError Mle::HandleDataResponse(const Message &aMessage, const Ip6::MessageInfo otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; LeaderDataTlv leaderData; NetworkDataTlv networkData; @@ -2389,12 +2415,12 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (mDeviceMode & ModeTlv::kModeFullNetworkData) { - diff = static_cast(leaderData.GetDataVersion() - mNetif.GetNetworkDataLeader().GetVersion()); + diff = static_cast(leaderData.GetDataVersion() - netif.GetNetworkDataLeader().GetVersion()); } else { diff = static_cast(leaderData.GetStableDataVersion() - - mNetif.GetNetworkDataLeader().GetStableVersion()); + netif.GetNetworkDataLeader().GetStableVersion()); } VerifyOrExit(diff > 0); @@ -2406,7 +2432,7 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a const MeshCoP::Timestamp *timestamp; VerifyOrExit(activeTimestamp.IsValid(), error = OT_ERROR_PARSE); - timestamp = mNetif.GetActiveDataset().GetNetwork().GetTimestamp(); + timestamp = netif.GetActiveDataset().GetNetwork().GetTimestamp(); // if received timestamp does not match the local value and message does not contain the dataset, // send MLE Data Request @@ -2427,7 +2453,7 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a const MeshCoP::Timestamp *timestamp; VerifyOrExit(pendingTimestamp.IsValid(), error = OT_ERROR_PARSE); - timestamp = mNetif.GetPendingDataset().GetNetwork().GetTimestamp(); + timestamp = netif.GetPendingDataset().GetNetwork().GetTimestamp(); // if received timestamp does not match the local value and message does not contain the dataset, // send MLE Data Request @@ -2446,9 +2472,9 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a { VerifyOrExit(networkData.IsValid(), error = OT_ERROR_PARSE); - mNetif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), - (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, - networkData.GetNetworkData(), networkData.GetLength()); + netif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), + (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, + networkData.GetNetworkData(), networkData.GetLength()); } else { @@ -2461,13 +2487,13 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (activeDatasetOffset > 0) { aMessage.Read(activeDatasetOffset, sizeof(tlv), &tlv); - mNetif.GetActiveDataset().Set(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), - tlv.GetLength()); + netif.GetActiveDataset().Set(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), + tlv.GetLength()); } } else { - mNetif.GetActiveDataset().Clear(false); + netif.GetActiveDataset().Clear(false); } // Pending Dataset @@ -2476,13 +2502,13 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (pendingDatasetOffset > 0) { aMessage.Read(pendingDatasetOffset, sizeof(tlv), &tlv); - mNetif.GetPendingDataset().Set(pendingTimestamp, aMessage, pendingDatasetOffset + sizeof(tlv), - tlv.GetLength()); + netif.GetPendingDataset().Set(pendingTimestamp, aMessage, pendingDatasetOffset + sizeof(tlv), + tlv.GetLength()); } } else { - mNetif.GetPendingDataset().Clear(false); + netif.GetPendingDataset().Clear(false); } mRetrieveNewNetworkData = false; @@ -2507,7 +2533,7 @@ bool Mle::IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, ConnectivityTlv { bool rval = false; - uint8_t candidateLinkQualityIn = mParentCandidate.GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + uint8_t candidateLinkQualityIn = mParentCandidate.GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); uint8_t candidateTwoWayLinkQuality = (candidateLinkQualityIn < mParentCandidate.GetLinkQualityOut()) ? candidateLinkQualityIn : mParentCandidate.GetLinkQualityOut(); @@ -2554,6 +2580,7 @@ void Mle::ResetParentCandidate(void) otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; const ThreadMessageInfo *threadMessageInfo = static_cast(aMessageInfo.GetLinkInfo()); ResponseTlv response; @@ -2588,7 +2615,7 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkMargin, sizeof(linkMarginTlv), linkMarginTlv)); VerifyOrExit(linkMarginTlv.IsValid(), error = OT_ERROR_PARSE); - linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(netif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); if (linkMargin > linkMarginTlv.GetLinkMargin()) { @@ -2605,7 +2632,7 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf if ((mDeviceMode & ModeTlv::kModeFFD) && (mRole != OT_DEVICE_ROLE_DETACHED)) { - diff = static_cast(connectivity.GetIdSequence() - mNetif.GetMle().GetRouterIdSequence()); + diff = static_cast(connectivity.GetIdSequence() - netif.GetMle().GetRouterIdSequence()); switch (mParentRequestMode) { @@ -2617,13 +2644,13 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf case kAttachSame2: VerifyOrExit(leaderData.GetPartitionId() == mLeaderData.GetPartitionId()); VerifyOrExit(diff > 0 || - (diff == 0 && mNetif.GetMle().GetLeaderAge() < mNetif.GetMle().GetNetworkIdTimeout())); + (diff == 0 && netif.GetMle().GetLeaderAge() < netif.GetMle().GetNetworkIdTimeout())); break; case kAttachBetter: VerifyOrExit(leaderData.GetPartitionId() != mLeaderData.GetPartitionId()); - VerifyOrExit(mNetif.GetMle().ComparePartitions(connectivity.GetActiveRouters() <= 1, leaderData, - mNetif.GetMle().IsSingleton(), mLeaderData) > 0); + VerifyOrExit(netif.GetMle().ComparePartitions(connectivity.GetActiveRouters() <= 1, leaderData, + netif.GetMle().IsSingleton(), mLeaderData) > 0); break; } } @@ -2635,8 +2662,8 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf if (mDeviceMode & ModeTlv::kModeFFD) { - compare = mNetif.GetMle().ComparePartitions(connectivity.GetActiveRouters() <= 1, leaderData, - mParentIsSingleton, mParentLeaderData); + compare = netif.GetMle().ComparePartitions(connectivity.GetActiveRouters() <= 1, leaderData, + mParentIsSingleton, mParentLeaderData); } // only consider partitions that are the same or better @@ -2673,7 +2700,7 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf mParentCandidate.SetDeviceMode(ModeTlv::kModeFFD | ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeFullNetworkData | ModeTlv::kModeSecureDataRequest); mParentCandidate.GetLinkInfo().Clear(); - mParentCandidate.GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + mParentCandidate.GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); mParentCandidate.ResetLinkFailures(); mParentCandidate.SetLinkQualityOut(LinkQualityInfo::ConvertLinkMarginToLinkQuality(linkMarginTlv.GetLinkMargin())); mParentCandidate.SetState(Neighbor::kStateValid); @@ -2699,6 +2726,7 @@ exit: otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; LeaderDataTlv leaderData; SourceAddressTlv sourceAddress; @@ -2738,19 +2766,19 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn if (Tlv::GetOffset(aMessage, Tlv::kActiveDataset, offset) == OT_ERROR_NONE) { aMessage.Read(offset, sizeof(tlv), &tlv); - mNetif.GetActiveDataset().Set(activeTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); + netif.GetActiveDataset().Set(activeTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); } - else if (mNetif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL && - mNetif.GetActiveDataset().GetLocal().GetTimestamp() != NULL) + else if (netif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL && + netif.GetActiveDataset().GetLocal().GetTimestamp() != NULL) { - mNetif.GetActiveDataset().Set(mNetif.GetActiveDataset().GetLocal()); + netif.GetActiveDataset().Set(netif.GetActiveDataset().GetLocal()); } } // clear local Pending Dataset if device succeed to reattach using stored Pending Dataset if (mReattachState == kReattachPending) { - mNetif.GetPendingDataset().GetLocal().Clear(true); + netif.GetPendingDataset().GetLocal().Clear(true); } // Pending Timestamp @@ -2762,12 +2790,12 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn if (Tlv::GetOffset(aMessage, Tlv::kPendingDataset, offset) == OT_ERROR_NONE) { aMessage.Read(offset, sizeof(tlv), &tlv); - mNetif.GetPendingDataset().Set(pendingTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); + netif.GetPendingDataset().Set(pendingTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); } } else { - mNetif.GetPendingDataset().Clear(true); + netif.GetPendingDataset().Clear(true); } // Parent Attach Success @@ -2779,19 +2807,19 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - mNetif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(false); + netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); + netif.GetMeshForwarder().SetRxOnWhenIdle(false); } else { - mNetif.GetMeshForwarder().SetRxOnWhenIdle(true); + netif.GetMeshForwarder().SetRxOnWhenIdle(true); } // Route if ((Tlv::GetTlv(aMessage, Tlv::kRoute, sizeof(route), route) == OT_ERROR_NONE) && (mDeviceMode & ModeTlv::kModeFFD)) { - SuccessOrExit(error = mNetif.GetMle().ProcessRouteTlv(route)); + SuccessOrExit(error = netif.GetMle().ProcessRouteTlv(route)); } mParent = mParentCandidate; @@ -2799,11 +2827,11 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn mParent.SetRloc16(sourceAddress.GetRloc16()); - mNetif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), - (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, - networkData.GetNetworkData(), networkData.GetLength()); + netif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), + (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, + networkData.GetNetworkData(), networkData.GetLength()); - mNetif.GetActiveDataset().ApplyConfiguration(); + netif.GetActiveDataset().ApplyConfiguration(); SuccessOrExit(error = SetStateChild(shortAddress.GetRloc16())); @@ -2822,6 +2850,7 @@ otError Mle::HandleChildUpdateRequest(const Message &aMessage, const Ip6::Messag { static const uint8_t kMaxResponseTlvs = 5; + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; SourceAddressTlv sourceAddress; LeaderDataTlv leaderData; @@ -2846,9 +2875,9 @@ otError Mle::HandleChildUpdateRequest(const Message &aMessage, const Ip6::Messag SetLeaderData(leaderData.GetPartitionId(), leaderData.GetWeighting(), leaderData.GetLeaderRouterId()); if ((mDeviceMode & ModeTlv::kModeFullNetworkData && - leaderData.GetDataVersion() != mNetif.GetNetworkDataLeader().GetVersion()) || + leaderData.GetDataVersion() != netif.GetNetworkDataLeader().GetVersion()) || ((mDeviceMode & ModeTlv::kModeFullNetworkData) == 0 && - leaderData.GetStableDataVersion() != mNetif.GetNetworkDataLeader().GetStableVersion())) + leaderData.GetStableDataVersion() != netif.GetNetworkDataLeader().GetStableVersion())) { mRetrieveNewNetworkData = true; } @@ -2857,11 +2886,11 @@ otError Mle::HandleChildUpdateRequest(const Message &aMessage, const Ip6::Messag if (Tlv::GetTlv(aMessage, Tlv::kNetworkData, sizeof(networkData), networkData) == OT_ERROR_NONE) { VerifyOrExit(networkData.IsValid(), error = OT_ERROR_PARSE); - mNetif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), - leaderData.GetStableDataVersion(), - (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, - networkData.GetNetworkData(), - networkData.GetLength()); + netif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), + leaderData.GetStableDataVersion(), + (mDeviceMode & ModeTlv::kModeFullNetworkData) == 0, + networkData.GetNetworkData(), + networkData.GetLength()); } } @@ -2896,6 +2925,7 @@ exit: otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; StatusTlv status; ModeTlv mode; @@ -2974,15 +3004,15 @@ otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::Messa if ((mDeviceMode & ModeTlv::kModeRxOnWhenIdle) == 0) { - mNetif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(false); + netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); + netif.GetMeshForwarder().SetRxOnWhenIdle(false); mParentRequestTimer.Stop(); } else { mParentRequestTimer.Start(Timer::SecToMsec(mTimeout) - static_cast(kUnicastRetransmissionDelay) * kMaxChildKeepAliveAttempts); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(true); + netif.GetMeshForwarder().SetRxOnWhenIdle(true); } mChildUpdateAttempts = 0; @@ -3006,6 +3036,7 @@ exit: otError Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; ChannelTlv channel; ActiveTimestampTlv timestamp; @@ -3023,15 +3054,15 @@ otError Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMe SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kPanId, sizeof(panid), panid)); VerifyOrExit(panid.IsValid(), error = OT_ERROR_PARSE); - localTimestamp = mNetif.GetActiveDataset().GetNetwork().GetTimestamp(); + localTimestamp = netif.GetActiveDataset().GetNetwork().GetTimestamp(); if (localTimestamp == NULL || localTimestamp->Compare(timestamp) > 0) { Stop(false); - mPreviousChannel = mNetif.GetMac().GetChannel(); - mPreviousPanId = mNetif.GetMac().GetPanId(); - mNetif.GetMac().SetChannel(static_cast(channel.GetChannel())); - mNetif.GetMac().SetPanId(panid.GetPanId()); + mPreviousChannel = netif.GetMac().GetChannel(); + mPreviousPanId = netif.GetMac().GetPanId(); + netif.GetMac().SetChannel(static_cast(channel.GetChannel())); + netif.GetMac().SetPanId(panid.GetPanId()); Start(false, true); } else @@ -3251,6 +3282,7 @@ Router *Mle::GetParent(void) otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_DROP; Ip6::MessageInfo messageInfo; @@ -3259,22 +3291,33 @@ otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::He ExitNow(error = OT_ERROR_NONE); } - if (mNetif.IsUnicastAddress(aIp6Header.GetDestination())) + if (netif.IsUnicastAddress(aIp6Header.GetDestination())) { ExitNow(error = OT_ERROR_NONE); } messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - mNetif.GetIp6().mIcmp.SendError(Ip6::IcmpHeader::kTypeDstUnreach, - Ip6::IcmpHeader::kCodeDstUnreachNoRoute, - messageInfo, aIp6Header); + netif.GetIp6().mIcmp.SendError(Ip6::IcmpHeader::kTypeDstUnreach, + Ip6::IcmpHeader::kCodeDstUnreachNoRoute, + messageInfo, aIp6Header); exit: return error; } +Mle &Mle::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Mle &mle = *static_cast(aContext.GetContext()); +#else + Mle &mle = otGetInstance()->mThreadNetif.GetMle(); + OT_UNUSED_VARIABLE(aContext); +#endif + return mle; +} + } // namespace Mle } // namespace ot diff --git a/src/core/thread/mle.hpp b/src/core/thread/mle.hpp index 48c5b4019..650d62cd7 100644 --- a/src/core/thread/mle.hpp +++ b/src/core/thread/mle.hpp @@ -37,6 +37,7 @@ #include #include "common/encoding.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "mac/mac.hpp" #include "meshcop/joiner_router.hpp" @@ -446,7 +447,7 @@ private: * This class implements MLE functionality required by the Thread EndDevices, Router, and Leader roles. * */ -class Mle +class Mle: public ThreadNetifLocator { public: /** @@ -457,14 +458,6 @@ public: */ explicit Mle(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method enables MLE. * @@ -1319,8 +1312,6 @@ protected: */ otError AddDelayedResponse(Message &aMessage, const Ip6::Address &aDestination, uint16_t aDelay); - ThreadNetif &mNetif; ///< The Thread Network Interface object. - LeaderDataTlv mLeaderData; ///< Last received Leader Data TLV. bool mRetrieveNewNetworkData; ///< Indicating new Network Data is needed if set. @@ -1380,13 +1371,13 @@ private: static void HandleNetifStateChanged(uint32_t aFlags, void *aContext); void HandleNetifStateChanged(uint32_t aFlags); - static void HandleParentRequestTimer(void *aContext); + static void HandleParentRequestTimer(Timer &aTimer); void HandleParentRequestTimer(void); - static void HandleDelayedResponseTimer(void *aContext); + static void HandleDelayedResponseTimer(Timer &aTimer); void HandleDelayedResponseTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); void HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleSendChildUpdateRequest(void *aContext); + static void HandleSendChildUpdateRequest(Tasklet &aTasklet); void HandleSendChildUpdateRequest(void); otError HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo); @@ -1407,6 +1398,8 @@ private: bool IsBetterParent(uint16_t aRloc16, uint8_t aLinkQuality, ConnectivityTlv &aConnectivityTlv); void ResetParentCandidate(void); + static Mle &GetOwner(const Context &aContext); + MessageQueue mDelayedResponses; struct diff --git a/src/core/thread/mle_router.cpp b/src/core/thread/mle_router.cpp index d2eea8dff..8279ee2e9 100644 --- a/src/core/thread/mle_router.cpp +++ b/src/core/thread/mle_router.cpp @@ -41,6 +41,7 @@ #include #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/encoding.hpp" @@ -104,7 +105,7 @@ void MleRouter::SetRouterRoleEnabled(bool aEnabled) break; case OT_DEVICE_ROLE_CHILD: - mNetif.GetMac().SetBeaconEnabled(mRouterRoleEnabled); + GetNetif().GetMac().SetBeaconEnabled(mRouterRoleEnabled); break; case OT_DEVICE_ROLE_ROUTER: @@ -193,6 +194,7 @@ exit: otError MleRouter::ReleaseRouterId(uint8_t aRouterId) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Router *router = GetRouter(aRouterId); @@ -216,8 +218,8 @@ otError MleRouter::ReleaseRouterId(uint8_t aRouterId) mRouterIdSequence++; mRouterIdSequenceLastUpdated = Timer::GetNow(); - mNetif.GetAddressResolver().Remove(aRouterId); - mNetif.GetNetworkDataLeader().RemoveBorderRouter(GetRloc16(aRouterId)); + netif.GetAddressResolver().Remove(aRouterId); + netif.GetNetworkDataLeader().RemoveBorderRouter(GetRloc16(aRouterId)); ResetAdvertiseInterval(); exit: @@ -231,6 +233,7 @@ uint32_t MleRouter::GetLeaderAge(void) const otError MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); @@ -246,8 +249,8 @@ otError MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) } mAdvertiseTimer.Stop(); - mNetif.GetAddressResolver().Clear(); - mNetif.GetMeshForwarder().SetRxOnWhenIdle(true); + netif.GetAddressResolver().Clear(); + netif.GetMeshForwarder().SetRxOnWhenIdle(true); mRouterSelectionJitterTimeout = 0; switch (mRole) @@ -272,6 +275,7 @@ exit: otError MleRouter::BecomeLeader(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; uint8_t routerId; Router *router; @@ -294,9 +298,9 @@ otError MleRouter::BecomeLeader(void) SetRouterId(routerId); - router->SetExtAddress(*mNetif.GetMac().GetExtAddress()); + router->SetExtAddress(*netif.GetMac().GetExtAddress()); mAdvertiseTimer.Stop(); - mNetif.GetAddressResolver().Clear(); + netif.GetAddressResolver().Clear(); if (mFixedLeaderPartitionId != 0) { @@ -309,8 +313,8 @@ otError MleRouter::BecomeLeader(void) mRouterIdSequence = static_cast(otPlatRandomGet()); - mNetif.GetNetworkDataLeader().Reset(); - mNetif.GetLeader().SetEmptyCommissionerData(); + netif.GetNetworkDataLeader().Reset(); + netif.GetLeader().SetEmptyCommissionerData(); SuccessOrExit(error = SetStateLeader(GetRloc16(mRouterId))); @@ -320,20 +324,22 @@ exit: void MleRouter::StopLeader(void) { - mNetif.GetCoap().RemoveResource(mAddressSolicit); - mNetif.GetCoap().RemoveResource(mAddressRelease); - mNetif.GetActiveDataset().StopLeader(); - mNetif.GetPendingDataset().StopLeader(); + ThreadNetif &netif = GetNetif(); + + netif.GetCoap().RemoveResource(mAddressSolicit); + netif.GetCoap().RemoveResource(mAddressRelease); + netif.GetActiveDataset().StopLeader(); + netif.GetPendingDataset().StopLeader(); mAdvertiseTimer.Stop(); - mNetif.GetNetworkDataLeader().Stop(); - mNetif.UnsubscribeAllRoutersMulticast(); + netif.GetNetworkDataLeader().Stop(); + netif.UnsubscribeAllRoutersMulticast(); } otError MleRouter::HandleDetachStart(void) { otError error = OT_ERROR_NONE; - mNetif.GetAddressResolver().Clear(); + GetNetif().GetAddressResolver().Clear(); for (int i = 0; i <= kMaxRouterId; i++) { @@ -348,6 +354,7 @@ otError MleRouter::HandleDetachStart(void) otError MleRouter::HandleChildStart(AttachMode aMode) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; mRouterIdSequenceLastUpdated = Timer::GetNow(); mRouterSelectionJitterTimeout = (otPlatRandomGet() % mRouterSelectionJitter) + 1; @@ -357,10 +364,10 @@ otError MleRouter::HandleChildStart(AttachMode aMode) if (mRouterRoleEnabled) { - mNetif.GetMac().SetBeaconEnabled(true); + netif.GetMac().SetBeaconEnabled(true); } - mNetif.SubscribeAllRoutersMulticast(); + netif.SubscribeAllRoutersMulticast(); VerifyOrExit(IsRouterIdValid(mPreviousRouterId), error = OT_ERROR_INVALID_STATE); @@ -414,9 +421,11 @@ exit: otError MleRouter::SetStateRouter(uint16_t aRloc16) { + ThreadNetif &netif = GetNetif(); + if (mRole != OT_DEVICE_ROLE_ROUTER) { - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); } SetRloc16(aRloc16); @@ -425,14 +434,14 @@ otError MleRouter::SetStateRouter(uint16_t aRloc16) mParentRequestTimer.Stop(); ResetAdvertiseInterval(); - mNetif.SubscribeAllRoutersMulticast(); + netif.SubscribeAllRoutersMulticast(); mRouters[mRouterId].SetNextHop(mRouterId); mPreviousPartitionId = mLeaderData.GetPartitionId(); - mNetif.GetNetworkDataLeader().Stop(); + netif.GetNetworkDataLeader().Stop(); mStateUpdateTimer.Start(kStateUpdatePeriod); - mNetif.GetIp6().SetForwardingEnabled(true); - mNetif.GetIp6().mMpl.SetTimerExpirations(kMplRouterDataMessageTimerExpirations); - mNetif.GetMac().SetBeaconEnabled(true); + netif.GetIp6().SetForwardingEnabled(true); + netif.GetIp6().mMpl.SetTimerExpirations(kMplRouterDataMessageTimerExpirations); + netif.GetMac().SetBeaconEnabled(true); for (int i = 0; i < mMaxChildrenAllowed; i++) { @@ -449,9 +458,11 @@ otError MleRouter::SetStateRouter(uint16_t aRloc16) otError MleRouter::SetStateLeader(uint16_t aRloc16) { + ThreadNetif &netif = GetNetif(); + if (mRole != OT_DEVICE_ROLE_LEADER) { - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_ROLE); } SetRloc16(aRloc16); @@ -461,20 +472,20 @@ otError MleRouter::SetStateLeader(uint16_t aRloc16) ResetAdvertiseInterval(); AddLeaderAloc(); - mNetif.SubscribeAllRoutersMulticast(); + netif.SubscribeAllRoutersMulticast(); mRouters[mRouterId].SetNextHop(mRouterId); mPreviousPartitionId = mLeaderData.GetPartitionId(); mStateUpdateTimer.Start(kStateUpdatePeriod); mRouters[mRouterId].SetLastHeard(Timer::GetNow()); - mNetif.GetNetworkDataLeader().Start(); - mNetif.GetActiveDataset().StartLeader(); - mNetif.GetPendingDataset().StartLeader(); - mNetif.GetCoap().AddResource(mAddressSolicit); - mNetif.GetCoap().AddResource(mAddressRelease); - mNetif.GetIp6().SetForwardingEnabled(true); - mNetif.GetIp6().mMpl.SetTimerExpirations(kMplRouterDataMessageTimerExpirations); - mNetif.GetMac().SetBeaconEnabled(true); + netif.GetNetworkDataLeader().Start(); + netif.GetActiveDataset().StartLeader(); + netif.GetPendingDataset().StartLeader(); + netif.GetCoap().AddResource(mAddressSolicit); + netif.GetCoap().AddResource(mAddressRelease); + netif.GetIp6().SetForwardingEnabled(true); + netif.GetIp6().mMpl.SetTimerExpirations(kMplRouterDataMessageTimerExpirations); + netif.GetMac().SetBeaconEnabled(true); for (int i = 0; i < mMaxChildrenAllowed; i++) { @@ -489,10 +500,9 @@ otError MleRouter::SetStateLeader(uint16_t aRloc16) return OT_ERROR_NONE; } -bool MleRouter::HandleAdvertiseTimer(void *aContext) +bool MleRouter::HandleAdvertiseTimer(TrickleTimer &aTimer) { - MleRouter *obj = static_cast(aContext); - return obj->HandleAdvertiseTimer(); + return GetOwner(aTimer).HandleAdvertiseTimer(); } bool MleRouter::HandleAdvertiseTimer(void) @@ -710,7 +720,7 @@ otError MleRouter::HandleLinkRequest(const Message &aMessage, const Ip6::Message neighbor->SetExtAddress(macAddr); neighbor->GetLinkInfo().Clear(); - neighbor->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + neighbor->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), threadMessageInfo->mRss); neighbor->ResetLinkFailures(); neighbor->SetState(Neighbor::kStateLinkRequest); } @@ -772,7 +782,7 @@ otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, Neighbor SuccessOrExit(error = AppendMleFrameCounter(*message)); // always append a link margin, regardless of whether or not it was requested - linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(GetNetif().GetMac().GetNoiseFloor(), threadMessageInfo->mRss); // add for certification testing if (isAssignLinkQuality && aNeighbor != NULL && @@ -1010,7 +1020,7 @@ otError MleRouter::HandleLinkAccept(const Message &aMessage, const Ip6::MessageI router->SetLastHeard(Timer::GetNow()); router->SetDeviceMode(ModeTlv::kModeFFD | ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeFullNetworkData); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + router->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), threadMessageInfo->mRss); router->ResetLinkFailures(); router->SetState(Neighbor::kStateValid); router->SetKeySequence(aKeySequence); @@ -1113,7 +1123,7 @@ uint8_t MleRouter::GetLinkCost(uint8_t aRouterId) // NULL aRouterId indicates non-existing next hop, hence return kMaxRouteCost for it. VerifyOrExit(aRouterId != mRouterId && router != NULL && router->GetState() == Neighbor::kStateValid); - rval = router->GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + rval = router->GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); if (rval > router->GetLinkQualityOut()) { @@ -1159,7 +1169,7 @@ otError MleRouter::ProcessRouteTlv(const RouteTlv &aRoute) if (old && !mRouters[i].IsAllocated()) { mRouters[i].SetNextHop(kInvalidRouterId); - mNetif.GetAddressResolver().Remove(i); + GetNetif().GetAddressResolver().Remove(i); } } @@ -1260,6 +1270,7 @@ uint8_t MleRouter::GetActiveRouterCount(void) const otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; const ThreadMessageInfo *threadMessageInfo = static_cast(aMessageInfo.GetLinkInfo()); Mac::ExtAddress macAddr; @@ -1439,7 +1450,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa { router->SetExtAddress(macAddr); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + router->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); router->ResetLinkFailures(); router->SetState(Neighbor::kStateLinkRequest); SendLinkRequest(router); @@ -1486,7 +1497,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa { router->SetExtAddress(macAddr); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + router->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); router->ResetLinkFailures(); router->SetState(Neighbor::kStateLinkRequest); router->SetDataRequestPending(false); @@ -1501,7 +1512,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa UpdateRoutes(route, routerId); #if OPENTHREAD_ENABLE_BORDER_ROUTER - mNetif.GetNetworkDataLocal().SendServerDataNotification(); + netif.GetNetworkDataLocal().SendServerDataNotification(); #endif exit: @@ -1626,7 +1637,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) GetRloc16(i), GetRloc16(mRouters[i].GetNextHop()), mRouters[i].GetCost(), - GetLinkCost(i), mRouters[i].GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()), + GetLinkCost(i), mRouters[i].GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()), mRouters[i].GetLinkQualityOut()); } @@ -1711,7 +1722,7 @@ otError MleRouter::HandleParentRequest(const Message &aMessage, const Ip6::Messa // MAC Address child->SetExtAddress(macAddr); child->GetLinkInfo().Clear(); - child->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + child->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), threadMessageInfo->mRss); child->ResetLinkFailures(); child->SetState(Neighbor::kStateParentRequest); child->SetDataRequestPending(false); @@ -1726,9 +1737,9 @@ exit: return error; } -void MleRouter::HandleStateUpdateTimer(void *aContext) +void MleRouter::HandleStateUpdateTimer(Timer &aTimer) { - static_cast(aContext)->HandleStateUpdateTimer(); + GetOwner(aTimer).HandleStateUpdateTimer(); } void MleRouter::HandleStateUpdateTimer(void) @@ -1927,7 +1938,7 @@ otError MleRouter::SendParentResponse(Child *aChild, const ChallengeTlv &challen } else { - error = AppendLinkMargin(*message, aChild->GetLinkInfo().GetLinkMargin(mNetif.GetMac().GetNoiseFloor())); + error = AppendLinkMargin(*message, aChild->GetLinkInfo().GetLinkMargin(GetNetif().GetMac().GetNoiseFloor())); SuccessOrExit(error); } @@ -1983,7 +1994,7 @@ otError MleRouter::UpdateChildAddresses(const AddressRegistrationTlv &aTlv, Chil if (entry->IsCompressed()) { // xxx check if context id exists - mNetif.GetNetworkDataLeader().GetContext(entry->GetContextId(), context); + GetNetif().GetNetworkDataLeader().GetContext(entry->GetContextId(), context); memcpy(&address, context.mPrefix, BitVectorBytes(context.mPrefixLength)); address.SetIid(entry->GetIid()); } @@ -2041,6 +2052,7 @@ otError MleRouter::UpdateChildAddresses(const AddressRegistrationTlv &aTlv, Chil otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; const ThreadMessageInfo *threadMessageInfo = static_cast(aMessageInfo.GetLinkInfo()); Mac::ExtAddress macAddr; @@ -2147,7 +2159,7 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess if (!child->IsRxOnWhenIdle()) { - mNetif.GetMeshForwarder().ClearChildIndirectMessages(*child); + netif.GetMeshForwarder().ClearChildIndirectMessages(*child); } } @@ -2157,7 +2169,7 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess child->SetMleFrameCounter(mleFrameCounter.GetFrameCounter()); child->SetKeySequence(aKeySequence); child->SetDeviceMode(mode.GetMode()); - child->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + child->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); child->SetTimeout(timeout.GetTimeout()); if (mode.GetMode() & ModeTlv::kModeFullNetworkData) @@ -2179,15 +2191,15 @@ otError MleRouter::HandleChildIdRequest(const Message &aMessage, const Ip6::Mess } if (activeTimestamp.GetLength() == 0 || - mNetif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL || - mNetif.GetActiveDataset().GetNetwork().GetTimestamp()->Compare(activeTimestamp) != 0) + netif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL || + netif.GetActiveDataset().GetNetwork().GetTimestamp()->Compare(activeTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kActiveDataset); } if (pendingTimestamp.GetLength() == 0 || - mNetif.GetPendingDataset().GetNetwork().GetTimestamp() == NULL || - mNetif.GetPendingDataset().GetNetwork().GetTimestamp()->Compare(pendingTimestamp) != 0) + netif.GetPendingDataset().GetNetwork().GetTimestamp() == NULL || + netif.GetPendingDataset().GetNetwork().GetTimestamp()->Compare(pendingTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kPendingDataset); } @@ -2410,7 +2422,7 @@ otError MleRouter::HandleChildUpdateResponse(const Message &aMessage, const Ip6: SetChildStateToValid(child); child->SetLastHeard(Timer::GetNow()); child->SetKeySequence(aKeySequence); - child->GetLinkInfo().AddRss(mNetif.GetMac().GetNoiseFloor(), threadMessageInfo->mRss); + child->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), threadMessageInfo->mRss); exit: return error; @@ -2418,6 +2430,7 @@ exit: otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; TlvRequestTlv tlvRequest; ActiveTimestampTlv activeTimestamp; @@ -2452,15 +2465,15 @@ otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::Message numTlvs = tlvRequest.GetLength(); if (activeTimestamp.GetLength() == 0 || - mNetif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL || - mNetif.GetActiveDataset().GetNetwork().GetTimestamp()->Compare(activeTimestamp) != 0) + netif.GetActiveDataset().GetNetwork().GetTimestamp() == NULL || + netif.GetActiveDataset().GetNetwork().GetTimestamp()->Compare(activeTimestamp) != 0) { tlvs[numTlvs++] = Tlv::kActiveDataset; } if (pendingTimestamp.GetLength() == 0 || - mNetif.GetPendingDataset().GetNetwork().GetTimestamp() == NULL || - mNetif.GetPendingDataset().GetNetwork().GetTimestamp()->Compare(pendingTimestamp) != 0) + netif.GetPendingDataset().GetNetwork().GetTimestamp() == NULL || + netif.GetPendingDataset().GetNetwork().GetTimestamp()->Compare(pendingTimestamp) != 0) { tlvs[numTlvs++] = Tlv::kPendingDataset; } @@ -2474,6 +2487,7 @@ exit: otError MleRouter::HandleNetworkDataUpdateRouter(void) { static const uint8_t tlvs[] = {Tlv::kNetworkData}; + ThreadNetif &netif = GetNetif(); Ip6::Address destination; uint16_t delay; @@ -2501,14 +2515,14 @@ otError MleRouter::HandleNetworkDataUpdateRouter(void) if (child->IsFullNetworkData()) { - if (child->GetNetworkDataVersion() != mNetif.GetNetworkDataLeader().GetVersion()) + if (child->GetNetworkDataVersion() != netif.GetNetworkDataLeader().GetVersion()) { SendDataResponse(destination, tlvs, sizeof(tlvs), 0); } } else { - if (child->GetNetworkDataVersion() != mNetif.GetNetworkDataLeader().GetStableVersion()) + if (child->GetNetworkDataVersion() != netif.GetNetworkDataLeader().GetStableVersion()) { SendDataResponse(destination, tlvs, sizeof(tlvs), 0); } @@ -2554,6 +2568,7 @@ otError MleRouter::SetSteeringData(otExtAddress *aExtAddress) otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Tlv tlv; MeshCoP::Tlv meshcopTlv; @@ -2595,7 +2610,7 @@ otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::Me else // if steering data is not set out of band, fall back to network data #endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB { - VerifyOrExit(mNetif.GetNetworkDataLeader().IsJoiningEnabled(), error = OT_ERROR_NOT_CAPABLE); + VerifyOrExit(netif.GetNetworkDataLeader().IsJoiningEnabled(), error = OT_ERROR_NOT_CAPABLE); } } @@ -2604,7 +2619,7 @@ otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::Me case MeshCoP::Tlv::kExtendedPanId: aMessage.Read(offset, sizeof(extPanId), &extPanId); VerifyOrExit(extPanId.IsValid(), error = OT_ERROR_PARSE); - VerifyOrExit(memcmp(mNetif.GetMac().GetExtendedPanId(), extPanId.GetExtendedPanId(), OT_EXT_PAN_ID_SIZE), + VerifyOrExit(memcmp(netif.GetMac().GetExtendedPanId(), extPanId.GetExtendedPanId(), OT_EXT_PAN_ID_SIZE), error = OT_ERROR_DROP); break; @@ -2629,6 +2644,7 @@ exit: otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint16_t aPanId) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message; uint16_t startOffset; @@ -2655,7 +2671,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 discoveryResponse.Init(); discoveryResponse.SetVersion(kVersion); - if (mNetif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) + if (netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) { discoveryResponse.SetNativeCommissioner(true); } @@ -2668,12 +2684,12 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 // Extended PAN ID TLV extPanId.Init(); - extPanId.SetExtendedPanId(mNetif.GetMac().GetExtendedPanId()); + extPanId.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); SuccessOrExit(error = message->Append(&extPanId, sizeof(extPanId))); // Network Name TLV networkName.Init(); - networkName.SetNetworkName(mNetif.GetMac().GetNetworkName()); + networkName.SetNetworkName(netif.GetMac().GetNetworkName()); SuccessOrExit(error = message->Append(&networkName, sizeof(tlv) + networkName.GetLength())); #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB @@ -2688,7 +2704,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 #endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB { // Steering Data TLV - steeringData = mNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv(MeshCoP::Tlv::kSteeringData); + steeringData = netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(MeshCoP::Tlv::kSteeringData); if (steeringData != NULL) { @@ -2698,7 +2714,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 // Joiner UDP Port TLV joinerUdpPort.Init(); - joinerUdpPort.SetUdpPort(mNetif.GetJoinerRouter().GetJoinerUdpPort()); + joinerUdpPort.SetUdpPort(netif.GetJoinerRouter().GetJoinerUdpPort()); SuccessOrExit(error = message->Append(&joinerUdpPort, sizeof(tlv) + joinerUdpPort.GetLength())); tlv.SetLength(static_cast(message->GetLength() - startOffset)); @@ -2722,6 +2738,7 @@ exit: otError MleRouter::SendChildIdResponse(Child *aChild) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Address destination; Message *message; @@ -2748,7 +2765,7 @@ otError MleRouter::SendChildIdResponse(Child *aChild) while (FindChild(mNextChildId) != NULL); // allocate Child ID - aChild->SetRloc16(mNetif.GetMac().GetShortAddress() | mNextChildId); + aChild->SetRloc16(netif.GetMac().GetShortAddress() | mNextChildId); } SuccessOrExit(error = AppendAddress16(*message, aChild->GetRloc16())); @@ -2787,7 +2804,7 @@ otError MleRouter::SendChildIdResponse(Child *aChild) if (!aChild->IsRxOnWhenIdle()) { - mNetif.GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*aChild, false); + netif.GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*aChild, false); } memset(&destination, 0, sizeof(destination)); @@ -2810,16 +2827,17 @@ exit: otError MleRouter::SendChildUpdateRequest(Child *aChild) { static const uint8_t tlvs[] = {Tlv::kTimeout, Tlv::kAddressRegistration}; + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Address destination; Message *message; if (!aChild->IsRxOnWhenIdle()) { - uint8_t childIndex = mNetif.GetMle().GetChildIndex(*aChild); + uint8_t childIndex = netif.GetMle().GetChildIndex(*aChild); // No need to send "Child Update Request" to the sleepy child if there is one already queued for it. - for (message = mNetif.GetMeshForwarder().GetSendQueue().GetHead(); message; message = message->GetNext()) + for (message = netif.GetMeshForwarder().GetSendQueue().GetHead(); message; message = message->GetNext()) { if (message->GetChildMask(childIndex) && message->GetSubType() == Message::kSubTypeMleChildUpdateRequest) { @@ -3080,6 +3098,8 @@ exit: otError MleRouter::RemoveNeighbor(Neighbor &aNeighbor) { + ThreadNetif &netif = GetNetif(); + switch (mRole) { case OT_DEVICE_ROLE_DISABLED: @@ -3099,9 +3119,9 @@ otError MleRouter::RemoveNeighbor(Neighbor &aNeighbor) if (aNeighbor.IsStateValidOrRestoring() && !IsActiveRouter(aNeighbor.GetRloc16())) { aNeighbor.SetState(Neighbor::kStateInvalid); - mNetif.GetMeshForwarder().UpdateIndirectMessages(); - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_REMOVED); - mNetif.GetNetworkDataLeader().SendServerDataNotification(aNeighbor.GetRloc16()); + netif.GetMeshForwarder().UpdateIndirectMessages(); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_REMOVED); + netif.GetNetworkDataLeader().SendServerDataNotification(aNeighbor.GetRloc16()); RemoveStoredChild(aNeighbor.GetRloc16()); } else if ((aNeighbor.GetState() == Neighbor::kStateValid) && IsActiveRouter(aNeighbor.GetRloc16())) @@ -3287,7 +3307,7 @@ Neighbor *MleRouter::GetNeighbor(const Ip6::Address &aAddress) ExitNow(rval = GetNeighbor(macaddr)); } - if (mNetif.GetNetworkDataLeader().GetContext(aAddress, context) != OT_ERROR_NONE) + if (GetNetif().GetNetworkDataLeader().GetContext(aAddress, context) != OT_ERROR_NONE) { context.mContextId = 0xff; } @@ -3508,7 +3528,7 @@ otError MleRouter::RestoreChildren(void) uint16_t length; length = sizeof(childInfo); - SuccessOrExit(error = otPlatSettingsGet(mNetif.GetInstance(), Settings::kKeyChildInfo, i, + SuccessOrExit(error = otPlatSettingsGet(GetInstance(), Settings::kKeyChildInfo, i, reinterpret_cast(&childInfo), &length)); VerifyOrExit(length >= sizeof(childInfo), error = OT_ERROR_PARSE); @@ -3521,7 +3541,7 @@ otError MleRouter::RestoreChildren(void) child->SetDeviceMode(childInfo.mMode); child->SetState(Neighbor::kStateRestored); child->SetLastHeard(Timer::GetNow()); - mNetif.GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*child, true); + GetNetif().GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*child, true); } exit: @@ -3537,13 +3557,13 @@ otError MleRouter::RemoveStoredChild(uint16_t aChildRloc16) Settings::ChildInfo childInfo; uint16_t length = sizeof(childInfo); - SuccessOrExit(error = otPlatSettingsGet(mNetif.GetInstance(), Settings::kKeyChildInfo, i, + SuccessOrExit(error = otPlatSettingsGet(GetInstance(), Settings::kKeyChildInfo, i, reinterpret_cast(&childInfo), &length)); VerifyOrExit(length == sizeof(childInfo), error = OT_ERROR_PARSE); if (childInfo.mRloc16 == aChildRloc16) { - error = otPlatSettingsDelete(mNetif.GetInstance(), Settings::kKeyChildInfo, i); + error = otPlatSettingsDelete(GetNetif().GetInstance(), Settings::kKeyChildInfo, i); ExitNow(); } } @@ -3569,7 +3589,7 @@ otError MleRouter::StoreChild(uint16_t aChildRloc16) childInfo.mRloc16 = child->GetRloc16(); childInfo.mMode = child->GetDeviceMode(); - error = otPlatSettingsAdd(mNetif.GetInstance(), Settings::kKeyChildInfo, reinterpret_cast(&childInfo), + error = otPlatSettingsAdd(GetInstance(), Settings::kKeyChildInfo, reinterpret_cast(&childInfo), sizeof(childInfo)); exit: @@ -3580,7 +3600,7 @@ otError MleRouter::RefreshStoredChildren(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = otPlatSettingsDelete(mNetif.GetInstance(), Settings::kKeyChildInfo, -1)); + SuccessOrExit(error = otPlatSettingsDelete(GetInstance(), Settings::kKeyChildInfo, -1)); for (uint8_t i = 0; i < kMaxChildren; i++) { @@ -3608,7 +3628,7 @@ otError MleRouter::GetChildInfo(Child &aChild, otChildInfo &aChildInfo) aChildInfo.mChildId = GetChildId(aChild.GetRloc16()); aChildInfo.mNetworkDataVersion = aChild.GetNetworkDataVersion(); aChildInfo.mAge = Timer::MsecToSec(Timer::GetNow() - aChild.GetLastHeard()); - aChildInfo.mLinkQualityIn = aChild.GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + aChildInfo.mLinkQualityIn = aChild.GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); aChildInfo.mAverageRssi = aChild.GetLinkInfo().GetAverageRss(); aChildInfo.mLastRssi = aChild.GetLinkInfo().GetLastRss(); @@ -3647,7 +3667,7 @@ otError MleRouter::GetRouterInfo(uint16_t aRouterId, otRouterInfo &aRouterInfo) aRouterInfo.mNextHop = router->GetNextHop(); aRouterInfo.mLinkEstablished = router->GetState() == Neighbor::kStateValid; aRouterInfo.mPathCost = router->GetCost(); - aRouterInfo.mLinkQualityIn = router->GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + aRouterInfo.mLinkQualityIn = router->GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); aRouterInfo.mLinkQualityOut = router->GetLinkQualityOut(); aRouterInfo.mAge = static_cast(Timer::MsecToSec(Timer::GetNow() - router->GetLastHeard())); @@ -3708,7 +3728,7 @@ exit: aNeighInfo.mRloc16 = neighbor->GetRloc16(); aNeighInfo.mLinkFrameCounter = neighbor->GetLinkFrameCounter(); aNeighInfo.mMleFrameCounter = neighbor->GetMleFrameCounter(); - aNeighInfo.mLinkQualityIn = neighbor->GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + aNeighInfo.mLinkQualityIn = neighbor->GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); aNeighInfo.mAverageRssi = neighbor->GetLinkInfo().GetAverageRss(); aNeighInfo.mLastRssi = neighbor->GetLinkInfo().GetLastRss(); aNeighInfo.mRxOnWhenIdle = neighbor->IsRxOnWhenIdle(); @@ -3736,6 +3756,7 @@ void MleRouter::ResolveRoutingLoops(uint16_t aSourceMac, uint16_t aDestRloc16) otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { + ThreadNetif &netif = GetNetif(); Ip6::MessageInfo messageInfo; if (mRole == OT_DEVICE_ROLE_CHILD) @@ -3743,10 +3764,10 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I return Mle::CheckReachability(aMeshSource, aMeshDest, aIp6Header); } - if (aMeshDest == mNetif.GetMac().GetShortAddress()) + if (aMeshDest == netif.GetMac().GetShortAddress()) { // mesh destination is this device - if (mNetif.IsUnicastAddress(aIp6Header.GetDestination())) + if (netif.IsUnicastAddress(aIp6Header.GetDestination())) { // IPv6 destination is this device return OT_ERROR_NONE; @@ -3773,17 +3794,18 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - mNetif.GetIp6().mIcmp.SendError(Ip6::IcmpHeader::kTypeDstUnreach, - Ip6::IcmpHeader::kCodeDstUnreachNoRoute, - messageInfo, aIp6Header); + netif.GetIp6().mIcmp.SendError(Ip6::IcmpHeader::kTypeDstUnreach, + Ip6::IcmpHeader::kCodeDstUnreachNoRoute, + messageInfo, aIp6Header); return OT_ERROR_DROP; } otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; ThreadExtMacAddressTlv macAddr64Tlv; @@ -3797,10 +3819,10 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_SOLICIT); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); macAddr64Tlv.Init(); - macAddr64Tlv.SetMacAddr(*mNetif.GetMac().GetExtAddress()); + macAddr64Tlv.SetMacAddr(*netif.GetMac().GetExtAddress()); SuccessOrExit(error = message->Append(&macAddr64Tlv, sizeof(macAddr64Tlv))); if (IsRouterIdValid(mPreviousRouterId)) @@ -3818,8 +3840,8 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) messageInfo.SetSockAddr(GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, - &MleRouter::HandleAddressSolicitResponse, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, + &MleRouter::HandleAddressSolicitResponse, this)); otLogInfoMle(GetInstance(), "Sent address solicit to %04x", HostSwap16(messageInfo.GetPeerAddr().mFields.m16[7])); @@ -3835,6 +3857,7 @@ exit: otError MleRouter::SendAddressRelease(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; ThreadRloc16Tlv rlocTlv; @@ -3847,20 +3870,20 @@ otError MleRouter::SendAddressRelease(void) header.AppendUriPathOptions(OT_URI_PATH_ADDRESS_RELEASE); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); rlocTlv.Init(); rlocTlv.SetRloc16(GetRloc16(mRouterId)); SuccessOrExit(error = message->Append(&rlocTlv, sizeof(rlocTlv))); macAddr64Tlv.Init(); - macAddr64Tlv.SetMacAddr(*mNetif.GetMac().GetExtAddress()); + macAddr64Tlv.SetMacAddr(*netif.GetMac().GetExtAddress()); SuccessOrExit(error = message->Append(&macAddr64Tlv, sizeof(macAddr64Tlv))); messageInfo.SetSockAddr(GetMeshLocal16()); SuccessOrExit(error = GetLeaderAddress(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMle(GetInstance(), "Sent address release"); @@ -3957,7 +3980,7 @@ void MleRouter::HandleAddressSolicitResponse(Coap::Header *aHeader, Message *aMe if (old && !mRouters[i].IsAllocated()) { - mNetif.GetAddressResolver().Remove(i); + GetNetif().GetAddressResolver().Remove(i); } } @@ -4115,6 +4138,7 @@ exit: void MleRouter::SendAddressSolicitResponse(const Coap::Header &aRequestHeader, uint8_t aRouterId, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; ThreadStatusTlv statusTlv; @@ -4125,7 +4149,7 @@ void MleRouter::SendAddressSolicitResponse(const Coap::Header &aRequestHeader, u responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); statusTlv.Init(); statusTlv.SetStatus(!IsRouterIdValid(aRouterId) ? statusTlv.kNoAddressAvailable : statusTlv.kSuccess); @@ -4152,7 +4176,7 @@ void MleRouter::SendAddressSolicitResponse(const Coap::Header &aRequestHeader, u SuccessOrExit(error = message->Append(&routerMaskTlv, sizeof(routerMaskTlv))); } - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMle(GetInstance(), "Sent address reply"); @@ -4199,7 +4223,7 @@ void MleRouter::HandleAddressRelease(Coap::Header &aHeader, Message &aMessage, ReleaseRouterId(routerId); - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, aMessageInfo)); otLogInfoMle(GetInstance(), "Sent address release response"); @@ -4214,6 +4238,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) uint8_t linkQuality; uint8_t numChildren = 0; int8_t parentPriority = kParentPriorityMedium; + int8_t noiseFloor = GetNetif().GetMac().GetNoiseFloor(); if (mParentPriority != kParentPriorityUnspecified) { @@ -4256,7 +4281,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) break; case OT_DEVICE_ROLE_CHILD: - switch (mParent.GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor())) + switch (mParent.GetLinkInfo().GetLinkQuality(noiseFloor)) { case 1: tlv.SetLinkQuality1(tlv.GetLinkQuality1() + 1); @@ -4271,7 +4296,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) break; } - cost += LinkQualityToCost(mParent.GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor())); + cost += LinkQualityToCost(mParent.GetLinkInfo().GetLinkQuality(noiseFloor)); break; case OT_DEVICE_ROLE_ROUTER: @@ -4303,7 +4328,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) continue; } - linkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + linkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(noiseFloor); if (linkQuality > mRouters[i].GetLinkQualityOut()) { @@ -4348,6 +4373,7 @@ exit: otError MleRouter::AppendChildAddresses(Message &aMessage, Child &aChild) { + ThreadNetif &netif = GetNetif(); otError error; Tlv tlv; AddressRegistrationEntry entry; @@ -4365,7 +4391,7 @@ otError MleRouter::AppendChildAddresses(Message &aMessage, Child &aChild) break; } - if (mNetif.GetNetworkDataLeader().GetContext(aChild.GetIp6Address(i), context) == OT_ERROR_NONE) + if (netif.GetNetworkDataLeader().GetContext(aChild.GetIp6Address(i), context) == OT_ERROR_NONE) { // compressed entry entry.SetContextId(context.mContextId); @@ -4391,6 +4417,7 @@ exit: void MleRouter::FillRouteTlv(RouteTlv &tlv) { + uint8_t routeCount = 0; uint8_t linkCost; uint8_t cost; @@ -4447,7 +4474,7 @@ void MleRouter::FillRouteTlv(RouteTlv &tlv) else { tlv.SetLinkQualityIn(routeCount, - mRouters[i].GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor())); + mRouters[i].GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor())); } } @@ -4470,11 +4497,12 @@ exit: otError MleRouter::AppendActiveDataset(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; - VerifyOrExit(mNetif.GetActiveDataset().GetNetwork().GetSize() > 0); + VerifyOrExit(netif.GetActiveDataset().GetNetwork().GetSize() > 0); - SuccessOrExit(error = mNetif.GetActiveDataset().GetNetwork().AppendMleDatasetTlv(aMessage)); + SuccessOrExit(error = netif.GetActiveDataset().GetNetwork().AppendMleDatasetTlv(aMessage)); exit: return error; @@ -4482,12 +4510,13 @@ exit: otError MleRouter::AppendPendingDataset(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; - VerifyOrExit(mNetif.GetPendingDataset().GetNetwork().GetSize() > 0); + VerifyOrExit(netif.GetPendingDataset().GetNetwork().GetSize() > 0); - mNetif.GetPendingDataset().UpdateDelayTimer(); - SuccessOrExit(error = mNetif.GetPendingDataset().GetNetwork().AppendMleDatasetTlv(aMessage)); + netif.GetPendingDataset().UpdateDelayTimer(); + SuccessOrExit(error = netif.GetPendingDataset().GetNetwork().AppendMleDatasetTlv(aMessage)); exit: return error; @@ -4524,7 +4553,7 @@ bool MleRouter::HasOneNeighborwithComparableConnectivity(const RouteTlv &aRoute, continue; } - localLinkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + localLinkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); if (localLinkQuality > mRouters[i].GetLinkQualityOut()) { @@ -4572,7 +4601,7 @@ void MleRouter::SetChildStateToValid(Child *aChild) VerifyOrExit(aChild->GetState() != Neighbor::kStateValid); aChild->SetState(Neighbor::kStateValid); - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_ADDED); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_ADDED); StoreChild(aChild->GetRloc16()); exit: @@ -4603,7 +4632,7 @@ void MleRouter::RemoveChildren(void) switch (mChildren[i].GetState()) { case Neighbor::kStateValid: - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_REMOVED); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_CHILD_REMOVED); // Fall-through to next case @@ -4653,7 +4682,7 @@ uint8_t MleRouter::GetMinDowngradeNeighborRouters(void) continue; } - linkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(mNetif.GetMac().GetNoiseFloor()); + linkQuality = mRouters[i].GetLinkInfo().GetLinkQuality(GetNetif().GetMac().GetNoiseFloor()); if (linkQuality > mRouters[i].GetLinkQualityOut()) { @@ -4687,6 +4716,17 @@ exit: return error; } +MleRouter &MleRouter::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + MleRouter &mle = *static_cast(aContext.GetContext()); +#else + MleRouter &mle = otGetThreadNetif().GetMle(); + OT_UNUSED_VARIABLE(aContext); +#endif + return mle; +} + } // namespace Mle } // namespace ot diff --git a/src/core/thread/mle_router_ftd.hpp b/src/core/thread/mle_router_ftd.hpp index f667bd3f7..e79b3cdb8 100644 --- a/src/core/thread/mle_router_ftd.hpp +++ b/src/core/thread/mle_router_ftd.hpp @@ -773,11 +773,13 @@ private: uint8_t AllocateRouterId(uint8_t aRouterId); bool InRouterIdMask(uint8_t aRouterId); - static bool HandleAdvertiseTimer(void *aContext); + static bool HandleAdvertiseTimer(TrickleTimer &aTimer); bool HandleAdvertiseTimer(void); - static void HandleStateUpdateTimer(void *aContext); + static void HandleStateUpdateTimer(Timer &aTimer); void HandleStateUpdateTimer(void); + static MleRouter &GetOwner(const Context &aContext); + TrickleTimer mAdvertiseTimer; Timer mStateUpdateTimer; diff --git a/src/core/thread/network_data.cpp b/src/core/thread/network_data.cpp index fdcf168b6..6dea77a9c 100644 --- a/src/core/thread/network_data.cpp +++ b/src/core/thread/network_data.cpp @@ -52,7 +52,7 @@ namespace ot { namespace NetworkData { NetworkData::NetworkData(ThreadNetif &aThreadNetif, bool aLocal): - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mLocal(aLocal), mLastAttemptWait(false), mLastAttempt(0) @@ -60,10 +60,6 @@ NetworkData::NetworkData(ThreadNetif &aThreadNetif, bool aLocal): mLength = 0; } -otInstance *NetworkData::GetInstance(void) -{ - return mNetif.GetInstance(); -} void NetworkData::Clear(void) { @@ -198,7 +194,7 @@ otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, uint aConfig->mPrefix.mLength = prefix->GetPrefixLength(); aConfig->mPreference = hasRouteEntry->GetPreference(); aConfig->mStable = cur->IsStable(); - aConfig->mNextHopIsThisDevice = (hasRouteEntry->GetRloc() == mNetif.GetMle().GetRloc16()); + aConfig->mNextHopIsThisDevice = (hasRouteEntry->GetRloc() == GetNetif().GetMle().GetRloc16()); *aIterator = static_cast(reinterpret_cast(cur->GetNext()) - mTlvs); @@ -606,6 +602,7 @@ otError NetworkData::Remove(uint8_t *aStart, uint8_t aLength) otError NetworkData::SendServerDataNotification(uint16_t aRloc16) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; Message *message = NULL; @@ -619,7 +616,7 @@ otError NetworkData::SendServerDataNotification(uint16_t aRloc16) header.AppendUriPathOptions(OT_URI_PATH_SERVER_DATA); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); if (mLocal) { @@ -638,10 +635,10 @@ otError NetworkData::SendServerDataNotification(uint16_t aRloc16) SuccessOrExit(error = message->Append(&rloc16Tlv, sizeof(rloc16Tlv))); } - mNetif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); if (mLocal) { diff --git a/src/core/thread/network_data.hpp b/src/core/thread/network_data.hpp index d9fa19e6a..b045747d3 100644 --- a/src/core/thread/network_data.hpp +++ b/src/core/thread/network_data.hpp @@ -37,6 +37,7 @@ #include #include "coap/coap.hpp" +#include "common/locator.hpp" #include "net/udp6.hpp" #include "thread/lowpan.hpp" #include "thread/mle_router.hpp" @@ -83,7 +84,7 @@ namespace NetworkData { * This class implements Network Data processing. * */ -class NetworkData +class NetworkData: public ThreadNetifLocator { public: enum @@ -100,14 +101,6 @@ public: */ NetworkData(ThreadNetif &aThreadNetif, bool aLocal); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method clears the network data. * @@ -354,8 +347,6 @@ protected: uint8_t mTlvs[kMaxSize]; ///< The Network Data buffer. uint8_t mLength; ///< The number of valid bytes in @var mTlvs. - ThreadNetif &mNetif; - private: enum { diff --git a/src/core/thread/network_data_leader.cpp b/src/core/thread/network_data_leader.cpp index 480511997..0575d19b9 100644 --- a/src/core/thread/network_data_leader.cpp +++ b/src/core/thread/network_data_leader.cpp @@ -69,19 +69,20 @@ void LeaderBase::Reset(void) mVersion = static_cast(otPlatRandomGet()); mStableVersion = static_cast(otPlatRandomGet()); mLength = 0; - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); } otError LeaderBase::GetContext(const Ip6::Address &aAddress, Lowpan::Context &aContext) { + ThreadNetif &netif = GetNetif(); PrefixTlv *prefix; ContextTlv *contextTlv; aContext.mPrefixLength = 0; - if (PrefixMatch(mNetif.GetMle().GetMeshLocalPrefix(), aAddress.mFields.m8, 64) >= 0) + if (PrefixMatch(netif.GetMle().GetMeshLocalPrefix(), aAddress.mFields.m8, 64) >= 0) { - aContext.mPrefix = mNetif.GetMle().GetMeshLocalPrefix(); + aContext.mPrefix = netif.GetMle().GetMeshLocalPrefix(); aContext.mPrefixLength = 64; aContext.mContextId = 0; aContext.mCompressFlag = true; @@ -130,7 +131,7 @@ otError LeaderBase::GetContext(uint8_t aContextId, Lowpan::Context &aContext) if (aContextId == 0) { - aContext.mPrefix = mNetif.GetMle().GetMeshLocalPrefix(); + aContext.mPrefix = GetNetif().GetMle().GetMeshLocalPrefix(); aContext.mPrefixLength = 64; aContext.mContextId = 0; aContext.mCompressFlag = true; @@ -202,7 +203,7 @@ bool LeaderBase::IsOnMesh(const Ip6::Address &aAddress) PrefixTlv *prefix; bool rval = false; - if (memcmp(aAddress.mFields.m8, mNetif.GetMle().GetMeshLocalPrefix(), 8) == 0) + if (memcmp(aAddress.mFields.m8, GetNetif().GetMle().GetMeshLocalPrefix(), 8) == 0) { ExitNow(rval = true); } @@ -278,6 +279,7 @@ exit: otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &aDestination, uint8_t *aPrefixMatch, uint16_t *aRloc16) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NO_ROUTE; PrefixTlv *prefix; HasRouteTlv *hasRoute; @@ -325,7 +327,7 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &a if (rvalRoute == NULL || entry->GetPreference() > rvalRoute->GetPreference() || (entry->GetPreference() == rvalRoute->GetPreference() && - mNetif.GetMle().GetCost(entry->GetRloc()) < mNetif.GetMle().GetCost(rvalRoute->GetRloc()))) + netif.GetMle().GetCost(entry->GetRloc()) < netif.GetMle().GetCost(rvalRoute->GetRloc()))) { rvalRoute = entry; rval_plen = static_cast(plen); @@ -356,6 +358,7 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, const Ip6::Address &a otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NO_ROUTE; BorderRouterTlv *borderRouter; BorderRouterEntry *entry; @@ -382,9 +385,9 @@ otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) if (route == NULL || entry->GetPreference() > route->GetPreference() || (entry->GetPreference() == route->GetPreference() && - (entry->GetRloc() == mNetif.GetMle().GetRloc16() || - (route->GetRloc() != mNetif.GetMle().GetRloc16() && - mNetif.GetMle().GetCost(entry->GetRloc()) < mNetif.GetMle().GetCost(route->GetRloc()))))) + (entry->GetRloc() == netif.GetMle().GetRloc16() || + (route->GetRloc() != netif.GetMle().GetRloc16() && + netif.GetMle().GetCost(entry->GetRloc()) < netif.GetMle().GetCost(route->GetRloc()))))) { route = entry; } @@ -419,7 +422,7 @@ void LeaderBase::SetNetworkData(uint8_t aVersion, uint8_t aStableVersion, bool a otDumpDebgNetData(GetInstance(), "set network data", mTlvs, mLength); - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); } otError LeaderBase::SetCommissioningData(const uint8_t *aValue, uint8_t aValueLength) @@ -442,7 +445,7 @@ otError LeaderBase::SetCommissioningData(const uint8_t *aValue, uint8_t aValueLe } mVersion++; - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); exit: return error; diff --git a/src/core/thread/network_data_leader_ftd.cpp b/src/core/thread/network_data_leader_ftd.cpp index a32783bf8..e237ee9f7 100644 --- a/src/core/thread/network_data_leader_ftd.cpp +++ b/src/core/thread/network_data_leader_ftd.cpp @@ -40,6 +40,7 @@ #include "network_data_leader.hpp" #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -81,30 +82,36 @@ void Leader::Reset(void) void Leader::Start(void) { - mNetif.GetCoap().AddResource(mServerData); - mNetif.GetCoap().AddResource(mCommissioningDataGet); - mNetif.GetCoap().AddResource(mCommissioningDataSet); + Coap::Coap &coap = GetNetif().GetCoap(); + + coap.AddResource(mServerData); + coap.AddResource(mCommissioningDataGet); + coap.AddResource(mCommissioningDataSet); } void Leader::Stop(void) { - mNetif.GetCoap().RemoveResource(mServerData); - mNetif.GetCoap().RemoveResource(mCommissioningDataGet); - mNetif.GetCoap().RemoveResource(mCommissioningDataSet); + Coap::Coap &coap = GetNetif().GetCoap(); + + coap.RemoveResource(mServerData); + coap.RemoveResource(mCommissioningDataGet); + coap.RemoveResource(mCommissioningDataSet); } void Leader::IncrementVersion(void) { - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + ThreadNetif &netif = GetNetif(); + + if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) { mVersion++; - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + netif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); } } void Leader::IncrementStableVersion(void) { - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) { mStableVersion++; } @@ -137,7 +144,7 @@ void Leader::RemoveBorderRouter(uint16_t aRloc16) mStableVersion++; } - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); exit: return; @@ -172,7 +179,7 @@ void Leader::HandleServerData(Coap::Header &aHeader, Message &aMessage, networkData.GetTlvs(), networkData.GetLength()); } - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, aMessageInfo)); otLogInfoNetData(GetInstance(), "Sent network data registration acknowledgment"); @@ -198,7 +205,7 @@ void Leader::HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, co bool hasValidTlv = false; uint16_t sessionId = 0; - VerifyOrExit(mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, state = MeshCoP::StateTlv::kReject); + VerifyOrExit(GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, state = MeshCoP::StateTlv::kReject); aMessage.Read(offset, length, tlvs); @@ -266,7 +273,7 @@ void Leader::HandleCommissioningSet(Coap::Header &aHeader, Message &aMessage, co exit: - if (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) { SendCommissioningSetResponse(aHeader, aMessageInfo, state); } @@ -309,6 +316,7 @@ void Leader::HandleCommissioningGet(Coap::Header &aHeader, Message &aMessage, co void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, uint8_t *aTlvs, uint8_t aLength) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; Message *message; @@ -319,7 +327,7 @@ void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, co responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); @@ -363,7 +371,7 @@ void Leader::SendCommissioningGetResponse(const Coap::Header &aRequestHeader, co message->SetLength(message->GetLength() - 1); } - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent commissioning dataset get response"); @@ -378,6 +386,7 @@ exit: void Leader::SendCommissioningSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, MeshCoP::StateTlv::State aState) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header responseHeader; Message *message; @@ -386,14 +395,14 @@ void Leader::SendCommissioningSetResponse(const Coap::Header &aRequestHeader, co responseHeader.SetDefaultResponseHeader(aRequestHeader); responseHeader.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), responseHeader)) != NULL, + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), responseHeader)) != NULL, error = OT_ERROR_NO_BUFS); state.Init(); state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP(GetInstance(), "sent commissioning dataset set response"); @@ -585,7 +594,7 @@ otError Leader::RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aT } } - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); exit: return error; @@ -769,7 +778,7 @@ otError Leader::FreeContext(uint8_t aContextId) mContextUsed &= ~(1 << aContextId); mVersion++; mStableVersion++; - mNetif.SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); + GetNetif().SetStateChangedFlags(OT_CHANGED_THREAD_NETDATA); return OT_ERROR_NONE; } @@ -1041,10 +1050,9 @@ otError Leader::RemoveContext(PrefixTlv &aPrefix, uint8_t aContextId) return OT_ERROR_NONE; } -void Leader::HandleTimer(void *aContext) +void Leader::HandleTimer(Timer &aTimer) { - Leader *obj = reinterpret_cast(aContext); - obj->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void Leader::HandleTimer(void) @@ -1074,6 +1082,17 @@ void Leader::HandleTimer(void) } } +Leader &Leader::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + Leader &leader = *static_cast(aContext.GetContext()); +#else + Leader &leader = otGetThreadNetif().GetNetworkDataLeader(); + OT_UNUSED_VARIABLE(aContext); +#endif + return leader; +} + } // namespace NetworkData } // namespace ot diff --git a/src/core/thread/network_data_leader_ftd.hpp b/src/core/thread/network_data_leader_ftd.hpp index 338d0e741..44984838d 100644 --- a/src/core/thread/network_data_leader_ftd.hpp +++ b/src/core/thread/network_data_leader_ftd.hpp @@ -145,7 +145,7 @@ private: const otMessageInfo *aMessageInfo); void HandleServerData(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); otError RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aTlvsLength); @@ -184,6 +184,7 @@ private: uint8_t *aTlvs, uint8_t aLength); void SendCommissioningSetResponse(const Coap::Header &aRequestHeader, const Ip6::MessageInfo &aMessageInfo, MeshCoP::StateTlv::State aState); + static Leader &GetOwner(const Context &aContext); /** * Thread Specification Constants diff --git a/src/core/thread/network_data_local.cpp b/src/core/thread/network_data_local.cpp index ad43e2edc..cac640f32 100644 --- a/src/core/thread/network_data_local.cpp +++ b/src/core/thread/network_data_local.cpp @@ -59,7 +59,7 @@ otError Local::AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, in PrefixTlv *prefixTlv; BorderRouterTlv *brTlv; - VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, mNetif.GetMle().GetMeshLocalPrefix(), + VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, GetNetif().GetMle().GetMeshLocalPrefix(), (aPrefixLength + 7) / 8) < Ip6::Address::kMeshLocalPrefixLength, error = OT_ERROR_INVALID_ARGS); @@ -202,41 +202,47 @@ otError Local::UpdateRloc(PrefixTlv &aPrefix) otError Local::UpdateRloc(HasRouteTlv &aHasRoute) { HasRouteEntry *entry = aHasRoute.GetEntry(0); - entry->SetRloc(mNetif.GetMle().GetRloc16()); + entry->SetRloc(GetNetif().GetMle().GetRloc16()); return OT_ERROR_NONE; } otError Local::UpdateRloc(BorderRouterTlv &aBorderRouter) { BorderRouterEntry *entry = aBorderRouter.GetEntry(0); - entry->SetRloc(mNetif.GetMle().GetRloc16()); + entry->SetRloc(GetNetif().GetMle().GetRloc16()); return OT_ERROR_NONE; } bool Local::IsOnMeshPrefixConsistent(void) { - return (mNetif.GetNetworkDataLeader().ContainsOnMeshPrefixes(*this, mNetif.GetMle().GetRloc16()) && - ContainsOnMeshPrefixes(mNetif.GetNetworkDataLeader(), mNetif.GetMle().GetRloc16())); + ThreadNetif &netif = GetNetif(); + + return (netif.GetNetworkDataLeader().ContainsOnMeshPrefixes(*this, netif.GetMle().GetRloc16()) && + ContainsOnMeshPrefixes(netif.GetNetworkDataLeader(), netif.GetMle().GetRloc16())); } bool Local::IsExternalRouteConsistent(void) { - return (mNetif.GetNetworkDataLeader().ContainsExternalRoutes(*this, mNetif.GetMle().GetRloc16()) && - ContainsExternalRoutes(mNetif.GetNetworkDataLeader(), mNetif.GetMle().GetRloc16())); + ThreadNetif &netif = GetNetif(); + + return (netif.GetNetworkDataLeader().ContainsExternalRoutes(*this, netif.GetMle().GetRloc16()) && + ContainsExternalRoutes(netif.GetNetworkDataLeader(), netif.GetMle().GetRloc16())); } otError Local::SendServerDataNotification(void) { + ThreadNetif &netif = GetNetif(); + Mle::MleRouter &mle = netif.GetMle(); otError error = OT_ERROR_NONE; - uint16_t rloc = mNetif.GetMle().GetRloc16(); + uint16_t rloc = mle.GetRloc16(); #if OPENTHREAD_FTD // Don't send this Server Data Notification if the device is going to upgrade to Router - if ((mNetif.GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) != 0 && - (mNetif.GetMle().IsRouterRoleEnabled()) && - (mNetif.GetMle().GetRole() < OT_DEVICE_ROLE_ROUTER) && - (mNetif.GetMle().GetActiveRouterCount() < mNetif.GetMle().GetRouterUpgradeThreshold())) + if ((mle.GetDeviceMode() & Mle::ModeTlv::kModeFFD) != 0 && + (mle.IsRouterRoleEnabled()) && + (mle.GetRole() < OT_DEVICE_ROLE_ROUTER) && + (mle.GetActiveRouterCount() < mle.GetRouterUpgradeThreshold())) { ExitNow(error = OT_ERROR_INVALID_STATE); } diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 35ab09fba..42f91408a 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -62,23 +62,18 @@ namespace ot { namespace NetworkDiagnostic { NetworkDiagnostic::NetworkDiagnostic(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mDiagnosticGetRequest(OT_URI_PATH_DIAGNOSTIC_GET_REQUEST, &NetworkDiagnostic::HandleDiagnosticGetRequest, this), mDiagnosticGetQuery(OT_URI_PATH_DIAGNOSTIC_GET_QUERY, &NetworkDiagnostic::HandleDiagnosticGetQuery, this), mDiagnosticGetAnswer(OT_URI_PATH_DIAGNOSTIC_GET_ANSWER, &NetworkDiagnostic::HandleDiagnosticGetAnswer, this), mDiagnosticReset(OT_URI_PATH_DIAGNOSTIC_RESET, &NetworkDiagnostic::HandleDiagnosticReset, this), - mNetif(aThreadNetif), mReceiveDiagnosticGetCallback(NULL), mReceiveDiagnosticGetCallbackContext(NULL) { - mNetif.GetCoap().AddResource(mDiagnosticGetRequest); - mNetif.GetCoap().AddResource(mDiagnosticGetQuery); - mNetif.GetCoap().AddResource(mDiagnosticGetAnswer); - mNetif.GetCoap().AddResource(mDiagnosticReset); -} - -otInstance *NetworkDiagnostic::GetInstance(void) -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mDiagnosticGetRequest); + aThreadNetif.GetCoap().AddResource(mDiagnosticGetQuery); + aThreadNetif.GetCoap().AddResource(mDiagnosticGetAnswer); + aThreadNetif.GetCoap().AddResource(mDiagnosticReset); } void NetworkDiagnostic::SetReceiveDiagnosticGetCallback(otReceiveDiagnosticGetCallback aCallback, @@ -91,6 +86,7 @@ void NetworkDiagnostic::SetReceiveDiagnosticGetCallback(otReceiveDiagnosticGetCa otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount) { + ThreadNetif &netif = GetNetif(); otError error; Message *message; Coap::Header header; @@ -116,16 +112,16 @@ otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, c header.SetPayloadMarker(); } - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Append(aTlvTypes, aCount)); messageInfo.SetPeerAddr(aDestination); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, handler, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, handler, this)); otLogInfoNetDiag(GetInstance(), "Sent diagnostic get"); @@ -187,7 +183,7 @@ void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Header &aHeader, Message mReceiveDiagnosticGetCallback(&aMessage, &aMessageInfo, mReceiveDiagnosticGetCallbackContext); } - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, aMessageInfo)); otLogInfoNetDiag(GetInstance(), "Sent diagnostic answer acknowledgment"); @@ -197,13 +193,14 @@ exit: otError NetworkDiagnostic::AppendIp6AddressList(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6AddressListTlv tlv; uint8_t count = 0; tlv.Init(); - for (const Ip6::NetifUnicastAddress *addr = mNetif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) { count++; } @@ -211,7 +208,7 @@ otError NetworkDiagnostic::AppendIp6AddressList(Message &aMessage) tlv.SetLength(count * sizeof(Ip6::Address)); SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); - for (const Ip6::NetifUnicastAddress *addr = mNetif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) { SuccessOrExit(error = aMessage.Append(&addr->GetAddress(), sizeof(Ip6::Address))); } @@ -223,11 +220,12 @@ exit: otError NetworkDiagnostic::AppendChildTable(Message &aMessage) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; uint8_t count = 0; uint8_t timeout = 0; uint8_t numChildren; - const Child *children = mNetif.GetMle().GetChildren(&numChildren); + const Child *children = netif.GetMle().GetChildren(&numChildren); ChildTableTlv tlv; ChildTableEntry entry; @@ -255,7 +253,7 @@ otError NetworkDiagnostic::AppendChildTable(Message &aMessage) entry.SetReserved(0); entry.SetTimeout(timeout + 4); - entry.SetChildId(mNetif.GetMle().GetChildId(children[i].GetRloc16())); + entry.SetChildId(netif.GetMle().GetChildId(children[i].GetRloc16())); entry.SetMode(children[i].GetDeviceMode()); SuccessOrExit(error = aMessage.Append(&entry, sizeof(ChildTableEntry))); @@ -270,6 +268,7 @@ exit: otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aResponse, NetworkDiagnosticTlv &aNetworkDiagnosticTlv) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; uint16_t offset = 0; uint8_t type; @@ -288,7 +287,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { ExtMacAddressTlv tlv; tlv.Init(); - tlv.SetMacAddr(*mNetif.GetMac().GetExtAddress()); + tlv.SetMacAddr(*netif.GetMac().GetExtAddress()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -297,7 +296,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { Address16Tlv tlv; tlv.Init(); - tlv.SetRloc16(mNetif.GetMle().GetRloc16()); + tlv.SetRloc16(netif.GetMle().GetRloc16()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -306,18 +305,18 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { ModeTlv tlv; tlv.Init(); - tlv.SetMode(mNetif.GetMle().GetDeviceMode()); + tlv.SetMode(netif.GetMle().GetDeviceMode()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } case NetworkDiagnosticTlv::kTimeout: { - if ((mNetif.GetMle().GetDeviceMode() & ModeTlv::kModeRxOnWhenIdle) == 0) + if ((netif.GetMle().GetDeviceMode() & ModeTlv::kModeRxOnWhenIdle) == 0) { TimeoutTlv tlv; tlv.Init(); - tlv.SetTimeout(mNetif.GetMle().GetTimeout()); + tlv.SetTimeout(netif.GetMle().GetTimeout()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); } @@ -328,7 +327,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { ConnectivityTlv tlv; tlv.Init(); - mNetif.GetMle().FillConnectivityTlv(*reinterpret_cast(&tlv)); + netif.GetMle().FillConnectivityTlv(*reinterpret_cast(&tlv)); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -337,7 +336,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { RouteTlv tlv; tlv.Init(); - mNetif.GetMle().FillRouteTlv(*reinterpret_cast(&tlv)); + netif.GetMle().FillRouteTlv(*reinterpret_cast(&tlv)); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; } @@ -345,7 +344,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon case NetworkDiagnosticTlv::kLeaderData: { LeaderDataTlv tlv; - memcpy(&tlv, &mNetif.GetMle().GetLeaderDataTlv(), sizeof(tlv)); + memcpy(&tlv, &netif.GetMle().GetLeaderDataTlv(), sizeof(tlv)); tlv.Init(); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; @@ -355,7 +354,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon { NetworkDataTlv tlv; tlv.Init(); - mNetif.GetMle().FillNetworkDataTlv((*reinterpret_cast(&tlv)), true); + netif.GetMle().FillNetworkDataTlv((*reinterpret_cast(&tlv)), true); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; } @@ -371,7 +370,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message &aRequest, Message &aRespon MacCountersTlv tlv; memset(&tlv, 0, sizeof(tlv)); tlv.Init(); - mNetif.GetMac().FillMacCountersTlv(tlv); + netif.GetMac().FillMacCountersTlv(tlv); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; } @@ -434,6 +433,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(void *aContext, otCoapHeader *a void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -454,7 +454,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Header &aHeader, Message // DIAG_GET.qry may be sent as a confirmable message. if (aHeader.GetType() == OT_COAP_TYPE_CONFIRMABLE) { - if (mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) + if (netif.GetCoap().SendEmptyAck(aHeader, aMessageInfo) == OT_ERROR_NONE) { otLogInfoNetDiag(GetInstance(), "Sent diagnostic get query acknowledgment"); } @@ -469,16 +469,16 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Header &aHeader, Message header.SetPayloadMarker(); } - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); messageInfo.SetPeerAddr(aMessageInfo.GetPeerAddr()); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); SuccessOrExit(error = FillRequestedTlvs(aMessage, *message, networkDiagnosticTlv)); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo, NULL, this)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, NULL, this)); otLogInfoNetDiag(GetInstance(), "Sent diagnostic get answer"); @@ -501,6 +501,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(void *aContext, otCoapHeader void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Message *message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -522,7 +523,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Header &aHeader, Messag header.SetDefaultResponseHeader(aHeader); header.SetPayloadMarker(); - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = FillRequestedTlvs(aMessage, *message, networkDiagnosticTlv)); @@ -532,7 +533,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Header &aHeader, Messag message->SetLength(header.GetLength() - 1); } - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoNetDiag(GetInstance(), "Sent diagnostic get response"); @@ -547,6 +548,7 @@ exit: otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount) { + ThreadNetif &netif = GetNetif(); otError error; Message *message; Coap::Header header; @@ -561,16 +563,16 @@ otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, header.SetPayloadMarker(); } - VerifyOrExit((message = mNetif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = netif.GetCoap().NewMessage(header)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->Append(aTlvTypes, aCount)); messageInfo.SetPeerAddr(aDestination); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(mNetif.GetInterfaceId()); + messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoNetDiag(GetInstance(), "Sent network diagnostic reset"); @@ -595,6 +597,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(void *aContext, otCoapHeader *aHea void NetworkDiagnostic::HandleDiagnosticReset(Coap::Header &aHeader, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { + ThreadNetif &netif = GetNetif(); uint16_t offset = 0; uint8_t type; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -620,7 +623,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Header &aHeader, Message &aM switch (type) { case NetworkDiagnosticTlv::kMacCounters: - mNetif.GetMac().ResetCounters(); + netif.GetMac().ResetCounters(); otLogInfoNetDiag(GetInstance(), "Received diagnostic reset type kMacCounters(9)"); break; @@ -630,7 +633,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Header &aHeader, Message &aM } } - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); + SuccessOrExit(netif.GetCoap().SendEmptyAck(aHeader, aMessageInfo)); otLogInfoNetDiag(GetInstance(), "Sent diagnostic reset acknowledgment"); diff --git a/src/core/thread/network_diagnostic.hpp b/src/core/thread/network_diagnostic.hpp index 9785055ca..ed5a64d0a 100644 --- a/src/core/thread/network_diagnostic.hpp +++ b/src/core/thread/network_diagnostic.hpp @@ -38,12 +38,11 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "net/udp6.hpp" namespace ot { -class ThreadNetif; - namespace NetworkDiagnostic { class Ip6AddressListTlv; @@ -63,7 +62,7 @@ class NetworkDiagnosticTlv; * This class implements the Network Diagnostic processing. * */ -class NetworkDiagnostic +class NetworkDiagnostic: public ThreadNetifLocator { public: /** @@ -72,14 +71,6 @@ public: */ explicit NetworkDiagnostic(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(); - /** * This method registers a callback to provide received raw DIAG_GET.rsp or an DIAG_GET.ans payload. * @@ -143,8 +134,6 @@ private: Coap::Resource mDiagnosticGetAnswer; Coap::Resource mDiagnosticReset; - ThreadNetif &mNetif; - otReceiveDiagnosticGetCallback mReceiveDiagnosticGetCallback; void *mReceiveDiagnosticGetCallbackContext; }; diff --git a/src/core/thread/panid_query_server.cpp b/src/core/thread/panid_query_server.cpp index dc0d237dc..aa33583be 100644 --- a/src/core/thread/panid_query_server.cpp +++ b/src/core/thread/panid_query_server.cpp @@ -39,6 +39,7 @@ #include +#include "openthread-instance.h" #include "coap/coap_header.hpp" #include "common/code_utils.hpp" #include "common/debug.hpp" @@ -51,18 +52,13 @@ namespace ot { PanIdQueryServer::PanIdQueryServer(ThreadNetif &aThreadNetif) : + ThreadNetifLocator(aThreadNetif), mChannelMask(0), mPanId(Mac::kPanIdBroadcast), mTimer(aThreadNetif.GetIp6().mTimerScheduler, &PanIdQueryServer::HandleTimer, this), - mPanIdQuery(OT_URI_PATH_PANID_QUERY, &PanIdQueryServer::HandleQuery, this), - mNetif(aThreadNetif) + mPanIdQuery(OT_URI_PATH_PANID_QUERY, &PanIdQueryServer::HandleQuery, this) { - mNetif.GetCoap().AddResource(mPanIdQuery); -} - -otInstance *PanIdQueryServer::GetInstance() -{ - return mNetif.GetInstance(); + aThreadNetif.GetCoap().AddResource(mPanIdQuery); } void PanIdQueryServer::HandleQuery(void *aContext, otCoapHeader *aHeader, otMessage *aMessage, @@ -94,7 +90,7 @@ void PanIdQueryServer::HandleQuery(Coap::Header &aHeader, Message &aMessage, con if (aHeader.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(mNetif.GetCoap().SendEmptyAck(aHeader, responseInfo)); + SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aHeader, responseInfo)); otLogInfoMeshCoP(GetInstance(), "sent panid query response"); } @@ -128,6 +124,7 @@ void PanIdQueryServer::HandleScanResult(Mac::Frame *aFrame) otError PanIdQueryServer::SendConflict(void) { + ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Header header; MeshCoP::ChannelMask0Tlv channelMask; @@ -140,7 +137,7 @@ otError PanIdQueryServer::SendConflict(void) header.AppendUriPathOptions(OT_URI_PATH_PANID_CONFLICT); header.SetPayloadMarker(); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(mNetif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap(), header)) != NULL, error = OT_ERROR_NO_BUFS); channelMask.Init(); channelMask.SetMask(mChannelMask); @@ -150,10 +147,10 @@ otError PanIdQueryServer::SendConflict(void) panId.SetPanId(mPanId); SuccessOrExit(error = message->Append(&panId, sizeof(panId))); - messageInfo.SetSockAddr(mNetif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); messageInfo.SetPeerAddr(mCommissioner); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = mNetif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); otLogInfoMeshCoP(GetInstance(), "sent panid conflict"); @@ -167,15 +164,26 @@ exit: return error; } -void PanIdQueryServer::HandleTimer(void *aContext) +void PanIdQueryServer::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void PanIdQueryServer::HandleTimer(void) { - mNetif.GetMac().ActiveScan(mChannelMask, 0, HandleScanResult, this); + GetNetif().GetMac().ActiveScan(mChannelMask, 0, HandleScanResult, this); mChannelMask = 0; } +PanIdQueryServer &PanIdQueryServer::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + PanIdQueryServer &server = *static_cast(aContext.GetContext()); +#else + PanIdQueryServer &server = otGetThreadNetif().GetPanIdQueryServer(); + OT_UNUSED_VARIABLE(aContext); +#endif + return server; +} + } // namespace ot diff --git a/src/core/thread/panid_query_server.hpp b/src/core/thread/panid_query_server.hpp index 44b114dda..622f7f86b 100644 --- a/src/core/thread/panid_query_server.hpp +++ b/src/core/thread/panid_query_server.hpp @@ -38,6 +38,7 @@ #include "openthread-core-config.h" #include "coap/coap.hpp" +#include "common/locator.hpp" #include "common/timer.hpp" #include "net/ip6_address.hpp" #include "net/udp6.hpp" @@ -54,7 +55,7 @@ class ThreadTargetTlv; * This class implements handling PANID Query Requests. * */ -class PanIdQueryServer +class PanIdQueryServer: public ThreadNetifLocator { public: /** @@ -63,14 +64,6 @@ public: */ PanIdQueryServer(ThreadNetif &aThreadNetif); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(); - private: enum { @@ -83,13 +76,15 @@ private: static void HandleScanResult(void *aContext, Mac::Frame *aFrame); void HandleScanResult(Mac::Frame *aFrame); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); static void HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo); otError SendConflict(void); + static PanIdQueryServer &GetOwner(const Context &aContext); + Ip6::Address mCommissioner; uint32_t mChannelMask; uint16_t mPanId; @@ -97,8 +92,6 @@ private: Timer mTimer; Coap::Resource mPanIdQuery; - - ThreadNetif &mNetif; }; /** diff --git a/src/core/thread/src_match_controller.cpp b/src/core/thread/src_match_controller.cpp index d4a15f1ce..e56c87340 100644 --- a/src/core/thread/src_match_controller.cpp +++ b/src/core/thread/src_match_controller.cpp @@ -46,17 +46,12 @@ namespace ot { SourceMatchController::SourceMatchController(MeshForwarder &aMeshForwarder) : - mMeshForwarder(aMeshForwarder), + MeshForwarderLocator(aMeshForwarder), mEnabled(false) { ClearTable(); } -otInstance *SourceMatchController::GetInstance(void) -{ - return mMeshForwarder.GetInstance(); -} - void SourceMatchController::IncrementMessageCount(Child &aChild) { if (aChild.GetIndirectMessageCount() == 0) @@ -227,7 +222,7 @@ otError SourceMatchController::AddPendingEntries(void) uint8_t numChildren; Child *child; - child = mMeshForwarder.GetNetif().GetMle().GetChildren(&numChildren); + child = GetMeshForwarder().GetNetif().GetMle().GetChildren(&numChildren); for (uint8_t i = 0; i < numChildren; i++, child++) { diff --git a/src/core/thread/src_match_controller.hpp b/src/core/thread/src_match_controller.hpp index 5c9763fa7..d122d809c 100644 --- a/src/core/thread/src_match_controller.hpp +++ b/src/core/thread/src_match_controller.hpp @@ -37,12 +37,11 @@ #include #include "openthread-core-config.h" +#include "common/locator.hpp" #include "thread/topology.hpp" namespace ot { -class MeshForwarder; - /** * @addtogroup core-source-match-controller * @@ -65,7 +64,7 @@ class MeshForwarder; * address or an extended/long address can be added to the source address match table. * */ -class SourceMatchController +class SourceMatchController: public MeshForwarderLocator { public: /** @@ -76,14 +75,6 @@ public: */ explicit SourceMatchController(MeshForwarder &aMeshForwarder); - /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); - /** * This method returns the current state of source address matching. * @@ -191,7 +182,6 @@ private: */ otError AddPendingEntries(void); - MeshForwarder &mMeshForwarder; bool mEnabled; }; diff --git a/src/core/thread/thread_netif.cpp b/src/core/thread/thread_netif.cpp index d314964c3..08c91aae9 100644 --- a/src/core/thread/thread_netif.cpp +++ b/src/core/thread/thread_netif.cpp @@ -121,7 +121,7 @@ otError ThreadNetif::Up(void) { if (!mIsUp) { - mIp6.AddNetif(*this); + GetIp6().AddNetif(*this); mMeshForwarder.Start(); mCoap.Start(kCoapUdpPort); #if OPENTHREAD_ENABLE_DNS_CLIENT @@ -144,7 +144,7 @@ otError ThreadNetif::Down(void) mChildSupervisor.Stop(); mMleRouter.Disable(); mMeshForwarder.Stop(); - mIp6.RemoveNetif(*this); + GetIp6().RemoveNetif(*this); RemoveAllExternalUnicastAddresses(); UnsubscribeAllExternalMulticastAddresses(); mIsUp = false; @@ -199,9 +199,4 @@ exit: return error; } -otInstance *ThreadNetif::GetInstance(void) -{ - return otInstanceFromThreadNetif(this); -} - } // namespace ot diff --git a/src/core/thread/thread_netif.hpp b/src/core/thread/thread_netif.hpp index ca8a04800..87b6211c2 100644 --- a/src/core/thread/thread_netif.hpp +++ b/src/core/thread/thread_netif.hpp @@ -397,12 +397,20 @@ public: Utils::SupervisionListener &GetSupervisionListener(void) { return mSupervisionListener; } /** - * This method returns the pointer to the parent otInstance structure. - * - * @returns The pointer to the parent otInstance structure. - * - */ - otInstance *GetInstance(void); + * This method returns a reference to the energy scan server object. + * + * @returns A reference to the energy scan server object. + * + */ + EnergyScanServer &GetEnergyScanServer(void) { return mEnergyScan; } + + /** + * This method returns a reference to the PAN ID query server object. + * + * @returns A reference to the PAN ID query server object. + * + */ + PanIdQueryServer &GetPanIdQueryServer(void) { return mPanIdQuery; } private: static otError TmfFilter(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo, void *aContext); diff --git a/src/core/utils/child_supervision.cpp b/src/core/utils/child_supervision.cpp index 434b9d13b..62f88dccd 100644 --- a/src/core/utils/child_supervision.cpp +++ b/src/core/utils/child_supervision.cpp @@ -37,6 +37,8 @@ #include +#include "openthread-core-config.h" +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "common/logging.hpp" #include "thread/thread_netif.hpp" @@ -49,7 +51,7 @@ namespace Utils { #if OPENTHREAD_FTD ChildSupervisor::ChildSupervisor(ThreadNetif &aThreadNetif) : - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mTimer(aThreadNetif.GetIp6().mTimerScheduler, &ChildSupervisor::HandleTimer, this), mSupervisionInterval(kDefaultSupervisionInterval) { @@ -85,7 +87,7 @@ Child *ChildSupervisor::GetDestination(const Message &aMessage) const VerifyOrExit(aMessage.GetType() == Message::kTypeSupervision); aMessage.Read(0, sizeof(childIndex), &childIndex); - child = mNetif.GetMle().GetChildren(&numChildren); + child = GetNetif().GetMle().GetChildren(&numChildren); VerifyOrExit(childIndex < numChildren, child = NULL); child += childIndex; @@ -95,13 +97,14 @@ exit: void ChildSupervisor::SendMessage(Child &aChild) { + ThreadNetif &netif = GetNetif(); Message *message = NULL; otError error = OT_ERROR_NONE; uint8_t childIndex; VerifyOrExit(aChild.GetIndirectMessageCount() == 0); - message = mNetif.GetIp6().mMessagePool.New(Message::kTypeSupervision, sizeof(uint8_t)); + message = netif.GetIp6().mMessagePool.New(Message::kTypeSupervision, sizeof(uint8_t)); VerifyOrExit(message != NULL); // Supervision message is an empty payload 15.4 data frame. @@ -109,10 +112,10 @@ void ChildSupervisor::SendMessage(Child &aChild) // the destination of the message to be later retrieved using // `ChildSupervisor::GetDestination(message)`. - childIndex = mNetif.GetMle().GetChildIndex(aChild); + childIndex = netif.GetMle().GetChildIndex(aChild); SuccessOrExit(error = message->Append(&childIndex, sizeof(childIndex))); - SuccessOrExit(error = mNetif.SendMessage(*message)); + SuccessOrExit(error = netif.SendMessage(*message)); message = NULL; exit: @@ -128,9 +131,9 @@ void ChildSupervisor::UpdateOnSend(Child &aChild) aChild.ResetSecondsSinceLastSupervision(); } -void ChildSupervisor::HandleTimer(void *aContext) +void ChildSupervisor::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void ChildSupervisor::HandleTimer(void) @@ -140,7 +143,7 @@ void ChildSupervisor::HandleTimer(void) VerifyOrExit(mSupervisionInterval != 0); - child = mNetif.GetMle().GetChildren(&numChildren); + child = GetNetif().GetMle().GetChildren(&numChildren); for (uint8_t i = 0; i < numChildren; i++, child++) { @@ -163,10 +166,21 @@ exit: return; } +ChildSupervisor &ChildSupervisor::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + ChildSupervisor &supervisor = *static_cast(aContext.GetContext()); +#else + ChildSupervisor &supervisor = otGetThreadNetif().GetChildSupervisor(); + OT_UNUSED_VARIABLE(aContext); +#endif + return supervisor; +} + #endif // #if OPENTHREAD_FTD SupervisionListener::SupervisionListener(ThreadNetif &aThreadNetif) : - mNetif(aThreadNetif), + ThreadNetifLocator(aThreadNetif), mTimer(aThreadNetif.GetIp6().mTimerScheduler, &SupervisionListener::HandleTimer, this), mTimeout(0) { @@ -194,10 +208,12 @@ void SupervisionListener::SetTimeout(uint16_t aTimeout) void SupervisionListener::UpdateOnReceive(const Mac::Address &aSourceAddress, bool aIsSecure) { + ThreadNetif &netif = GetNetif(); + // If listener is enabled and device is a child and it received a secure frame from its parent, restart the timer. - VerifyOrExit(mTimer.IsRunning() && aIsSecure && (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && - (mNetif.GetMle().GetNeighbor(aSourceAddress) == mNetif.GetMle().GetParent())); + VerifyOrExit(mTimer.IsRunning() && aIsSecure && (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && + (netif.GetMle().GetNeighbor(aSourceAddress) == netif.GetMle().GetParent())); RestartTimer(); @@ -207,10 +223,12 @@ exit: void SupervisionListener::RestartTimer(void) { + ThreadNetif &netif = GetNetif(); + // Restart the timer, if the timeout value is non-zero and the device is a sleepy child. - if ((mTimeout != 0) && (mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && - (mNetif.GetMeshForwarder().GetRxOnWhenIdle() == false)) + if ((mTimeout != 0) && (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && + (netif.GetMeshForwarder().GetRxOnWhenIdle() == false)) { mTimer.Start(Timer::SecToMsec(mTimeout)); } @@ -220,24 +238,37 @@ void SupervisionListener::RestartTimer(void) } } -void SupervisionListener::HandleTimer(void *aContext) +void SupervisionListener::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void SupervisionListener::HandleTimer(void) { - VerifyOrExit((mNetif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && - (mNetif.GetMeshForwarder().GetRxOnWhenIdle() == false)); + ThreadNetif &netif = GetNetif(); - otLogWarnMle(mNetif.GetInstance(), "Supervision timeout. No frame from parent in %d sec", mTimeout); + VerifyOrExit((netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && + (netif.GetMeshForwarder().GetRxOnWhenIdle() == false)); - mNetif.GetMle().SendChildUpdateRequest(); + otLogWarnMle(netif.GetInstance(), "Supervision timeout. No frame from parent in %d sec", mTimeout); + + netif.GetMle().SendChildUpdateRequest(); exit: RestartTimer(); } +SupervisionListener &SupervisionListener::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + SupervisionListener &listener = *static_cast(aContext.GetContext()); +#else + SupervisionListener &listener = otGetThreadNetif().GetSupervisionListener(); + OT_UNUSED_VARIABLE(aContext); +#endif + return listener; +} + #endif // #if OPENTHREAD_ENABLE_CHILD_SUPERVISION } // namespace Utils diff --git a/src/core/utils/child_supervision.hpp b/src/core/utils/child_supervision.hpp index 4ea7f89e7..22c2dd158 100644 --- a/src/core/utils/child_supervision.hpp +++ b/src/core/utils/child_supervision.hpp @@ -37,6 +37,8 @@ #include +#include "openthread-core-config.h" +#include "common/locator.hpp" #include "common/message.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" @@ -85,7 +87,7 @@ namespace Utils { * This class implements a child supervisor. * */ -class ChildSupervisor +class ChildSupervisor: public ThreadNetifLocator { public: /** @@ -154,10 +156,10 @@ private: }; void SendMessage(Child &aChild); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); + static ChildSupervisor &GetOwner(const Context &aContext); - ThreadNetif &mNetif; Timer mTimer; uint16_t mSupervisionInterval; }; @@ -184,7 +186,7 @@ public: * This class implements a child supervision listener. * */ -class SupervisionListener +class SupervisionListener: public ThreadNetifLocator { public: /** @@ -246,10 +248,10 @@ private: }; void RestartTimer(void); - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); + static SupervisionListener &GetOwner(const Context &aContext); - ThreadNetif &mNetif; Timer mTimer; uint16_t mTimeout; }; diff --git a/src/core/utils/jam_detector.cpp b/src/core/utils/jam_detector.cpp index 3099eedf6..6eda86749 100644 --- a/src/core/utils/jam_detector.cpp +++ b/src/core/utils/jam_detector.cpp @@ -38,6 +38,7 @@ #include #include +#include "openthread-instance.h" #include "common/code_utils.hpp" #include "thread/thread_netif.hpp" @@ -47,7 +48,7 @@ namespace ot { namespace Utils { JamDetector::JamDetector(ThreadNetif &aNetif) : - mNetif(aNetif), + ThreadNetifLocator(aNetif), mHandler(NULL), mContext(NULL), mRssiThreshold(kDefaultRssiThreshold), @@ -135,9 +136,9 @@ exit: return error; } -void JamDetector::HandleTimer(void *aContext) +void JamDetector::HandleTimer(Timer &aTimer) { - static_cast(aContext)->HandleTimer(); + GetOwner(aTimer).HandleTimer(); } void JamDetector::HandleTimer(void) @@ -147,7 +148,7 @@ void JamDetector::HandleTimer(void) VerifyOrExit(mEnabled); - rssi = otPlatRadioGetRssi(mNetif.GetInstance()); + rssi = otPlatRadioGetRssi(GetNetif().GetInstance()); // If the RSSI is valid, check if it exceeds the threshold // and try to update the history bit map @@ -239,6 +240,17 @@ void JamDetector::UpdateJamState(void) } } +JamDetector &JamDetector::GetOwner(const Context &aContext) +{ +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + JamDetector &detector = *static_cast(aContext.GetContext()); +#else + JamDetector &detector = otGetThreadNetif().GetJamDetector(); + OT_UNUSED_VARIABLE(aContext); +#endif + return detector; +} + } // namespace Utils } // namespace ot diff --git a/src/core/utils/jam_detector.hpp b/src/core/utils/jam_detector.hpp index 6c7f42c60..ca314e3b8 100644 --- a/src/core/utils/jam_detector.hpp +++ b/src/core/utils/jam_detector.hpp @@ -36,6 +36,7 @@ #include +#include "common/locator.hpp" #include "common/timer.hpp" #include "utils/wrap_stdint.h" @@ -45,7 +46,7 @@ class ThreadNetif; namespace Utils { -class JamDetector +class JamDetector: public ThreadNetifLocator { public: @@ -173,10 +174,11 @@ public: uint64_t GetHistoryBitmap(void) const { return mHistoryBitmap; } private: - static void HandleTimer(void *aContext); + static void HandleTimer(Timer &aTimer); void HandleTimer(void); void UpdateHistory(bool aThresholdExceeded); void UpdateJamState(void); + static JamDetector &GetOwner(const Context &aContext); private: enum @@ -191,7 +193,6 @@ private: }; - ThreadNetif &mNetif; Handler mHandler; // Handler/callback to inform about jamming state void *mContext; // Context for handler/callback int8_t mRssiThreshold; // RSSI threshold for jam detection diff --git a/src/ncp/ncp_base.cpp b/src/ncp/ncp_base.cpp index cb2b3f206..fa32476e7 100644 --- a/src/ncp/ncp_base.cpp +++ b/src/ncp/ncp_base.cpp @@ -1192,10 +1192,10 @@ void NcpBase::HandleNetifStateChanged(uint32_t aFlags, void *aContext) obj->mUpdateChangedPropsTask.Post(); } -void NcpBase::UpdateChangedProps(void *aContext) +void NcpBase::UpdateChangedProps(Tasklet &aTasklet) { - NcpBase *obj = static_cast(aContext); - obj->UpdateChangedProps(); + OT_UNUSED_VARIABLE(aTasklet); + GetNcpInstance()->UpdateChangedProps(); } void NcpBase::UpdateChangedProps(void) diff --git a/src/ncp/ncp_base.hpp b/src/ncp/ncp_base.hpp index f541d0b62..7ec1de872 100644 --- a/src/ncp/ncp_base.hpp +++ b/src/ncp/ncp_base.hpp @@ -210,7 +210,7 @@ private: static void HandleJamStateChange_Jump(bool aJamState, void *aContext); void HandleJamStateChange(bool aJamState); - static void UpdateChangedProps(void *aContext); + static void UpdateChangedProps(Tasklet &aTasklet); void UpdateChangedProps(void); static void SendDoneTask(void *aContext); diff --git a/src/ncp/ncp_spi.cpp b/src/ncp/ncp_spi.cpp index f1f296bca..e8ee8e4bf 100644 --- a/src/ncp/ncp_spi.cpp +++ b/src/ncp/ncp_spi.cpp @@ -311,9 +311,10 @@ exit: return errorCode; } -void NcpSpi::PrepareTxFrame(void *aContext) +void NcpSpi::PrepareTxFrame(Tasklet &aTasklet) { - static_cast(aContext)->PrepareTxFrame(); + OT_UNUSED_VARIABLE(aTasklet); + static_cast(GetNcpInstance())->PrepareTxFrame(); } void NcpSpi::PrepareTxFrame(void) diff --git a/src/ncp/ncp_spi.hpp b/src/ncp/ncp_spi.hpp index 56fef5f24..a80519e31 100644 --- a/src/ncp/ncp_spi.hpp +++ b/src/ncp/ncp_spi.hpp @@ -84,7 +84,7 @@ private: static void HandleFrameAddedToTxBuffer(void *aContext, NcpFrameBuffer::FrameTag aFrameTag, NcpFrameBuffer *aNcpFrameBuffer); - static void PrepareTxFrame(void *context); + static void PrepareTxFrame(Tasklet &aTasklet); void PrepareTxFrame(void); void HandleRxFrame(void); diff --git a/src/ncp/ncp_uart.cpp b/src/ncp/ncp_uart.cpp index b99190b20..de1be8dee 100644 --- a/src/ncp/ncp_uart.cpp +++ b/src/ncp/ncp_uart.cpp @@ -122,11 +122,10 @@ void NcpUart::HandleFrameAddedToNcpBuffer(void) } } -void NcpUart::EncodeAndSendToUart(void *aContext) +void NcpUart::EncodeAndSendToUart(Tasklet &aTasklet) { - NcpUart *obj = static_cast(aContext); - - obj->EncodeAndSendToUart(); + OT_UNUSED_VARIABLE(aTasklet); + static_cast(GetNcpInstance())->EncodeAndSendToUart(); } // This method encodes a frame from the tx frame buffer (mTxFrameBuffer) into the uart buffer and sends it over uart. diff --git a/src/ncp/ncp_uart.hpp b/src/ncp/ncp_uart.hpp index 50b90a403..eb1fa4d16 100644 --- a/src/ncp/ncp_uart.hpp +++ b/src/ncp/ncp_uart.hpp @@ -101,7 +101,7 @@ private: void TxFrameBufferHasData(void); void HandleFrameAddedToNcpBuffer(void); - static void EncodeAndSendToUart(void *aContext); + static void EncodeAndSendToUart(Tasklet &aTasklet); static void HandleFrame(void *context, uint8_t *aBuf, uint16_t aBufLength); static void HandleError(void *context, otError aError, uint8_t *aBuf, uint16_t aBufLength); static void HandleFrameAddedToNcpBuffer(void *aContext, NcpFrameBuffer::FrameTag aTag, diff --git a/tests/unit/test_aes.cpp b/tests/unit/test_aes.cpp index 8bb8b723b..a9f4d6f76 100644 --- a/tests/unit/test_aes.cpp +++ b/tests/unit/test_aes.cpp @@ -26,20 +26,16 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - +#include #include #include "common/debug.hpp" #include "crypto/aes_ccm.hpp" -#include "crypto/mbedtls.hpp" +#include "utils/wrap_string.h" +#include "test_platform.h" #include "test_util.h" -#ifndef OPENTHREAD_MULTIPLE_INSTANCE -static ot::Crypto::MbedTls mbedtls; -#endif - /** * Verifies test vectors from IEEE 802.15.4-2006 Annex C Section C.2.1 */ @@ -78,6 +74,7 @@ void TestMacBeaconFrame(void) 0xB5, 0x53 }; + otInstance *instance = testInitInstance(); ot::Crypto::AesCcm aesCcm; uint32_t headerLength = sizeof(test) - 8; uint32_t payloadLength = 0; @@ -89,6 +86,8 @@ void TestMacBeaconFrame(void) 0x00, 0x00, 0x00, 0x05, 0x02, }; + VerifyOrQuit(instance != NULL, "Null OpenThread instance"); + aesCcm.SetKey(key, sizeof(key)); aesCcm.Init(headerLength, payloadLength, tagLength, nonce, sizeof(nonce)); aesCcm.Header(test, headerLength); @@ -103,6 +102,8 @@ void TestMacBeaconFrame(void) VerifyOrQuit(memcmp(test, decrypted, sizeof(decrypted)) == 0, "TestMacBeaconFrame decrypt failed"); + + testFreeInstance(instance); } /** diff --git a/tests/unit/test_diag.cpp b/tests/unit/test_diag.cpp index 807f80d49..e114aa7e6 100644 --- a/tests/unit/test_diag.cpp +++ b/tests/unit/test_diag.cpp @@ -26,12 +26,12 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - #include #include #include +#include "utils/wrap_string.h" + #include "test_util.h" extern "C" void otTaskletsSignalPending(otInstance *) diff --git a/tests/unit/test_fuzz.cpp b/tests/unit/test_fuzz.cpp index a8027b7ef..a94ab72f3 100644 --- a/tests/unit/test_fuzz.cpp +++ b/tests/unit/test_fuzz.cpp @@ -109,7 +109,7 @@ void TestFuzz(uint32_t aSeconds) Log("Initialized seed = 0x%X", seed); #endif -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES size_t otInstanceBufferLength = 0; uint8_t *otInstanceBuffer = NULL; @@ -124,7 +124,7 @@ void TestFuzz(uint32_t aSeconds) // Initialize OpenThread with the buffer aInstance = otInstanceInit(otInstanceBuffer, &otInstanceBufferLength); #else - aInstance = otInstanceInit(); + aInstance = otInstanceInitSingle(); #endif VerifyOrQuit(aInstance != NULL, "Failed to initialize otInstance"); @@ -196,7 +196,7 @@ void TestFuzz(uint32_t aSeconds) // Clean up the instance otInstanceFinalize(aInstance); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES free(otInstanceBuffer); #endif } diff --git a/tests/unit/test_hmac_sha256.cpp b/tests/unit/test_hmac_sha256.cpp index dd2f41c30..06d881137 100644 --- a/tests/unit/test_hmac_sha256.cpp +++ b/tests/unit/test_hmac_sha256.cpp @@ -26,20 +26,16 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - +#include #include #include "common/debug.hpp" #include "crypto/hmac_sha256.hpp" -#include "crypto/mbedtls.hpp" +#include "utils/wrap_string.h" +#include "test_platform.h" #include "test_util.h" -#ifndef OPENTHREAD_MULTIPLE_INSTANCE -static ot::Crypto::MbedTls mMbedTls; -#endif - void TestHmacSha256(void) { static const struct @@ -66,9 +62,12 @@ void TestHmacSha256(void) }, }; + otInstance *instance = testInitInstance(); ot::Crypto::HmacSha256 hmac; uint8_t hash[ot::Crypto::HmacSha256::kHashSize]; + VerifyOrQuit(instance != NULL, "Null OpenThread instance"); + for (int i = 0; tests[i].key != NULL; i++) { hmac.Start(reinterpret_cast(tests[i].key), static_cast(strlen(tests[i].key))); @@ -78,6 +77,8 @@ void TestHmacSha256(void) VerifyOrQuit(memcmp(hash, tests[i].hash, sizeof(tests[i].hash)) == 0, "HMAC-SHA-256 failed\n"); } + + testFreeInstance(instance); } #ifdef ENABLE_TEST_MAIN diff --git a/tests/unit/test_link_quality.cpp b/tests/unit/test_link_quality.cpp index 17d4db1e6..9f61c3964 100644 --- a/tests/unit/test_link_quality.cpp +++ b/tests/unit/test_link_quality.cpp @@ -26,11 +26,10 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - #include #include "thread/link_quality.hpp" +#include "utils/wrap_string.h" #include "test_util.h" diff --git a/tests/unit/test_lowpan.cpp b/tests/unit/test_lowpan.cpp index 17b047dc3..997b00209 100644 --- a/tests/unit/test_lowpan.cpp +++ b/tests/unit/test_lowpan.cpp @@ -27,6 +27,8 @@ */ #include "test_lowpan.hpp" + +#include "test_platform.h" #include "test_util.hpp" using namespace ot; @@ -34,9 +36,10 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { -Ip6::Ip6 sIp6; -ThreadNetif sMockThreadNetif(sIp6); -Lowpan::Lowpan sMockLowpan(sMockThreadNetif); +otInstance *sInstance; +Ip6::Ip6 *sIp6; +ThreadNetif *sThreadNetif; +Lowpan::Lowpan *sLowpan; void TestIphcVector::GetCompressedStream(uint8_t *aIphc, uint16_t &aIphcLength) { @@ -108,7 +111,7 @@ void TestIphcVector::GetUncompressedStream(Message &aMessage) static void Init() { uint8_t meshLocalPrefix[] = {0xfd, 0x00, 0xca, 0xfe, 0xfa, 0xce, 0x12, 0x34}; - sMockThreadNetif.GetMle().SetMeshLocalPrefix(meshLocalPrefix); + sThreadNetif->GetMle().SetMeshLocalPrefix(meshLocalPrefix); // Emulate global prefixes with contextes. uint8_t mockNetworkData[] = @@ -128,7 +131,7 @@ static void Init() 0x02, 0x40 // Context ID = 2, C = FALSE }; - sMockThreadNetif.GetNetworkDataLeader().SetNetworkData(0, 0, true, mockNetworkData, sizeof(mockNetworkData)); + sThreadNetif->GetNetworkDataLeader().SetNetworkData(0, 0, true, mockNetworkData, sizeof(mockNetworkData)); } /** @@ -173,13 +176,13 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) if (aCompress) { - VerifyOrQuit((message = sIp6.mMessagePool.New(Message::kTypeIp6, 0)) != NULL, + VerifyOrQuit((message = sIp6->mMessagePool.New(Message::kTypeIp6, 0)) != NULL, "6lo: Ip6::NewMessage failed"); aVector.GetUncompressedStream(*message); - int compressBytes = sMockLowpan.Compress(*message, aVector.mMacSource, aVector.mMacDestination, - result); + int compressBytes = sLowpan->Compress(*message, aVector.mMacSource, aVector.mMacDestination, + result); if (aVector.mError == OT_ERROR_NONE) { @@ -208,11 +211,11 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) if (aDecompress) { - VerifyOrQuit((message = sIp6.mMessagePool.New(Message::kTypeIp6, 0)) != NULL, + VerifyOrQuit((message = sIp6->mMessagePool.New(Message::kTypeIp6, 0)) != NULL, "6lo: Ip6::NewMessage failed"); - int decompressedBytes = sMockLowpan.Decompress(*message, aVector.mMacSource, aVector.mMacDestination, - iphc, iphcLength, 0); + int decompressedBytes = sLowpan->Decompress(*message, aVector.mMacSource, aVector.mMacDestination, + iphc, iphcLength, 0); message->Read(0, message->GetLength(), result); @@ -1859,6 +1862,14 @@ static void TestErrorReservedNhc6(void) void TestLowpanIphc(void) { + sInstance = testInitInstance(); + + VerifyOrQuit(sInstance != NULL, "NULL instance"); + + sIp6 = &sInstance->mIp6; + sThreadNetif = &sInstance->mThreadNetif; + sLowpan = &sThreadNetif->GetLowpan(); + Init(); // Stateless unicast addresses compression / decompression tests. @@ -1938,6 +1949,8 @@ void TestLowpanIphc(void) TestErrorUnknownNhc(); TestErrorReservedNhc5(); TestErrorReservedNhc6(); + + testFreeInstance(sInstance); } } // namespace ot diff --git a/tests/unit/test_lowpan.hpp b/tests/unit/test_lowpan.hpp index b2f3eaf06..63ceb5e3d 100644 --- a/tests/unit/test_lowpan.hpp +++ b/tests/unit/test_lowpan.hpp @@ -29,14 +29,15 @@ #ifndef TEST_LOWPAN_HPP #define TEST_LOWPAN_HPP -#include "utils/wrap_stdint.h" #include +#include "openthread-instance.h" #include "mac/mac.hpp" #include "net/ip6_headers.hpp" #include "thread/lowpan.hpp" #include "thread/thread_netif.hpp" +#include "utils/wrap_stdint.h" namespace ot { diff --git a/tests/unit/test_mac_frame.cpp b/tests/unit/test_mac_frame.cpp index caec0edfa..d1bd74f77 100644 --- a/tests/unit/test_mac_frame.cpp +++ b/tests/unit/test_mac_frame.cpp @@ -26,12 +26,11 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - #include #include "common/debug.hpp" #include "mac/mac_frame.hpp" +#include "utils/wrap_string.h" #include "test_util.h" diff --git a/tests/unit/test_message.cpp b/tests/unit/test_message.cpp index 4a26d4342..646eae203 100644 --- a/tests/unit/test_message.cpp +++ b/tests/unit/test_message.cpp @@ -26,30 +26,35 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#include "utils/wrap_string.h" - #include #include "openthread-instance.h" #include "common/debug.hpp" #include "common/message.hpp" +#include "utils/wrap_string.h" +#include "test_platform.h" #include "test_util.h" void TestMessage(void) { - otInstance instance; - ot::MessagePool messagePool(&instance); + otInstance *instance; + ot::MessagePool *messagePool; ot::Message *message; uint8_t writeBuffer[1024]; uint8_t readBuffer[1024]; + instance = testInitInstance(); + VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); + + messagePool = &instance->mIp6.mMessagePool; + for (unsigned i = 0; i < sizeof(writeBuffer); i++) { writeBuffer[i] = static_cast(random()); } - VerifyOrQuit((message = messagePool.New(ot::Message::kTypeIp6, 0)) != NULL, + VerifyOrQuit((message = messagePool->New(ot::Message::kTypeIp6, 0)) != NULL, "Message::New failed\n"); SuccessOrQuit(message->SetLength(sizeof(writeBuffer)), "Message::SetLength failed\n"); @@ -63,6 +68,8 @@ void TestMessage(void) "Message::GetLength failed\n"); SuccessOrQuit(message->Free(), "Message::Free failed\n"); + + testFreeInstance(instance); } #ifdef ENABLE_TEST_MAIN diff --git a/tests/unit/test_message_queue.cpp b/tests/unit/test_message_queue.cpp index e9af4bf3e..e641e9551 100644 --- a/tests/unit/test_message_queue.cpp +++ b/tests/unit/test_message_queue.cpp @@ -27,18 +27,24 @@ */ #include -#include "utils/wrap_string.h" +#include "test_platform.h" + +#include #include #include "openthread-instance.h" #include "common/debug.hpp" #include "common/message.hpp" +#include "utils/wrap_string.h" #include "test_util.h" #define kNumTestMessages 5 +static otInstance *sInstance; +static ot::MessagePool *sMessagePool; + // This function verifies the content of the message queue to match the passed in messages void VerifyMessageQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLength, ...) { @@ -73,16 +79,19 @@ void VerifyMessageQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLen void TestMessageQueue(void) { - otInstance instance; - ot::MessagePool messagePool(&instance); ot::MessageQueue messageQueue; ot::Message *msg[kNumTestMessages]; otError error; uint16_t msgCount, bufferCount; + sInstance = testInitInstance(); + VerifyOrQuit(sInstance != NULL, "Null instance"); + + sMessagePool = &sInstance->mIp6.mMessagePool; + for (int i = 0; i < kNumTestMessages; i++) { - msg[i] = messagePool.New(ot::Message::kTypeIp6, 0); + msg[i] = sMessagePool->New(ot::Message::kTypeIp6, 0); VerifyOrQuit(msg[i] != NULL, "Message::New failed\n"); } @@ -146,6 +155,8 @@ void TestMessageQueue(void) error = messageQueue.Dequeue(*msg[1]); VerifyOrQuit(error == OT_ERROR_NOT_FOUND, "Dequeuing a message not in the queue did not fail as expected.\n"); + + testFreeInstance(sInstance); } // This function verifies the content of the message queue to match the passed in messages @@ -186,35 +197,17 @@ void VerifyMessageQueueContentUsingOtApi(otMessageQueue *aQueue, int aExpectedLe // This test checks all the OpenThread C APIs for `otMessageQueue` void TestMessageQueueOtApis(void) { - otInstance *instance; - otMessageQueue queue, queue2; - otMessage *msg[kNumTestMessages]; otError error; otMessage *message; + otMessageQueue queue, queue2; -#ifdef OPENTHREAD_MULTIPLE_INSTANCE - size_t otInstanceBufferLength = 0; - uint8_t *otInstanceBuffer = NULL; - - // Call to query the buffer size - (void)otInstanceInit(NULL, &otInstanceBufferLength); - - // Call to allocate the buffer - otInstanceBuffer = (uint8_t *)malloc(otInstanceBufferLength); - assert(otInstanceBuffer); - - // Initialize OpenThread with the buffer - instance = otInstanceInit(otInstanceBuffer, &otInstanceBufferLength); -#else - instance = otInstanceInit(); -#endif - - VerifyOrQuit(instance != NULL, "Failed to get and init an otInstance.\n"); + sInstance = testInitInstance(); + VerifyOrQuit(sInstance != NULL, "Null instance"); for (int i = 0; i < kNumTestMessages; i++) { - msg[i] = otIp6NewMessage(instance, true); + msg[i] = otIp6NewMessage(sInstance, true); VerifyOrQuit(msg[i] != NULL, "otIp6NewMessage() failed.\n"); } @@ -270,10 +263,7 @@ void TestMessageQueueOtApis(void) SuccessOrQuit(otMessageQueueDequeue(&queue, msg[2]), "Failed to dequeue a message from otMessageQueue.\n"); VerifyMessageQueueContentUsingOtApi(&queue, 0); - otInstanceFinalize(instance); -#ifdef OPENTHREAD_MULTIPLE_INSTANCE - free(otInstanceBuffer); -#endif + testFreeInstance(sInstance); } #ifdef ENABLE_TEST_MAIN diff --git a/tests/unit/test_ncp_buffer.cpp b/tests/unit/test_ncp_buffer.cpp index 1d1c261f2..914c4ff70 100644 --- a/tests/unit/test_ncp_buffer.cpp +++ b/tests/unit/test_ncp_buffer.cpp @@ -35,6 +35,7 @@ #include "common/message.hpp" #include "ncp/ncp_buffer.hpp" +#include "test_platform.h" #include "test_util.h" namespace ot { @@ -54,8 +55,8 @@ static const uint8_t sHelloText[] = "Hello there!"; static const uint8_t sMottoText[] = "Think good thoughts, say good words, do good deeds!"; static const uint8_t sMysteryText[] = "4871(\\):|(3$}{4|/4/2%14(\\)"; -static otInstance sInstance; -static MessagePool sMessagePool(&sInstance); +static otInstance *sInstance; +static MessagePool *sMessagePool; struct CallbackContext { @@ -187,7 +188,7 @@ void WriteTestFrame1(NcpFrameBuffer &aNcpBuffer) Message *message; CallbackContext oldContext; - message = sMessagePool.New(Message::kTypeIp6, 0); + message = sMessagePool->New(Message::kTypeIp6, 0); VerifyOrQuit(message != NULL, "Null Message"); SuccessOrQuit(message->SetLength(sizeof(sMottoText)), "Could not set the length of message."); message->Write(0, sizeof(sMottoText), sMottoText); @@ -235,12 +236,12 @@ void WriteTestFrame2(NcpFrameBuffer &aNcpBuffer) Message *message2; CallbackContext oldContext = sContext; - message1 = sMessagePool.New(Message::kTypeIp6, 0); + message1 = sMessagePool->New(Message::kTypeIp6, 0); VerifyOrQuit(message1 != NULL, "Null Message"); SuccessOrQuit(message1->SetLength(sizeof(sMysteryText)), "Could not set the length of message."); message1->Write(0, sizeof(sMysteryText), sMysteryText); - message2 = sMessagePool.New(Message::kTypeIp6, 0); + message2 = sMessagePool->New(Message::kTypeIp6, 0); VerifyOrQuit(message2 != NULL, "Null Message"); SuccessOrQuit(message2->SetLength(sizeof(sHelloText)), "Could not set the length of message."); message2->Write(0, sizeof(sHelloText), sHelloText); @@ -282,7 +283,7 @@ void WriteTestFrame3(NcpFrameBuffer &aNcpBuffer) Message *message1; CallbackContext oldContext = sContext; - message1 = sMessagePool.New(Message::kTypeIp6, 0); + message1 = sMessagePool->New(Message::kTypeIp6, 0); VerifyOrQuit(message1 != NULL, "Null Message"); // An empty message with no content. @@ -327,6 +328,9 @@ void TestNcpFrameBuffer(void) uint8_t readBuffer[16]; uint16_t readLen, readOffset; + sInstance = testInitInstance(); + sMessagePool = &sInstance->mIp6.mMessagePool; + for (i = 0; i < sizeof(buffer); i++) { buffer[i] = 0; @@ -423,7 +427,7 @@ void TestNcpFrameBuffer(void) ncpBuffer.InFrameBegin(); ncpBuffer.InFrameFeedData(sHelloText, sizeof(sHelloText)); - message = sMessagePool.New(Message::kTypeIp6, 0); + message = sMessagePool->New(Message::kTypeIp6, 0); VerifyOrQuit(message != NULL, "Null Message"); SuccessOrQuit(message->SetLength(sizeof(sMysteryText)), "Could not set the length of message."); message->Write(0, sizeof(sMysteryText), sMysteryText); @@ -509,6 +513,8 @@ void TestNcpFrameBuffer(void) VerifyOrQuit(readOffset == sizeof(sMottoText), "Read len does not match expected length."); printf("\n -- PASS\n"); + + testFreeInstance(sInstance); } /** @@ -614,6 +620,9 @@ void TestFuzzNcpFrameBuffer(void) uint32_t lensArrayStart; uint32_t lensArrayCount; + sInstance = testInitInstance(); + sMessagePool = &sInstance->mIp6.mMessagePool; + memset(buffer, 0, sizeof(buffer)); memset(lensArray, 0, sizeof(lensArray)); @@ -682,6 +691,8 @@ void TestFuzzNcpFrameBuffer(void) } printf("\n -- PASS\n"); + + testFreeInstance(sInstance); } } // namespace ot diff --git a/tests/unit/test_platform.cpp b/tests/unit/test_platform.cpp index 257861cb6..0fb701f65 100644 --- a/tests/unit/test_platform.cpp +++ b/tests/unit/test_platform.cpp @@ -77,11 +77,45 @@ void testPlatResetToDefaults(void) g_testPlatRadioGetTransmitBuffer = NULL; } +otInstance *testInitInstance(void) +{ + otInstance *instance = NULL; + +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + size_t instaneBufferLength = 0; + uint8_t *instanceBuffer = NULL; + + // Call to query the buffer size + (void)otInstanceInit(NULL, &instaneBufferLength); + + // Call to allocate the buffer + instanceBuffer = (uint8_t *)malloc(instaneBufferLength); + VerifyOrQuit(instanceBuffer != NULL, "Failed to allocate otInstance"); + memset(instanceBuffer, 0, instaneBufferLength); + + // Initialize OpenThread with the buffer + instance = otInstanceInit(instanceBuffer, &instaneBufferLength); +#else + instance = otInstanceInitSingle(); +#endif + + return instance; +} + +void testFreeInstance(otInstance *aInstance) +{ + otInstanceFinalize(aInstance); + +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + free(aInstance); +#endif +} + bool sDiagMode = false; extern "C" { -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES void *otPlatCAlloc(size_t aNum, size_t aSize) { return calloc(aNum, aSize); diff --git a/tests/unit/test_platform.h b/tests/unit/test_platform.h index 20ae9fd5a..2abff7524 100644 --- a/tests/unit/test_platform.h +++ b/tests/unit/test_platform.h @@ -37,6 +37,7 @@ #include +#include #include #include #include @@ -88,6 +89,9 @@ extern testPlatRadioReceive g_testPlatRadioReceive; extern testPlatRadioTransmit g_testPlatRadioTransmit; extern testPlatRadioGetTransmitBuffer g_testPlatRadioGetTransmitBuffer; +otInstance *testInitInstance(void); +void testFreeInstance(otInstance *aInstance); + // Resets platform functions to defaults void testPlatResetToDefaults(void); diff --git a/tests/unit/test_priority_queue.cpp b/tests/unit/test_priority_queue.cpp index 9c645d9ae..a57c1f2d6 100644 --- a/tests/unit/test_priority_queue.cpp +++ b/tests/unit/test_priority_queue.cpp @@ -27,14 +27,15 @@ */ #include -#include "utils/wrap_string.h" #include #include #include "common/debug.hpp" #include "common/message.hpp" +#include "utils/wrap_string.h" +#include "test_platform.h" #include "test_util.h" #define kNumTestMessages 3 @@ -113,7 +114,7 @@ void VerifyPriorityQueueContent(ot::PriorityQueue &aPriorityQueue, int aExpected } // This function verifies the content of the all message queue to match the passed in messages -void VerifyAllMessagesContent(ot::MessagePool &aMessagePool, int aExpectedLength, ...) +void VerifyAllMessagesContent(ot::MessagePool *aMessagePool, int aExpectedLength, ...) { va_list args; ot::MessagePool::Iterator it; @@ -123,12 +124,12 @@ void VerifyAllMessagesContent(ot::MessagePool &aMessagePool, int aExpectedLength if (aExpectedLength == 0) { - VerifyOrQuit(aMessagePool.GetAllMessagesHead().IsEmpty(), "Head is not empty when expected len is zero.\n"); - VerifyOrQuit(aMessagePool.GetAllMessagesTail().IsEmpty(), "Tail is not empty when expected len is zero.\n"); + VerifyOrQuit(aMessagePool->GetAllMessagesHead().IsEmpty(), "Head is not empty when expected len is zero.\n"); + VerifyOrQuit(aMessagePool->GetAllMessagesTail().IsEmpty(), "Tail is not empty when expected len is zero.\n"); } else { - for (it = aMessagePool.GetAllMessagesHead(); !it.HasEnded() ; it.GoToNext()) + for (it = aMessagePool->GetAllMessagesHead(); !it.HasEnded() ; it.GoToNext()) { VerifyOrQuit(aExpectedLength != 0, "AllMessagesQueue contains more entries than expected.\n"); msgArg = va_arg(args, ot::Message *); @@ -144,7 +145,7 @@ void VerifyAllMessagesContent(ot::MessagePool &aMessagePool, int aExpectedLength // This function verifies the content of the all message queue to match the passed in messages. It goes // through the AllMessages list in reverse. -void VerifyAllMessagesContentInReverse(ot::MessagePool &aMessagePool, int aExpectedLength, ...) +void VerifyAllMessagesContentInReverse(ot::MessagePool *aMessagePool, int aExpectedLength, ...) { va_list args; ot::MessagePool::Iterator it; @@ -154,12 +155,12 @@ void VerifyAllMessagesContentInReverse(ot::MessagePool &aMessagePool, int aExpec if (aExpectedLength == 0) { - VerifyOrQuit(aMessagePool.GetAllMessagesHead().IsEmpty(), "Head is not empty when expected len is zero.\n"); - VerifyOrQuit(aMessagePool.GetAllMessagesTail().IsEmpty(), "Tail is not empty when expected len is zero.\n"); + VerifyOrQuit(aMessagePool->GetAllMessagesHead().IsEmpty(), "Head is not empty when expected len is zero.\n"); + VerifyOrQuit(aMessagePool->GetAllMessagesTail().IsEmpty(), "Tail is not empty when expected len is zero.\n"); } else { - for (it = aMessagePool.GetAllMessagesTail(); !it.HasEnded() ; it.GoToPrev()) + for (it = aMessagePool->GetAllMessagesTail(); !it.HasEnded() ; it.GoToPrev()) { VerifyOrQuit(aExpectedLength != 0, "AllMessagesQueue contains more entries than expected.\n"); msgArg = va_arg(args, ot::Message *); @@ -207,8 +208,8 @@ void VerifyMsgQueueContent(ot::MessageQueue &aMessageQueue, int aExpectedLength, void TestPriorityQueue(void) { - otInstance instance; - ot::MessagePool messagePool(&instance); + otInstance *instance; + ot::MessagePool *messagePool; ot::PriorityQueue queue; ot::MessageQueue messageQueue; ot::Message *msgHigh [kNumTestMessages]; @@ -217,19 +218,24 @@ void TestPriorityQueue(void) ot::Message *msgVeryLow [kNumTestMessages]; ot::MessagePool::Iterator it; + instance = testInitInstance(); + VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); + + messagePool = &instance->mIp6.mMessagePool; + // Allocate messages with different priorities. for (int i = 0; i < kNumTestMessages; i++) { - msgHigh[i] = messagePool.New(ot::Message::kTypeIp6, 0); + msgHigh[i] = messagePool->New(ot::Message::kTypeIp6, 0); VerifyOrQuit(msgHigh[i] != NULL, "Message::New failed\n"); SuccessOrQuit(msgHigh[i]->SetPriority(0), "Message:SetPriority failed\n"); - msgMed[i] = messagePool.New(ot::Message::kTypeIp6, 0); + msgMed[i] = messagePool->New(ot::Message::kTypeIp6, 0); VerifyOrQuit(msgMed[i] != NULL, "Message::New failed\n"); SuccessOrQuit(msgMed[i]->SetPriority(1), "Message:SetPriority failed\n"); - msgLow[i] = messagePool.New(ot::Message::kTypeIp6, 0); + msgLow[i] = messagePool->New(ot::Message::kTypeIp6, 0); VerifyOrQuit(msgLow[i] != NULL, "Message::New failed\n"); SuccessOrQuit(msgLow[i]->SetPriority(2), "Message:SetPriority failed\n"); - msgVeryLow[i] = messagePool.New(ot::Message::kTypeIp6, 0); + msgVeryLow[i] = messagePool->New(ot::Message::kTypeIp6, 0); VerifyOrQuit(msgVeryLow[i] != NULL, "Message::New failed\n"); SuccessOrQuit(msgVeryLow[i]->SetPriority(3), "Message:SetPriority failed\n"); } @@ -278,7 +284,7 @@ void TestPriorityQueue(void) it.GoToNext(); VerifyOrQuit(it.IsEmpty(), "Iterator::IsEmpty() failed to return `true` for an empty iterator.\n"); - it = messagePool.GetAllMessagesHead(); + it = messagePool->GetAllMessagesHead(); VerifyOrQuit(!it.IsEmpty(), "Iterator::IsEmpty() failed to return `false` when it is not empty.\n"); VerifyOrQuit(it.GetMessage() == msgHigh[0], "Iterator::GetMessage() failed.\n"); it = it.GetNext(); @@ -288,7 +294,7 @@ void TestPriorityQueue(void) VerifyOrQuit(it.GetMessage() == msgHigh[0], "Iterator::GetPrev() failed.\n"); it = it.GetPrev(); VerifyOrQuit(it.HasEnded(), "Iterator::GetPrev() failed to return empty at head.\n"); - it = messagePool.GetAllMessagesTail(); + it = messagePool->GetAllMessagesTail(); it = it.GetNext(); VerifyOrQuit(it.HasEnded(), "Iterator::GetNext() failed to return empty at tail.\n"); @@ -397,6 +403,8 @@ void TestPriorityQueue(void) VerifyAllMessagesContent(messagePool, 2, msgLow[1], msgLow[0]); VerifyPriorityQueueContent(queue, 1, msgLow[0]); VerifyMsgQueueContent(messageQueue, 1, msgLow[1]); + + testFreeInstance(instance); } #ifdef ENABLE_TEST_MAIN diff --git a/tests/unit/test_timer.cpp b/tests/unit/test_timer.cpp index 3f45c3517..0cc415766 100644 --- a/tests/unit/test_timer.cpp +++ b/tests/unit/test_timer.cpp @@ -78,15 +78,34 @@ void InitCounters(void) memset(sCallCount, 0, sizeof(sCallCount)); } -void TestTimerHandler(void *aContext) +/** + * `TestTimer` sub-classes `ot::Timer` and provides a handler and a counter to keep track of number of times timer gets + * fired. + */ +class TestTimer: public ot::Timer { - sCallCount[kCallCountIndexTimerHandler]++; +public: + TestTimer(otInstance *aInstance): + ot::Timer(aInstance->mIp6.mTimerScheduler, TestTimer::HandleTimerFired, NULL), + mFiredCounter(0) + { } - if (aContext) - { - (*static_cast(aContext))++; + static void HandleTimerFired(ot::Timer &aTimer) { + static_cast(aTimer).HandleTimerFired(); } -} + + void HandleTimerFired(void) { + sCallCount[kCallCountIndexTimerHandler]++; + mFiredCounter++; + } + + uint32_t GetFiredCounter(void) { return mFiredCounter; } + + void ResetFiredCounter(void) { mFiredCounter = 0; } + +private: + uint32_t mFiredCounter; //< Number of times timer has been fired so far +}; /** * Test the TimerScheduler's behavior of one timer started and fired. @@ -95,8 +114,8 @@ int TestOneTimer(void) { const uint32_t kTimeT0 = 1000; const uint32_t kTimerInterval = 10; - otInstance aInstance; - ot::Timer timer(aInstance.mIp6.mTimerScheduler, TestTimerHandler, NULL); + otInstance *instance = testInitInstance(); + TestTimer timer(instance); // Test one Timer basic operation. @@ -117,7 +136,7 @@ int TestOneTimer(void) sNow += kTimerInterval; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); @@ -141,7 +160,7 @@ int TestOneTimer(void) sNow += kTimerInterval; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); @@ -165,7 +184,7 @@ int TestOneTimer(void) sNow += kTimerInterval + 5; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 1, "TestOneTimer: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); @@ -189,7 +208,7 @@ int TestOneTimer(void) sNow += kTimerInterval - 2; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestOneTimer: Stop CallCount Failed.\n"); @@ -199,7 +218,7 @@ int TestOneTimer(void) sNow += kTimerInterval; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestOneTimer: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestOneTimer: Stop CallCount Failed.\n"); @@ -209,6 +228,8 @@ int TestOneTimer(void) printf(" --> PASSED\n"); + testFreeInstance(instance); + return 0; } @@ -219,10 +240,9 @@ int TestTwoTimers(void) { const uint32_t kTimeT0 = 1000; const uint32_t kTimerInterval = 10; - otInstance aInstance; - uint32_t timerContextHandleCounter[2] = {0}; - ot::Timer timer1(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[0]); - ot::Timer timer2(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[1]); + otInstance *instance = testInitInstance(); + TestTimer timer1(instance); + TestTimer timer2(instance); InitTestTimer(); printf("TestTwoTimers() "); @@ -230,7 +250,6 @@ int TestTwoTimers(void) // Test when second timer stars at the fire time of first timer (before alarm callback). InitCounters(); - memset(timerContextHandleCounter, 0, sizeof(timerContextHandleCounter)); sNow = kTimeT0; timer1.Start(kTimerInterval); @@ -255,24 +274,24 @@ int TestTwoTimers(void) VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[0] == 1, "TestTwoTimers: Context handler failed.\n"); - VerifyOrQuit(sPlatT0 == sNow && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); + VerifyOrQuit(sPlatT0 == sNow && sPlatDt == kTimerInterval, "TestTwoTimers: Start params Failed.\n"); VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += kTimerInterval; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[1] == 1, "TestTwoTimers: Context handler failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); @@ -281,7 +300,8 @@ int TestTwoTimers(void) // is before the first timer. Ensure that the second timer handler is invoked before the first one. InitCounters(); - memset(timerContextHandleCounter, 0, sizeof(timerContextHandleCounter)); + timer1.ResetFiredCounter(); + timer2.ResetFiredCounter(); sNow = kTimeT0; timer1.Start(kTimerInterval); @@ -303,21 +323,21 @@ int TestTwoTimers(void) VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[1] == 1, "TestTwoTimers: Context handler failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); VerifyOrQuit(sPlatT0 == sNow && sPlatDt == 0, "TestTwoTimers: Start params Failed.\n"); VerifyOrQuit(timer1.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[0] == 1, "TestTwoTimers: Context handler failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); @@ -327,7 +347,8 @@ int TestTwoTimers(void) // the maximum interval. InitCounters(); - memset(timerContextHandleCounter, 0, sizeof(timerContextHandleCounter)); + timer1.ResetFiredCounter(); + timer2.ResetFiredCounter(); sNow = kTimeT0; timer1.Start(kTimerInterval); @@ -351,12 +372,12 @@ int TestTwoTimers(void) VerifyOrQuit(timer2.IsRunning() == true, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn, "TestTwoTimers: Platform Timer State Failed.\n"); - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 0, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 1, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[0] == 1, "TestTwoTimers: Context handler failed.\n"); + VerifyOrQuit(timer1.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); VerifyOrQuit(sPlatT0 == sNow, "TestTwoTimers: Start params Failed.\n"); VerifyOrQuit(sPlatDt == ot::Timer::kMaxDt, "TestTwoTimers: Start params Failed.\n"); VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); @@ -364,18 +385,20 @@ int TestTwoTimers(void) VerifyOrQuit(sTimerOn == true, "TestTwoTimers: Platform Timer State Failed.\n"); sNow += ot::Timer::kMaxDt; - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStart] == 2, "TestTwoTimers: Start CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexAlarmStop] == 1, "TestTwoTimers: Stop CallCount Failed.\n"); VerifyOrQuit(sCallCount[kCallCountIndexTimerHandler] == 2, "TestTwoTimers: Handler CallCount Failed.\n"); - VerifyOrQuit(timerContextHandleCounter[1] == 1, "TestTwoTimers: Context handler failed.\n"); + VerifyOrQuit(timer2.GetFiredCounter() == 1, "TestTwoTimers: Fire Counter failed.\n"); VerifyOrQuit(timer1.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(timer2.IsRunning() == false, "TestTwoTimers: Timer running Failed.\n"); VerifyOrQuit(sTimerOn == false, "TestTwoTimers: Platform Timer State Failed.\n"); printf(" --> PASSED\n"); + testFreeInstance(instance); + return 0; } @@ -501,20 +524,19 @@ static void TenTimers(uint32_t aTimeShift) 11 }; - otInstance aInstance; + otInstance *instance = testInitInstance(); - uint32_t timerContextHandleCounter[kNumTimers] = {0}; - ot::Timer timer0(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[0]); - ot::Timer timer1(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[1]); - ot::Timer timer2(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[2]); - ot::Timer timer3(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[3]); - ot::Timer timer4(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[4]); - ot::Timer timer5(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[5]); - ot::Timer timer6(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[6]); - ot::Timer timer7(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[7]); - ot::Timer timer8(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[8]); - ot::Timer timer9(aInstance.mIp6.mTimerScheduler, TestTimerHandler, &timerContextHandleCounter[9]); - ot::Timer *timers[kNumTimers] = + TestTimer timer0(instance); + TestTimer timer1(instance); + TestTimer timer2(instance); + TestTimer timer3(instance); + TestTimer timer4(instance); + TestTimer timer5(instance); + TestTimer timer6(instance); + TestTimer timer7(instance); + TestTimer timer8(instance); + TestTimer timer9(instance); + TestTimer *timers[kNumTimers] = { &timer0, &timer1, @@ -570,7 +592,7 @@ static void TenTimers(uint32_t aTimeShift) // timer is ready to be triggered by examining the aDt arg passed into otPlatAlarmStartAt(). If // that value is 0, then otPlatAlarmFired should be fired immediately. This loop calls otPlatAlarmFired() // the requisite number of times based on the aDt argument. - otPlatAlarmFired(&aInstance); + otPlatAlarmFired(instance); } while (sPlatDt == 0); @@ -594,10 +616,12 @@ static void TenTimers(uint32_t aTimeShift) for (i = 0 ; i < kNumTimers ; i++) { - VerifyOrQuit(timerContextHandleCounter[i] == 1, "TestTenTimer: Timer context counter Failed.\n"); + VerifyOrQuit(timers[i]->GetFiredCounter() == 1, "TestTenTimer: Timer fired counter Failed.\n"); } printf("--> PASSED\n"); + + testFreeInstance(instance); } int TestTenTimers(void) diff --git a/tests/unit/test_toolchain.cpp b/tests/unit/test_toolchain.cpp index 937b45f53..4fbdf1352 100644 --- a/tests/unit/test_toolchain.cpp +++ b/tests/unit/test_toolchain.cpp @@ -27,12 +27,12 @@ */ #include -#include "utils/wrap_stdint.h" #include #include "thread/topology.hpp" #include "test_util.h" +#include "utils/wrap_stdint.h" extern "C" { uint32_t otNetifAddress_Size_c(); diff --git a/third_party/mbedtls/mbedtls-config.h b/third_party/mbedtls/mbedtls-config.h index f29ebeaa3..0b9693bd5 100644 --- a/third_party/mbedtls/mbedtls-config.h +++ b/third_party/mbedtls/mbedtls-config.h @@ -30,8 +30,9 @@ #include -#include "openthread/platform/logging.h" -#include "openthread/platform/memory.h" +#include +#include +#include #if defined(_WIN32) #include @@ -1973,7 +1974,7 @@ __inline int windows_kernel_snprintf(char * s, size_t n, const char * format, .. * * Enable this module to enable the buffer memory allocator. */ -#ifndef OPENTHREAD_MULTIPLE_INSTANCE +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES #define MBEDTLS_MEMORY_BUFFER_ALLOC_C #endif @@ -2547,7 +2548,7 @@ __inline int windows_kernel_snprintf(char * s, size_t n, const char * format, .. /* Platform options */ //#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */ -#ifdef OPENTHREAD_MULTIPLE_INSTANCE +#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES #define MBEDTLS_PLATFORM_STD_CALLOC otPlatCAlloc /**< Default allocator to use, can be undefined */ #define MBEDTLS_PLATFORM_STD_FREE otPlatFree /**< Default free to use, can be undefined */ #endif