diff --git a/Android.mk b/Android.mk index f8da48839..dc7af41e6 100644 --- a/Android.mk +++ b/Android.mk @@ -115,7 +115,6 @@ LOCAL_SRC_FILES := \ src/core/common/crc16.cpp \ src/core/common/instance.cpp \ src/core/common/logging.cpp \ - src/core/common/locator.cpp \ src/core/common/message.cpp \ src/core/common/notifier.cpp \ src/core/common/settings.cpp \ diff --git a/etc/visual-studio/libopenthread.vcxproj b/etc/visual-studio/libopenthread.vcxproj index adf19303e..712b55d6c 100644 --- a/etc/visual-studio/libopenthread.vcxproj +++ b/etc/visual-studio/libopenthread.vcxproj @@ -78,7 +78,6 @@ - @@ -171,6 +170,7 @@ + diff --git a/etc/visual-studio/libopenthread.vcxproj.filters b/etc/visual-studio/libopenthread.vcxproj.filters index c54bd11ff..d9c6e7127 100644 --- a/etc/visual-studio/libopenthread.vcxproj.filters +++ b/etc/visual-studio/libopenthread.vcxproj.filters @@ -132,9 +132,6 @@ Source Files\common - - Source Files\common - Source Files\common @@ -401,6 +398,9 @@ 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 dfb541c55..cb35102bf 100644 --- a/etc/visual-studio/libopenthread_k.vcxproj +++ b/etc/visual-studio/libopenthread_k.vcxproj @@ -87,7 +87,6 @@ - @@ -198,6 +197,7 @@ + diff --git a/etc/visual-studio/libopenthread_k.vcxproj.filters b/etc/visual-studio/libopenthread_k.vcxproj.filters index 028cc5ab2..5ad9902e6 100644 --- a/etc/visual-studio/libopenthread_k.vcxproj.filters +++ b/etc/visual-studio/libopenthread_k.vcxproj.filters @@ -129,9 +129,6 @@ Source Files\common - - Source Files\common - Source Files\common @@ -395,6 +392,9 @@ Header Files\common + + Header Files\common + Header Files\common diff --git a/src/core/Makefile.am b/src/core/Makefile.am index 9fc53e35e..5e866f970 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -135,7 +135,6 @@ SOURCES_COMMON = \ coap/coap_secure.cpp \ common/crc16.cpp \ common/instance.cpp \ - common/locator.cpp \ common/logging.cpp \ common/message.cpp \ common/notifier.cpp \ @@ -236,7 +235,6 @@ libopenthread_radio_a_SOURCES = \ api/message_api.cpp \ api/tasklet_api.cpp \ common/instance.cpp \ - common/locator.cpp \ common/logging.cpp \ common/message.cpp \ common/string.cpp \ @@ -297,11 +295,11 @@ HEADERS_COMMON = \ common/extension.hpp \ common/instance.hpp \ common/locator.hpp \ + common/locator-getters.hpp \ common/logging.hpp \ common/message.hpp \ common/new.hpp \ common/notifier.hpp \ - common/owner-locator.hpp \ common/random.hpp \ common/settings.hpp \ common/string.hpp \ diff --git a/src/core/api/border_agent_api.cpp b/src/core/api/border_agent_api.cpp index 110936c4f..641f4e883 100644 --- a/src/core/api/border_agent_api.cpp +++ b/src/core/api/border_agent_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #if OPENTHREAD_ENABLE_BORDER_AGENT @@ -45,7 +46,7 @@ otBorderAgentState otBorderAgentGetState(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetBorderAgent().GetState(); + return instance.Get().GetState(); } #endif // OPENTHREAD_ENABLE_BORDER_AGENT diff --git a/src/core/api/border_router_api.cpp b/src/core/api/border_router_api.cpp index a8ed43992..90d0ac5d2 100644 --- a/src/core/api/border_router_api.cpp +++ b/src/core/api/border_router_api.cpp @@ -38,6 +38,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -48,7 +49,7 @@ otError otBorderRouterGetNetData(otInstance *aInstance, bool aStable, uint8_t *a VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLocal().GetNetworkData(aStable, aData, *aDataLength); + error = instance.Get().GetNetworkData(aStable, aData, *aDataLength); exit: return error; @@ -89,7 +90,7 @@ otError otBorderRouterAddOnMeshPrefix(otInstance *aInstance, const otBorderRoute flags |= NetworkData::BorderRouterEntry::kOnMeshFlag; } - return instance.GetThreadNetif().GetNetworkDataLocal().AddOnMeshPrefix( + return instance.Get().AddOnMeshPrefix( aConfig->mPrefix.mPrefix.mFields.m8, aConfig->mPrefix.mLength, aConfig->mPreference, flags, aConfig->mStable); } @@ -97,8 +98,7 @@ otError otBorderRouterRemoveOnMeshPrefix(otInstance *aInstance, const otIp6Prefi { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().RemoveOnMeshPrefix(aPrefix->mPrefix.mFields.m8, - aPrefix->mLength); + return instance.Get().RemoveOnMeshPrefix(aPrefix->mPrefix.mFields.m8, aPrefix->mLength); } otError otBorderRouterGetNextOnMeshPrefix(otInstance * aInstance, @@ -110,7 +110,7 @@ otError otBorderRouterGetNextOnMeshPrefix(otInstance * aInstance, VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLocal().GetNextOnMeshPrefix(aIterator, aConfig); + error = instance.Get().GetNextOnMeshPrefix(aIterator, aConfig); exit: return error; @@ -120,7 +120,7 @@ otError otBorderRouterAddRoute(otInstance *aInstance, const otExternalRouteConfi { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().AddHasRoutePrefix( + return instance.Get().AddHasRoutePrefix( aConfig->mPrefix.mPrefix.mFields.m8, aConfig->mPrefix.mLength, aConfig->mPreference, aConfig->mStable); } @@ -128,8 +128,7 @@ otError otBorderRouterRemoveRoute(otInstance *aInstance, const otIp6Prefix *aPre { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().RemoveHasRoutePrefix(aPrefix->mPrefix.mFields.m8, - aPrefix->mLength); + return instance.Get().RemoveHasRoutePrefix(aPrefix->mPrefix.mFields.m8, aPrefix->mLength); } otError otBorderRouterGetNextRoute(otInstance * aInstance, @@ -141,7 +140,7 @@ otError otBorderRouterGetNextRoute(otInstance * aInstance, VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLocal().GetNextExternalRoute(aIterator, aConfig); + error = instance.Get().GetNextExternalRoute(aIterator, aConfig); exit: return error; @@ -151,7 +150,7 @@ otError otBorderRouterRegister(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().SendServerDataNotification(); + return instance.Get().SendServerDataNotification(); } #endif // OPENTHREAD_ENABLE_BORDER_ROUTER diff --git a/src/core/api/channel_manager_api.cpp b/src/core/api/channel_manager_api.cpp index 71a09522c..a9835e20a 100644 --- a/src/core/api/channel_manager_api.cpp +++ b/src/core/api/channel_manager_api.cpp @@ -35,6 +35,7 @@ #include "openthread/channel_manager.h" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "utils/channel_manager.hpp" using namespace ot; @@ -45,91 +46,91 @@ void otChannelManagerRequestChannelChange(otInstance *aInstance, uint8_t aChanne { Instance &instance = *static_cast(aInstance); - instance.GetChannelManager().RequestChannelChange(aChannel); + instance.Get().RequestChannelChange(aChannel); } uint8_t otChannelManagerGetRequestedChannel(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetRequestedChannel(); + return instance.Get().GetRequestedChannel(); } uint16_t otChannelManagerGetDelay(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetDelay(); + return instance.Get().GetDelay(); } otError otChannelManagerSetDelay(otInstance *aInstance, uint16_t aDelay) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().SetDelay(aDelay); + return instance.Get().SetDelay(aDelay); } otError otChannelManagerRequestChannelSelect(otInstance *aInstance, bool aSkipQualityCheck) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().RequestChannelSelect(aSkipQualityCheck); + return instance.Get().RequestChannelSelect(aSkipQualityCheck); } void otChannelManagerSetAutoChannelSelectionEnabled(otInstance *aInstance, bool aEnabled) { Instance &instance = *static_cast(aInstance); - instance.GetChannelManager().SetAutoChannelSelectionEnabled(aEnabled); + instance.Get().SetAutoChannelSelectionEnabled(aEnabled); } bool otChannelManagerGetAutoChannelSelectionEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetAutoChannelSelectionEnabled(); + return instance.Get().GetAutoChannelSelectionEnabled(); } otError otChannelManagerSetAutoChannelSelectionInterval(otInstance *aInstance, uint32_t aInterval) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().SetAutoChannelSelectionInterval(aInterval); + return instance.Get().SetAutoChannelSelectionInterval(aInterval); } uint32_t otChannelManagerGetAutoChannelSelectionInterval(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetAutoChannelSelectionInterval(); + return instance.Get().GetAutoChannelSelectionInterval(); } uint32_t otChannelManagerGetSupportedChannels(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetSupportedChannels(); + return instance.Get().GetSupportedChannels(); } void otChannelManagerSetSupportedChannels(otInstance *aInstance, uint32_t aChannelMask) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().SetSupportedChannels(aChannelMask); + return instance.Get().SetSupportedChannels(aChannelMask); } uint32_t otChannelManagerGetFavoredChannels(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().GetFavoredChannels(); + return instance.Get().GetFavoredChannels(); } void otChannelManagerSetFavoredChannels(otInstance *aInstance, uint32_t aChannelMask) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelManager().SetFavoredChannels(aChannelMask); + return instance.Get().SetFavoredChannels(aChannelMask); } #endif // OPENTHREAD_ENABLE_CHANNEL_MANAGER && OPENTHREAD_FTD diff --git a/src/core/api/channel_monitor_api.cpp b/src/core/api/channel_monitor_api.cpp index 48b0b5ab7..7c43ed0d5 100644 --- a/src/core/api/channel_monitor_api.cpp +++ b/src/core/api/channel_monitor_api.cpp @@ -35,6 +35,7 @@ #include "openthread/channel_monitor.h" #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -42,7 +43,7 @@ using namespace ot; otError otChannelMonitorSetEnabled(otInstance *aInstance, bool aEnabled) { - Utils::ChannelMonitor monitor = static_cast(aInstance)->GetChannelMonitor(); + Utils::ChannelMonitor monitor = static_cast(aInstance)->Get(); return aEnabled ? monitor.Start() : monitor.Stop(); } @@ -51,7 +52,7 @@ bool otChannelMonitorIsEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelMonitor().IsRunning(); + return instance.Get().IsRunning(); } uint32_t otChannelMonitorGetSampleInterval(otInstance *aInstance) @@ -79,14 +80,14 @@ uint32_t otChannelMonitorGetSampleCount(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelMonitor().GetSampleCount(); + return instance.Get().GetSampleCount(); } uint16_t otChannelMonitorGetChannelOccupancy(otInstance *aInstance, uint8_t aChannel) { Instance &instance = *static_cast(aInstance); - return instance.GetChannelMonitor().GetChannelOccupancy(aChannel); + return instance.Get().GetChannelOccupancy(aChannel); } #endif // OPENTHREAD_ENABLE_CHANNEL_MONITOR diff --git a/src/core/api/child_supervision_api.cpp b/src/core/api/child_supervision_api.cpp index e7f87af40..924f12a08 100644 --- a/src/core/api/child_supervision_api.cpp +++ b/src/core/api/child_supervision_api.cpp @@ -35,6 +35,7 @@ #include "openthread/child_supervision.h" #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -44,28 +45,28 @@ uint16_t otChildSupervisionGetInterval(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetChildSupervisor().GetSupervisionInterval(); + return instance.Get().GetSupervisionInterval(); } void otChildSupervisionSetInterval(otInstance *aInstance, uint16_t aInterval) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetChildSupervisor().SetSupervisionInterval(aInterval); + instance.Get().SetSupervisionInterval(aInterval); } uint16_t otChildSupervisionGetCheckTimeout(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetSupervisionListener().GetTimeout(); + return instance.Get().GetTimeout(); } void otChildSupervisionSetCheckTimeout(otInstance *aInstance, uint16_t aTimeout) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetSupervisionListener().SetTimeout(aTimeout); + instance.Get().SetTimeout(aTimeout); } #endif // OPENTHREAD_ENABLE_CHILD_SUPERVISION diff --git a/src/core/api/coap_api.cpp b/src/core/api/coap_api.cpp index 46b5bcc27..7b81fe977 100644 --- a/src/core/api/coap_api.cpp +++ b/src/core/api/coap_api.cpp @@ -37,6 +37,7 @@ #include "coap/coap_message.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #if OPENTHREAD_ENABLE_APPLICATION_COAP diff --git a/src/core/api/coap_secure_api.cpp b/src/core/api/coap_secure_api.cpp index 5f2c8acac..4027bb52e 100644 --- a/src/core/api/coap_secure_api.cpp +++ b/src/core/api/coap_secure_api.cpp @@ -39,6 +39,7 @@ #include "coap/coap_message.hpp" #include "coap/coap_secure.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE diff --git a/src/core/api/commissioner_api.cpp b/src/core/api/commissioner_api.cpp index 4463d4c19..92d61bf17 100644 --- a/src/core/api/commissioner_api.cpp +++ b/src/core/api/commissioner_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -49,7 +50,7 @@ otError otCommissionerStart(otInstance *aInstance) #if OPENTHREAD_ENABLE_BORDER_AGENT SuccessOrExit(error = instance.Get().Stop()); #endif - SuccessOrExit(error = instance.GetThreadNetif().GetCommissioner().Start()); + SuccessOrExit(error = instance.Get().Start()); exit: #endif OT_UNUSED_VARIABLE(aInstance); @@ -65,7 +66,7 @@ otError otCommissionerStop(otInstance *aInstance) #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - SuccessOrExit(error = instance.GetThreadNetif().GetCommissioner().Stop()); + SuccessOrExit(error = instance.Get().Stop()); #if OPENTHREAD_ENABLE_BORDER_AGENT SuccessOrExit(error = instance.Get().Start()); #endif @@ -81,8 +82,8 @@ otError otCommissionerAddJoiner(otInstance *aInstance, const otExtAddress *aEui6 #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().AddJoiner(static_cast(aEui64), aPSKd, - aTimeout); + error = + instance.Get().AddJoiner(static_cast(aEui64), aPSKd, aTimeout); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aEui64); @@ -100,7 +101,7 @@ otError otCommissionerRemoveJoiner(otInstance *aInstance, const otExtAddress *aE #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().RemoveJoiner(static_cast(aEui64), 0); + error = instance.Get().RemoveJoiner(static_cast(aEui64), 0); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aEui64); @@ -116,7 +117,7 @@ otError otCommissionerSetProvisioningUrl(otInstance *aInstance, const char *aPro #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().SetProvisioningUrl(aProvisioningUrl); + error = instance.Get().SetProvisioningUrl(aProvisioningUrl); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aProvisioningUrl); @@ -134,7 +135,7 @@ const char *otCommissionerGetProvisioningUrl(otInstance *aInstance, uint16_t *aL if (aLength != NULL) { - url = instance.GetThreadNetif().GetCommissioner().GetProvisioningUrl(*aLength); + url = instance.Get().GetProvisioningUrl(*aLength); } #else OT_UNUSED_VARIABLE(aInstance); @@ -155,7 +156,7 @@ otError otCommissionerAnnounceBegin(otInstance * aInstance, #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().GetAnnounceBeginClient().SendRequest( + error = instance.Get().GetAnnounceBeginClient().SendRequest( aChannelMask, aCount, aPeriod, *static_cast(aAddress)); #else OT_UNUSED_VARIABLE(aInstance); @@ -182,7 +183,7 @@ otError otCommissionerEnergyScan(otInstance * aInstance, #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().GetEnergyScanClient().SendQuery( + error = instance.Get().GetEnergyScanClient().SendQuery( aChannelMask, aCount, aPeriod, aScanDuration, *static_cast(aAddress), aCallback, aContext); #else @@ -211,7 +212,7 @@ otError otCommissionerPanIdQuery(otInstance * aInstance, #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().GetPanIdQueryClient().SendQuery( + error = instance.Get().GetPanIdQueryClient().SendQuery( aPanId, aChannelMask, *static_cast(aAddress), aCallback, aContext); #else OT_UNUSED_VARIABLE(aInstance); @@ -232,7 +233,7 @@ otError otCommissionerSendMgmtGet(otInstance *aInstance, const uint8_t *aTlvs, u #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().SendMgmtCommissionerGetRequest(aTlvs, aLength); + error = instance.Get().SendMgmtCommissionerGetRequest(aTlvs, aLength); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aTlvs); @@ -252,7 +253,7 @@ otError otCommissionerSendMgmtSet(otInstance * aInstance, #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetCommissioner().SendMgmtCommissionerSetRequest(*aDataset, aTlvs, aLength); + error = instance.Get().SendMgmtCommissionerSetRequest(*aDataset, aTlvs, aLength); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aDataset); @@ -270,7 +271,7 @@ uint16_t otCommissionerGetSessionId(otInstance *aInstance) #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - sessionId = instance.GetThreadNetif().GetCommissioner().GetSessionId(); + sessionId = instance.Get().GetSessionId(); #else OT_UNUSED_VARIABLE(aInstance); #endif @@ -285,7 +286,7 @@ otCommissionerState otCommissionerGetState(otInstance *aInstance) #if OPENTHREAD_FTD && OPENTHREAD_ENABLE_COMMISSIONER Instance &instance = *static_cast(aInstance); - state = instance.GetThreadNetif().GetCommissioner().GetState(); + state = instance.Get().GetState(); #else OT_UNUSED_VARIABLE(aInstance); #endif diff --git a/src/core/api/crypto_api.cpp b/src/core/api/crypto_api.cpp index 7a330487b..2c2c2776b 100644 --- a/src/core/api/crypto_api.cpp +++ b/src/core/api/crypto_api.cpp @@ -37,6 +37,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" +#include "common/locator-getters.hpp" #include "crypto/aes_ccm.hpp" #include "crypto/ecdsa.hpp" #include "crypto/hmac_sha256.hpp" diff --git a/src/core/api/dataset_api.cpp b/src/core/api/dataset_api.cpp index 0fe6f5767..09bb304d5 100644 --- a/src/core/api/dataset_api.cpp +++ b/src/core/api/dataset_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -57,7 +58,7 @@ otError otDatasetGetActive(otInstance *aInstance, otOperationalDataset *aDataset VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetActiveDataset().Read(*aDataset); + error = instance.Get().Read(*aDataset); exit: return error; @@ -70,7 +71,7 @@ otError otDatasetSetActive(otInstance *aInstance, const otOperationalDataset *aD VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetActiveDataset().Save(*aDataset); + error = instance.Get().Save(*aDataset); exit: return error; @@ -83,7 +84,7 @@ otError otDatasetGetPending(otInstance *aInstance, otOperationalDataset *aDatase VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetPendingDataset().Read(*aDataset); + error = instance.Get().Read(*aDataset); exit: return error; @@ -96,7 +97,7 @@ otError otDatasetSetPending(otInstance *aInstance, const otOperationalDataset *a VerifyOrExit(aDataset != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetPendingDataset().Save(*aDataset); + error = instance.Get().Save(*aDataset); exit: return error; @@ -110,8 +111,7 @@ otError otDatasetSendMgmtActiveGet(otInstance * aInstan { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetActiveDataset().SendGetRequest(*aDatasetComponents, aTlvTypes, aLength, - aAddress); + return instance.Get().SendGetRequest(*aDatasetComponents, aTlvTypes, aLength, aAddress); } otError otDatasetSendMgmtActiveSet(otInstance * aInstance, @@ -121,7 +121,7 @@ otError otDatasetSendMgmtActiveSet(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetActiveDataset().SendSetRequest(*aDataset, aTlvs, aLength); + return instance.Get().SendSetRequest(*aDataset, aTlvs, aLength); } otError otDatasetSendMgmtPendingGet(otInstance * aInstance, @@ -132,8 +132,7 @@ otError otDatasetSendMgmtPendingGet(otInstance * aInsta { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetPendingDataset().SendGetRequest(*aDatasetComponents, aTlvTypes, aLength, - aAddress); + return instance.Get().SendGetRequest(*aDatasetComponents, aTlvTypes, aLength, aAddress); } otError otDatasetSendMgmtPendingSet(otInstance * aInstance, @@ -143,5 +142,5 @@ otError otDatasetSendMgmtPendingSet(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetPendingDataset().SendSetRequest(*aDataset, aTlvs, aLength); + return instance.Get().SendSetRequest(*aDataset, aTlvs, aLength); } diff --git a/src/core/api/dataset_ftd_api.cpp b/src/core/api/dataset_ftd_api.cpp index 7e73e14f2..929906193 100644 --- a/src/core/api/dataset_ftd_api.cpp +++ b/src/core/api/dataset_ftd_api.cpp @@ -38,6 +38,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -45,14 +46,14 @@ uint32_t otDatasetGetDelayTimerMinimal(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetLeader().GetDelayTimerMinimal(); + return instance.Get().GetDelayTimerMinimal(); } otError otDatasetSetDelayTimerMinimal(otInstance *aInstance, uint32_t aDelayTimerMinimal) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetLeader().SetDelayTimerMinimal(aDelayTimerMinimal); + return instance.Get().SetDelayTimerMinimal(aDelayTimerMinimal); } #endif // OPENTHREAD_FTD diff --git a/src/core/api/dns_api.cpp b/src/core/api/dns_api.cpp index 0482f4735..256f9db82 100644 --- a/src/core/api/dns_api.cpp +++ b/src/core/api/dns_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -44,6 +45,6 @@ otError otDnsClientQuery(otInstance *aInstance, const otDnsQuery *aQuery, otDnsR { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetDnsClient().Query(aQuery, aHandler, aContext); + return instance.Get().Query(aQuery, aHandler, aContext); } #endif diff --git a/src/core/api/icmp6_api.cpp b/src/core/api/icmp6_api.cpp index 78ed9ce2d..f23f18fda 100644 --- a/src/core/api/icmp6_api.cpp +++ b/src/core/api/icmp6_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -43,21 +44,21 @@ otIcmp6EchoMode otIcmp6GetEchoMode(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetIcmp().GetEchoMode(); + return instance.Get().GetEchoMode(); } void otIcmp6SetEchoMode(otInstance *aInstance, otIcmp6EchoMode aMode) { Instance &instance = *static_cast(aInstance); - instance.GetIp6().GetIcmp().SetEchoMode(aMode); + instance.Get().SetEchoMode(aMode); } otError otIcmp6RegisterHandler(otInstance *aInstance, otIcmp6Handler *aHandler) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetIcmp().RegisterHandler(*static_cast(aHandler)); + return instance.Get().RegisterHandler(*static_cast(aHandler)); } otError otIcmp6SendEchoRequest(otInstance * aInstance, @@ -67,6 +68,6 @@ otError otIcmp6SendEchoRequest(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetIcmp().SendEchoRequest( - *static_cast(aMessage), *static_cast(aMessageInfo), aIdentifier); + return instance.Get().SendEchoRequest(*static_cast(aMessage), + *static_cast(aMessageInfo), aIdentifier); } diff --git a/src/core/api/instance_api.cpp b/src/core/api/instance_api.cpp index 52883caeb..3ad18bae1 100644 --- a/src/core/api/instance_api.cpp +++ b/src/core/api/instance_api.cpp @@ -40,6 +40,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/new.hpp" @@ -92,14 +93,14 @@ otError otSetStateChangedCallback(otInstance *aInstance, otStateChangedCallback { Instance &instance = *static_cast(aInstance); - return instance.GetNotifier().RegisterCallback(aCallback, aContext); + return instance.Get().RegisterCallback(aCallback, aContext); } void otRemoveStateChangeCallback(otInstance *aInstance, otStateChangedCallback aCallback, void *aContext) { Instance &instance = *static_cast(aInstance); - instance.GetNotifier().RemoveCallback(aCallback, aContext); + instance.Get().RemoveCallback(aCallback, aContext); } void otInstanceFactoryReset(otInstance *aInstance) diff --git a/src/core/api/ip6_api.cpp b/src/core/api/ip6_api.cpp index f7e789229..eca35bd1a 100644 --- a/src/core/api/ip6_api.cpp +++ b/src/core/api/ip6_api.cpp @@ -38,6 +38,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #if OPENTHREAD_CONFIG_ENABLE_SLAAC #include "utils/slaac_address.hpp" @@ -51,16 +52,16 @@ otError otIp6SetEnabled(otInstance *aInstance, bool aEnabled) Instance &instance = *static_cast(aInstance); #if OPENTHREAD_ENABLE_RAW_LINK_API - VerifyOrExit(!instance.GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(!instance.Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); #endif if (aEnabled) { - instance.GetThreadNetif().Up(); + instance.Get().Up(); } else { - instance.GetThreadNetif().Down(); + instance.Get().Down(); } #if OPENTHREAD_ENABLE_RAW_LINK_API @@ -73,21 +74,21 @@ bool otIp6IsEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().IsUp(); + return instance.Get().IsUp(); } const otNetifAddress *otIp6GetUnicastAddresses(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetUnicastAddresses(); + return instance.Get().GetUnicastAddresses(); } otError otIp6AddUnicastAddress(otInstance *aInstance, const otNetifAddress *aAddress) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().AddExternalUnicastAddress( + return instance.Get().AddExternalUnicastAddress( *static_cast(aAddress)); } @@ -95,70 +96,70 @@ otError otIp6RemoveUnicastAddress(otInstance *aInstance, const otIp6Address *aAd { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().RemoveExternalUnicastAddress(*static_cast(aAddress)); + return instance.Get().RemoveExternalUnicastAddress(*static_cast(aAddress)); } const otNetifMulticastAddress *otIp6GetMulticastAddresses(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMulticastAddresses(); + return instance.Get().GetMulticastAddresses(); } otError otIp6SubscribeMulticastAddress(otInstance *aInstance, const otIp6Address *aAddress) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().SubscribeExternalMulticast(*static_cast(aAddress)); + return instance.Get().SubscribeExternalMulticast(*static_cast(aAddress)); } otError otIp6UnsubscribeMulticastAddress(otInstance *aInstance, const otIp6Address *aAddress) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().UnsubscribeExternalMulticast(*static_cast(aAddress)); + return instance.Get().UnsubscribeExternalMulticast(*static_cast(aAddress)); } bool otIp6IsMulticastPromiscuousEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().IsMulticastPromiscuousEnabled(); + return instance.Get().IsMulticastPromiscuousEnabled(); } void otIp6SetMulticastPromiscuousEnabled(otInstance *aInstance, bool aEnabled) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().SetMulticastPromiscuous(aEnabled); + instance.Get().SetMulticastPromiscuous(aEnabled); } void otIp6SetReceiveCallback(otInstance *aInstance, otIp6ReceiveCallback aCallback, void *aCallbackContext) { Instance &instance = *static_cast(aInstance); - instance.GetIp6().SetReceiveDatagramCallback(aCallback, aCallbackContext); + instance.Get().SetReceiveDatagramCallback(aCallback, aCallbackContext); } void otIp6SetAddressCallback(otInstance *aInstance, otIp6AddressCallback aCallback, void *aCallbackContext) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().SetAddressCallback(aCallback, aCallbackContext); + instance.Get().SetAddressCallback(aCallback, aCallbackContext); } bool otIp6IsReceiveFilterEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().IsReceiveIp6FilterEnabled(); + return instance.Get().IsReceiveIp6FilterEnabled(); } void otIp6SetReceiveFilterEnabled(otInstance *aInstance, bool aEnabled) { Instance &instance = *static_cast(aInstance); - instance.GetIp6().SetReceiveIp6FilterEnabled(aEnabled); + instance.Get().SetReceiveIp6FilterEnabled(aEnabled); } otError otIp6Send(otInstance *aInstance, otMessage *aMessage) @@ -166,7 +167,8 @@ otError otIp6Send(otInstance *aInstance, otMessage *aMessage) otError error; Instance &instance = *static_cast(aInstance); - error = instance.GetIp6().SendRaw(*static_cast(aMessage), instance.GetThreadNetif().GetInterfaceId()); + error = instance.Get().SendRaw(*static_cast(aMessage), + instance.Get().GetInterfaceId()); return error; } @@ -181,7 +183,7 @@ otMessage *otIp6NewMessage(otInstance *aInstance, const otMessageSettings *aSett VerifyOrExit(aSettings->mPriority <= OT_MESSAGE_PRIORITY_HIGH, message = NULL); } - message = instance.GetIp6().NewMessage(0, aSettings); + message = instance.Get().NewMessage(0, aSettings); exit: return message; @@ -195,7 +197,7 @@ otMessage *otIp6NewMessageFromBuffer(otInstance * aInstance, Instance &instance = *static_cast(aInstance); Message * message; - VerifyOrExit((message = instance.GetIp6().NewMessage(aData, aDataLength, aSettings)) != NULL); + VerifyOrExit((message = instance.Get().NewMessage(aData, aDataLength, aSettings)) != NULL); exit: return message; @@ -205,28 +207,28 @@ otError otIp6AddUnsecurePort(otInstance *aInstance, uint16_t aPort) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetIp6Filter().AddUnsecurePort(aPort); + return instance.Get().AddUnsecurePort(aPort); } otError otIp6RemoveUnsecurePort(otInstance *aInstance, uint16_t aPort) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetIp6Filter().RemoveUnsecurePort(aPort); + return instance.Get().RemoveUnsecurePort(aPort); } void otIp6RemoveAllUnsecurePorts(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetIp6Filter().RemoveAllUnsecurePorts(); + instance.Get().RemoveAllUnsecurePorts(); } const uint16_t *otIp6GetUnsecurePorts(otInstance *aInstance, uint8_t *aNumEntries) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetIp6Filter().GetUnsecurePorts(*aNumEntries); + return instance.Get().GetUnsecurePorts(*aNumEntries); } bool otIp6IsAddressEqual(const otIp6Address *aFirst, const otIp6Address *aSecond) @@ -262,7 +264,7 @@ otError otIp6SelectSourceAddress(otInstance *aInstance, otMessageInfo *aMessageI Instance & instance = *static_cast(aInstance); const Ip6::NetifUnicastAddress *netifAddr; - netifAddr = instance.GetIp6().SelectSourceAddress(*static_cast(aMessageInfo)); + netifAddr = instance.Get().SelectSourceAddress(*static_cast(aMessageInfo)); VerifyOrExit(netifAddr != NULL, error = OT_ERROR_NOT_FOUND); memcpy(&aMessageInfo->mSockAddr, &netifAddr->mAddress, sizeof(aMessageInfo->mSockAddr)); @@ -279,16 +281,15 @@ bool otIp6IsSlaacEnabled(otInstance *aInstance) void otIp6SetSlaacEnabled(otInstance *aInstance, bool aEnabled) { - Instance & instance = *static_cast(aInstance); - Utils::Slaac &slaac = instance.Get(); + Instance &instance = *static_cast(aInstance); if (aEnabled) { - slaac.Enable(); + instance.Get().Enable(); } else { - slaac.Disable(); + instance.Get().Disable(); } } diff --git a/src/core/api/jam_detection_api.cpp b/src/core/api/jam_detection_api.cpp index a17e22a85..738dccc2c 100644 --- a/src/core/api/jam_detection_api.cpp +++ b/src/core/api/jam_detection_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -45,7 +46,7 @@ otError otJamDetectionSetRssiThreshold(otInstance *aInstance, int8_t aRssiThresh { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetJamDetector().SetRssiThreshold(aRssiThreshold); + instance.Get().SetRssiThreshold(aRssiThreshold); return OT_ERROR_NONE; } @@ -54,70 +55,70 @@ int8_t otJamDetectionGetRssiThreshold(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().GetRssiThreshold(); + return instance.Get().GetRssiThreshold(); } otError otJamDetectionSetWindow(otInstance *aInstance, uint8_t aWindow) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().SetWindow(aWindow); + return instance.Get().SetWindow(aWindow); } uint8_t otJamDetectionGetWindow(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().GetWindow(); + return instance.Get().GetWindow(); } otError otJamDetectionSetBusyPeriod(otInstance *aInstance, uint8_t aBusyPeriod) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().SetBusyPeriod(aBusyPeriod); + return instance.Get().SetBusyPeriod(aBusyPeriod); } uint8_t otJamDetectionGetBusyPeriod(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().GetBusyPeriod(); + return instance.Get().GetBusyPeriod(); } otError otJamDetectionStart(otInstance *aInstance, otJamDetectionCallback aCallback, void *aContext) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().Start(aCallback, aContext); + return instance.Get().Start(aCallback, aContext); } otError otJamDetectionStop(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().Stop(); + return instance.Get().Stop(); } bool otJamDetectionIsEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().IsEnabled(); + return instance.Get().IsEnabled(); } bool otJamDetectionGetState(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().GetState(); + return instance.Get().GetState(); } uint64_t otJamDetectionGetHistoryBitmap(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJamDetector().GetHistoryBitmap(); + return instance.Get().GetHistoryBitmap(); } #endif // OPENTHREAD_ENABLE_JAM_DETECTION diff --git a/src/core/api/joiner_api.cpp b/src/core/api/joiner_api.cpp index 620bfff02..be1964289 100644 --- a/src/core/api/joiner_api.cpp +++ b/src/core/api/joiner_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -53,8 +54,8 @@ otError otJoinerStart(otInstance * aInstance, #if OPENTHREAD_ENABLE_JOINER Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetJoiner().Start(aPSKd, aProvisioningUrl, aVendorName, aVendorModel, - aVendorSwVersion, aVendorData, aCallback, aContext); + error = instance.Get().Start(aPSKd, aProvisioningUrl, aVendorName, aVendorModel, aVendorSwVersion, + aVendorData, aCallback, aContext); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aPSKd); @@ -77,7 +78,7 @@ otError otJoinerStop(otInstance *aInstance) #if OPENTHREAD_ENABLE_JOINER Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetJoiner().Stop(); + instance.Get().Stop(); error = OT_ERROR_NONE; #else OT_UNUSED_VARIABLE(aInstance); @@ -94,7 +95,7 @@ otJoinerState otJoinerGetState(otInstance *aInstance) #if OPENTHREAD_ENABLE_JOINER Instance &instance = *static_cast(aInstance); - state = instance.GetThreadNetif().GetJoiner().GetState(); + state = instance.Get().GetState(); #else OT_UNUSED_VARIABLE(aInstance); #endif @@ -109,7 +110,7 @@ otError otJoinerGetId(otInstance *aInstance, otExtAddress *aJoinerId) #if OPENTHREAD_ENABLE_JOINER Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetJoiner().GetJoinerId(*static_cast(aJoinerId)); + instance.Get().GetJoinerId(*static_cast(aJoinerId)); error = OT_ERROR_NONE; #else OT_UNUSED_VARIABLE(aInstance); diff --git a/src/core/api/link_api.cpp b/src/core/api/link_api.cpp index ae02f99f8..bdea5c70a 100644 --- a/src/core/api/link_api.cpp +++ b/src/core/api/link_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "mac/mac.hpp" #include "phy/phy.hpp" @@ -50,14 +51,14 @@ uint8_t otLinkGetChannel(otInstance *aInstance) uint8_t channel; #if OPENTHREAD_ENABLE_RAW_LINK_API - if (instance.GetLinkRaw().IsEnabled()) + if (instance.Get().IsEnabled()) { - channel = instance.GetLinkRaw().GetChannel(); + channel = instance.Get().GetChannel(); } else #endif { - channel = instance.GetThreadNetif().GetMac().GetPanChannel(); + channel = instance.Get().GetPanChannel(); } return channel; @@ -69,19 +70,18 @@ otError otLinkSetChannel(otInstance *aInstance, uint8_t aChannel) Instance &instance = *static_cast(aInstance); #if OPENTHREAD_ENABLE_RAW_LINK_API - if (instance.GetLinkRaw().IsEnabled()) + if (instance.Get().IsEnabled()) { - error = instance.GetLinkRaw().SetChannel(aChannel); + error = instance.Get().SetChannel(aChannel); ExitNow(); } #endif - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - SuccessOrExit(error = instance.GetThreadNetif().GetMac().SetPanChannel(aChannel)); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + SuccessOrExit(error = instance.Get().SetPanChannel(aChannel)); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -91,7 +91,7 @@ uint32_t otLinkGetSupportedChannelMask(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetSupportedChannelMask().GetMask(); + return instance.Get().GetSupportedChannelMask().GetMask(); } otError otLinkSetSupportedChannelMask(otInstance *aInstance, uint32_t aChannelMask) @@ -99,10 +99,9 @@ otError otLinkSetSupportedChannelMask(otInstance *aInstance, uint32_t aChannelMa otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetSupportedChannelMask(static_cast(aChannelMask)); + instance.Get().SetSupportedChannelMask(static_cast(aChannelMask)); exit: return error; @@ -112,7 +111,7 @@ const otExtAddress *otLinkGetExtendedAddress(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMac().GetExtAddress(); + return &instance.Get().GetExtAddress(); } otError otLinkSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) @@ -121,12 +120,11 @@ otError otLinkSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExt Instance &instance = *static_cast(aInstance); VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetExtAddress(*static_cast(aExtAddress)); + instance.Get().SetExtAddress(*static_cast(aExtAddress)); - instance.GetThreadNetif().GetMle().UpdateLinkLocalAddress(); + instance.Get().UpdateLinkLocalAddress(); exit: return error; @@ -141,7 +139,7 @@ otPanId otLinkGetPanId(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetPanId(); + return instance.Get().GetPanId(); } otError otLinkSetPanId(otInstance *aInstance, otPanId aPanId) @@ -149,12 +147,11 @@ otError otLinkSetPanId(otInstance *aInstance, otPanId aPanId) otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetPanId(aPanId); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + instance.Get().SetPanId(aPanId); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -164,28 +161,28 @@ uint32_t otLinkGetPollPeriod(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMeshForwarder().GetDataPollManager().GetKeepAlivePollPeriod(); + return instance.Get().GetKeepAlivePollPeriod(); } otError otLinkSetPollPeriod(otInstance *aInstance, uint32_t aPollPeriod) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMeshForwarder().GetDataPollManager().SetExternalPollPeriod(aPollPeriod); + return instance.Get().SetExternalPollPeriod(aPollPeriod); } otError otLinkSendDataRequest(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMeshForwarder().GetDataPollManager().SendDataPoll(); + return instance.Get().SendDataPoll(); } otShortAddress otLinkGetShortAddress(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetShortAddress(); + return instance.Get().GetShortAddress(); } #if OPENTHREAD_ENABLE_MAC_FILTER @@ -194,14 +191,14 @@ otMacFilterAddressMode otLinkFilterGetAddressMode(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().GetAddressMode(); + return instance.Get().GetAddressMode(); } otError otLinkFilterSetAddressMode(otInstance *aInstance, otMacFilterAddressMode aMode) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().SetAddressMode(aMode); + return instance.Get().SetAddressMode(aMode); } otError otLinkFilterAddAddress(otInstance *aInstance, const otExtAddress *aExtAddress) @@ -211,8 +208,7 @@ otError otLinkFilterAddAddress(otInstance *aInstance, const otExtAddress *aExtAd VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); - error = - instance.GetThreadNetif().GetMac().GetFilter().AddAddress(*static_cast(aExtAddress)); + error = instance.Get().AddAddress(*static_cast(aExtAddress)); exit: return error; @@ -225,8 +221,7 @@ otError otLinkFilterRemoveAddress(otInstance *aInstance, const otExtAddress *aEx VerifyOrExit(aExtAddress != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMac().GetFilter().RemoveAddress( - *static_cast(aExtAddress)); + error = instance.Get().RemoveAddress(*static_cast(aExtAddress)); exit: return error; @@ -236,7 +231,7 @@ void otLinkFilterClearAddresses(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().ClearAddresses(); + return instance.Get().ClearAddresses(); } otError otLinkFilterGetNextAddress(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) @@ -246,7 +241,7 @@ otError otLinkFilterGetNextAddress(otInstance *aInstance, otMacFilterIterator *a VerifyOrExit(aIterator != NULL && aEntry != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMac().GetFilter().GetNextAddress(*aIterator, *aEntry); + error = instance.Get().GetNextAddress(*aIterator, *aEntry); exit: return error; @@ -256,23 +251,21 @@ otError otLinkFilterAddRssIn(otInstance *aInstance, const otExtAddress *aExtAddr { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().AddRssIn(static_cast(aExtAddress), - aRss); + return instance.Get().AddRssIn(static_cast(aExtAddress), aRss); } otError otLinkFilterRemoveRssIn(otInstance *aInstance, const otExtAddress *aExtAddress) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetFilter().RemoveRssIn( - static_cast(aExtAddress)); + return instance.Get().RemoveRssIn(static_cast(aExtAddress)); } void otLinkFilterClearRssIn(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMac().GetFilter().ClearRssIn(); + instance.Get().ClearRssIn(); } otError otLinkFilterGetNextRssIn(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) @@ -282,7 +275,7 @@ otError otLinkFilterGetNextRssIn(otInstance *aInstance, otMacFilterIterator *aIt VerifyOrExit(aIterator != NULL && aEntry != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMac().GetFilter().GetNextRssIn(*aIterator, *aEntry); + error = instance.Get().GetNextRssIn(*aIterator, *aEntry); exit: return error; @@ -292,14 +285,14 @@ uint8_t otLinkConvertRssToLinkQuality(otInstance *aInstance, int8_t aRss) { Instance &instance = *static_cast(aInstance); - return LinkQualityInfo::ConvertRssToLinkQuality(instance.GetThreadNetif().GetMac().GetNoiseFloor(), aRss); + return LinkQualityInfo::ConvertRssToLinkQuality(instance.Get().GetNoiseFloor(), aRss); } int8_t otLinkConvertLinkQualityToRss(otInstance *aInstance, uint8_t aLinkQuality) { Instance &instance = *static_cast(aInstance); - return LinkQualityInfo::ConvertLinkQualityToRss(instance.GetThreadNetif().GetMac().GetNoiseFloor(), aLinkQuality); + return LinkQualityInfo::ConvertLinkQualityToRss(instance.Get().GetNoiseFloor(), aLinkQuality); } #endif // OPENTHREAD_ENABLE_MAC_FILTER @@ -308,14 +301,14 @@ void otLinkSetPcapCallback(otInstance *aInstance, otLinkPcapCallback aPcapCallba { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMac().SetPcapCallback(aPcapCallback, aCallbackContext); + instance.Get().SetPcapCallback(aPcapCallback, aCallbackContext); } bool otLinkIsPromiscuous(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().IsPromiscuous(); + return instance.Get().IsPromiscuous(); } otError otLinkSetPromiscuous(otInstance *aInstance, bool aPromiscuous) @@ -324,9 +317,9 @@ otError otLinkSetPromiscuous(otInstance *aInstance, bool aPromiscuous) Instance &instance = *static_cast(aInstance); // cannot enable IEEE 802.15.4 promiscuous mode if the Thread interface is enabled - VerifyOrExit(instance.GetThreadNetif().IsUp() == false, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().IsUp() == false, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetPromiscuous(aPromiscuous); + instance.Get().SetPromiscuous(aPromiscuous); exit: return error; @@ -338,9 +331,9 @@ otError otLinkSetEnabled(otInstance *aInstance, bool aEnable) Instance &instance = *static_cast(aInstance); // cannot disable the link layer if the Thread interface is enabled - VerifyOrExit(instance.GetThreadNetif().IsUp() == false, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().IsUp() == false, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetEnabled(aEnable); + instance.Get().SetEnabled(aEnable); exit: return error; @@ -350,14 +343,14 @@ bool otLinkIsEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().IsEnabled(); + return instance.Get().IsEnabled(); } const otMacCounters *otLinkGetCounters(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMac().GetCounters(); + return &instance.Get().GetCounters(); } otError otLinkActiveScan(otInstance * aInstance, @@ -369,14 +362,14 @@ otError otLinkActiveScan(otInstance * aInstance, Instance &instance = *static_cast(aInstance); instance.RegisterActiveScanCallback(aCallback, aCallbackContext); - return instance.GetThreadNetif().GetMac().ActiveScan(aScanChannels, aScanDuration, &HandleActiveScanResult); + return instance.Get().ActiveScan(aScanChannels, aScanDuration, &HandleActiveScanResult); } bool otLinkIsActiveScanInProgress(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().IsActiveScanInProgress(); + return instance.Get().IsActiveScanInProgress(); } void HandleActiveScanResult(Instance &aInstance, Mac::Frame *aFrame) @@ -389,7 +382,7 @@ void HandleActiveScanResult(Instance &aInstance, Mac::Frame *aFrame) { otActiveScanResult result; - aInstance.GetThreadNetif().GetMac().ConvertBeaconToActiveScanResult(aFrame, result); + aInstance.Get().ConvertBeaconToActiveScanResult(aFrame, result); aInstance.InvokeActiveScanCallback(&result); } } @@ -403,7 +396,7 @@ otError otLinkEnergyScan(otInstance * aInstance, Instance &instance = *static_cast(aInstance); instance.RegisterEnergyScanCallback(aCallback, aCallbackContext); - return instance.GetThreadNetif().GetMac().EnergyScan(aScanChannels, aScanDuration, &HandleEnergyScanResult); + return instance.Get().EnergyScan(aScanChannels, aScanDuration, &HandleEnergyScanResult); } void HandleEnergyScanResult(Instance &aInstance, otEnergyScanResult *aResult) @@ -415,28 +408,28 @@ bool otLinkIsEnergyScanInProgress(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().IsEnergyScanInProgress(); + return instance.Get().IsEnergyScanInProgress(); } bool otLinkIsInTransmitState(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().IsInTransmitState(); + return instance.Get().IsInTransmitState(); } otError otLinkOutOfBandTransmitRequest(otInstance *aInstance, otRadioFrame *aOobFrame) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().SendOutOfBandFrameRequest(aOobFrame); + return instance.Get().SendOutOfBandFrameRequest(aOobFrame); } uint16_t otLinkGetCcaFailureRate(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetCcaFailureRate(); + return instance.Get().GetCcaFailureRate(); } uint8_t otLinkGetPhyChannelMin(otInstance *aInstance) diff --git a/src/core/api/link_raw_api.cpp b/src/core/api/link_raw_api.cpp index eba3e198f..1e0bd65c5 100644 --- a/src/core/api/link_raw_api.cpp +++ b/src/core/api/link_raw_api.cpp @@ -39,7 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" -#include "common/owner-locator.hpp" +#include "common/locator-getters.hpp" #include "common/random.hpp" #include "mac/mac.hpp" #include "mac/mac_frame.hpp" @@ -51,17 +51,17 @@ using namespace ot; otError otLinkRawSetEnable(otInstance *aInstance, bool aEnabled) { - return static_cast(aInstance)->GetLinkRaw().SetEnabled(aEnabled); + return static_cast(aInstance)->Get().SetEnabled(aEnabled); } bool otLinkRawIsEnabled(otInstance *aInstance) { - return static_cast(aInstance)->GetLinkRaw().IsEnabled(); + return static_cast(aInstance)->Get().IsEnabled(); } otError otLinkRawSetShortAddress(otInstance *aInstance, uint16_t aShortAddress) { - return static_cast(aInstance)->GetLinkRaw().SetShortAddress(aShortAddress); + return static_cast(aInstance)->Get().SetShortAddress(aShortAddress); } bool otLinkRawGetPromiscuous(otInstance *aInstance) @@ -73,7 +73,7 @@ otError otLinkRawSetPromiscuous(otInstance *aInstance, bool aEnable) { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); otPlatRadioSetPromiscuous(aInstance, aEnable); exit: @@ -84,7 +84,7 @@ otError otLinkRawSleep(otInstance *aInstance) { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); error = otPlatRadioSleep(aInstance); @@ -94,17 +94,17 @@ exit: otError otLinkRawReceive(otInstance *aInstance, otLinkRawReceiveDone aCallback) { - return static_cast(aInstance)->GetLinkRaw().Receive(aCallback); + return static_cast(aInstance)->Get().Receive(aCallback); } otRadioFrame *otLinkRawGetTransmitBuffer(otInstance *aInstance) { - return &static_cast(aInstance)->GetLinkRaw().GetTransmitFrame(); + return &static_cast(aInstance)->Get().GetTransmitFrame(); } otError otLinkRawTransmit(otInstance *aInstance, otLinkRawTransmitDone aCallback) { - return static_cast(aInstance)->GetLinkRaw().Transmit(aCallback); + return static_cast(aInstance)->Get().Transmit(aCallback); } int8_t otLinkRawGetRssi(otInstance *aInstance) @@ -114,7 +114,7 @@ int8_t otLinkRawGetRssi(otInstance *aInstance) otRadioCaps otLinkRawGetCaps(otInstance *aInstance) { - return static_cast(aInstance)->GetLinkRaw().GetCaps(); + return static_cast(aInstance)->Get().GetCaps(); } otError otLinkRawEnergyScan(otInstance * aInstance, @@ -122,14 +122,14 @@ otError otLinkRawEnergyScan(otInstance * aInstance, uint16_t aScanDuration, otLinkRawEnergyScanDone aCallback) { - return static_cast(aInstance)->GetLinkRaw().EnergyScan(aScanChannel, aScanDuration, aCallback); + return static_cast(aInstance)->Get().EnergyScan(aScanChannel, aScanDuration, aCallback); } otError otLinkRawSrcMatchEnable(otInstance *aInstance, bool aEnable) { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); otPlatRadioEnableSrcMatch(aInstance, aEnable); @@ -141,7 +141,7 @@ otError otLinkRawSrcMatchAddShortEntry(otInstance *aInstance, const uint16_t aSh { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); error = otPlatRadioAddSrcMatchShortEntry(aInstance, aShortAddress); @@ -154,7 +154,7 @@ otError otLinkRawSrcMatchAddExtEntry(otInstance *aInstance, const otExtAddress * Mac::Address address; otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); address.SetExtended(aExtAddress->m8, /* aReverse */ true); @@ -168,7 +168,7 @@ otError otLinkRawSrcMatchClearShortEntry(otInstance *aInstance, const uint16_t a { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); error = otPlatRadioClearSrcMatchShortEntry(aInstance, aShortAddress); @@ -181,7 +181,7 @@ otError otLinkRawSrcMatchClearExtEntry(otInstance *aInstance, const otExtAddress Mac::Address address; otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); address.SetExtended(aExtAddress->m8, /* aReverse */ true); @@ -195,7 +195,7 @@ otError otLinkRawSrcMatchClearShortEntries(otInstance *aInstance) { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); otPlatRadioClearSrcMatchShortEntries(aInstance); @@ -207,7 +207,7 @@ otError otLinkRawSrcMatchClearExtEntries(otInstance *aInstance) { otError error = OT_ERROR_NONE; - VerifyOrExit(static_cast(aInstance)->GetLinkRaw().IsEnabled(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(static_cast(aInstance)->Get().IsEnabled(), error = OT_ERROR_INVALID_STATE); otPlatRadioClearSrcMatchExtEntries(aInstance); @@ -225,38 +225,38 @@ otDeviceRole otThreadGetDeviceRole(otInstance *aInstance) uint8_t otLinkGetChannel(otInstance *aInstance) { - return static_cast(aInstance)->GetLinkRaw().GetChannel(); + return static_cast(aInstance)->Get().GetChannel(); } otError otLinkSetChannel(otInstance *aInstance, uint8_t aChannel) { - return static_cast(aInstance)->GetLinkRaw().SetChannel(aChannel); + return static_cast(aInstance)->Get().SetChannel(aChannel); } otPanId otLinkGetPanId(otInstance *aInstance) { - return static_cast(aInstance)->GetLinkRaw().GetPanId(); + return static_cast(aInstance)->Get().GetPanId(); } otError otLinkSetPanId(otInstance *aInstance, uint16_t aPanId) { - return static_cast(aInstance)->GetLinkRaw().SetPanId(aPanId); + return static_cast(aInstance)->Get().SetPanId(aPanId); } const otExtAddress *otLinkGetExtendedAddress(otInstance *aInstance) { - return &static_cast(aInstance)->GetLinkRaw().GetExtAddress(); + return &static_cast(aInstance)->Get().GetExtAddress(); } otError otLinkSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { - return static_cast(aInstance)->GetLinkRaw().SetExtAddress( + return static_cast(aInstance)->Get().SetExtAddress( *static_cast(aExtAddress)); } uint16_t otLinkGetShortAddress(otInstance *aInstance) { - return static_cast(aInstance)->GetLinkRaw().GetShortAddress(); + return static_cast(aInstance)->Get().GetShortAddress(); } #if OPENTHREAD_ENABLE_DIAG diff --git a/src/core/api/logging_api.cpp b/src/core/api/logging_api.cpp index 4f43761a5..1f14ab257 100644 --- a/src/core/api/logging_api.cpp +++ b/src/core/api/logging_api.cpp @@ -37,6 +37,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; diff --git a/src/core/api/message_api.cpp b/src/core/api/message_api.cpp index 8dd556883..c25e9c6d4 100644 --- a/src/core/api/message_api.cpp +++ b/src/core/api/message_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -170,39 +171,35 @@ void otMessageGetBufferInfo(otInstance *aInstance, otBufferInfo *aBufferInfo) aBufferInfo->mTotalBuffers = OPENTHREAD_CONFIG_NUM_MESSAGE_BUFFERS; - aBufferInfo->mFreeBuffers = instance.GetMessagePool().GetFreeBufferCount(); + aBufferInfo->mFreeBuffers = instance.Get().GetFreeBufferCount(); - instance.GetThreadNetif().GetMeshForwarder().GetSendQueue().GetInfo(aBufferInfo->m6loSendMessages, - aBufferInfo->m6loSendBuffers); + instance.Get().GetSendQueue().GetInfo(aBufferInfo->m6loSendMessages, aBufferInfo->m6loSendBuffers); - instance.GetThreadNetif().GetMeshForwarder().GetReassemblyQueue().GetInfo(aBufferInfo->m6loReassemblyMessages, - aBufferInfo->m6loReassemblyBuffers); + instance.Get().GetReassemblyQueue().GetInfo(aBufferInfo->m6loReassemblyMessages, + aBufferInfo->m6loReassemblyBuffers); #if OPENTHREAD_FTD - instance.GetThreadNetif().GetMeshForwarder().GetResolvingQueue().GetInfo(aBufferInfo->mArpMessages, - aBufferInfo->mArpBuffers); + instance.Get().GetResolvingQueue().GetInfo(aBufferInfo->mArpMessages, aBufferInfo->mArpBuffers); #else aBufferInfo->mArpMessages = 0; aBufferInfo->mArpBuffers = 0; #endif - instance.GetThreadNetif().GetIp6().GetSendQueue().GetInfo(aBufferInfo->mIp6Messages, aBufferInfo->mIp6Buffers); + instance.Get().GetSendQueue().GetInfo(aBufferInfo->mIp6Messages, aBufferInfo->mIp6Buffers); - instance.GetThreadNetif().GetIp6().GetMpl().GetBufferedMessageSet().GetInfo(aBufferInfo->mMplMessages, - aBufferInfo->mMplBuffers); + instance.Get().GetBufferedMessageSet().GetInfo(aBufferInfo->mMplMessages, aBufferInfo->mMplBuffers); - instance.GetThreadNetif().GetMle().GetMessageQueue().GetInfo(aBufferInfo->mMleMessages, aBufferInfo->mMleBuffers); + instance.Get().GetMessageQueue().GetInfo(aBufferInfo->mMleMessages, aBufferInfo->mMleBuffers); - instance.GetThreadNetif().GetCoap().GetRequestMessages().GetInfo(aBufferInfo->mCoapMessages, - aBufferInfo->mCoapBuffers); - instance.GetThreadNetif().GetCoap().GetCachedResponses().GetInfo(messages, buffers); + instance.Get().GetRequestMessages().GetInfo(aBufferInfo->mCoapMessages, aBufferInfo->mCoapBuffers); + instance.Get().GetCachedResponses().GetInfo(messages, buffers); aBufferInfo->mCoapMessages += messages; aBufferInfo->mCoapBuffers += buffers; #if OPENTHREAD_ENABLE_DTLS - instance.GetThreadNetif().GetCoapSecure().GetRequestMessages().GetInfo(aBufferInfo->mCoapSecureMessages, - aBufferInfo->mCoapSecureBuffers); - instance.GetThreadNetif().GetCoapSecure().GetCachedResponses().GetInfo(messages, buffers); + instance.Get().GetRequestMessages().GetInfo(aBufferInfo->mCoapSecureMessages, + aBufferInfo->mCoapSecureBuffers); + instance.Get().GetCachedResponses().GetInfo(messages, buffers); aBufferInfo->mCoapSecureMessages += messages; aBufferInfo->mCoapSecureBuffers += buffers; #else diff --git a/src/core/api/netdata_api.cpp b/src/core/api/netdata_api.cpp index 27e3986ad..fe30987d1 100644 --- a/src/core/api/netdata_api.cpp +++ b/src/core/api/netdata_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -46,7 +47,7 @@ otError otNetDataGet(otInstance *aInstance, bool aStable, uint8_t *aData, uint8_ VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLeader().GetNetworkData(aStable, aData, *aDataLength); + error = instance.Get().GetNetworkData(aStable, aData, *aDataLength); exit: return error; @@ -61,7 +62,7 @@ otError otNetDataGetNextOnMeshPrefix(otInstance * aInstance, VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLeader().GetNextOnMeshPrefix(aIterator, aConfig); + error = instance.Get().GetNextOnMeshPrefix(aIterator, aConfig); exit: return error; @@ -74,7 +75,7 @@ otError otNetDataGetNextRoute(otInstance *aInstance, otNetworkDataIterator *aIte VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLeader().GetNextExternalRoute(aIterator, aConfig); + error = instance.Get().GetNextExternalRoute(aIterator, aConfig); exit: return error; @@ -84,12 +85,12 @@ uint8_t otNetDataGetVersion(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetDataVersion(); + return instance.Get().GetLeaderDataTlv().GetDataVersion(); } uint8_t otNetDataGetStableVersion(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetStableDataVersion(); + return instance.Get().GetLeaderDataTlv().GetStableDataVersion(); } diff --git a/src/core/api/network_time_api.cpp b/src/core/api/network_time_api.cpp index 7d1fc9b04..dd4d5f99e 100644 --- a/src/core/api/network_time_api.cpp +++ b/src/core/api/network_time_api.cpp @@ -38,6 +38,7 @@ #include "openthread/network_time.h" #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -45,7 +46,7 @@ otNetworkTimeStatus otNetworkTimeGet(otInstance *aInstance, uint64_t &aNetworkTi { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetTimeSync().GetTime(aNetworkTime); + return instance.Get().GetTime(aNetworkTime); } otError otNetworkTimeSetSyncPeriod(otInstance *aInstance, uint16_t aTimeSyncPeriod) @@ -53,10 +54,9 @@ otError otNetworkTimeSetSyncPeriod(otInstance *aInstance, uint16_t aTimeSyncPeri otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetTimeSync().SetTimeSyncPeriod(aTimeSyncPeriod); + instance.Get().SetTimeSyncPeriod(aTimeSyncPeriod); exit: return error; @@ -66,7 +66,7 @@ uint16_t otNetworkTimeGetSyncPeriod(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetTimeSync().GetTimeSyncPeriod(); + return instance.Get().GetTimeSyncPeriod(); } otError otNetworkTimeSetXtalThreshold(otInstance *aInstance, uint16_t aXtalThreshold) @@ -74,10 +74,9 @@ otError otNetworkTimeSetXtalThreshold(otInstance *aInstance, uint16_t aXtalThres otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetTimeSync().SetXtalThreshold(aXtalThreshold); + instance.Get().SetXtalThreshold(aXtalThreshold); exit: return error; @@ -87,14 +86,14 @@ uint16_t otNetworkTimeGetXtalThreshold(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetTimeSync().GetXtalThreshold(); + return instance.Get().GetXtalThreshold(); } void otNetworkTimeSyncSetCallback(otInstance *aInstance, otNetworkTimeSyncCallbackFn aCallback, void *aCallbackContext) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetTimeSync().SetTimeSyncCallback(aCallback, aCallbackContext); + return instance.Get().SetTimeSyncCallback(aCallback, aCallbackContext); } #endif // OPENTHREAD_CONFIG_ENABLE_TIME_SYNC diff --git a/src/core/api/server_api.cpp b/src/core/api/server_api.cpp index d29bdcdbc..5ec29119c 100644 --- a/src/core/api/server_api.cpp +++ b/src/core/api/server_api.cpp @@ -38,6 +38,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -48,7 +49,7 @@ otError otServerGetNetDataLocal(otInstance *aInstance, bool aStable, uint8_t *aD VerifyOrExit(aData != NULL && aDataLength != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLocal().GetNetworkData(aStable, aData, *aDataLength); + error = instance.Get().GetNetworkData(aStable, aData, *aDataLength); exit: return error; @@ -58,10 +59,10 @@ otError otServerAddService(otInstance *aInstance, const otServiceConfig *aConfig { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().AddService( - aConfig->mEnterpriseNumber, &aConfig->mServiceData[0], aConfig->mServiceDataLength, - aConfig->mServerConfig.mStable, &aConfig->mServerConfig.mServerData[0], - aConfig->mServerConfig.mServerDataLength); + return instance.Get().AddService(aConfig->mEnterpriseNumber, &aConfig->mServiceData[0], + aConfig->mServiceDataLength, aConfig->mServerConfig.mStable, + &aConfig->mServerConfig.mServerData[0], + aConfig->mServerConfig.mServerDataLength); } otError otServerRemoveService(otInstance * aInstance, @@ -71,8 +72,7 @@ otError otServerRemoveService(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().RemoveService(aEnterpriseNumber, aServiceData, - aServiceDataLength); + return instance.Get().RemoveService(aEnterpriseNumber, aServiceData, aServiceDataLength); } otError otServerGetNextService(otInstance *aInstance, otNetworkDataIterator *aIterator, otServiceConfig *aConfig) @@ -82,7 +82,7 @@ otError otServerGetNextService(otInstance *aInstance, otNetworkDataIterator *aIt VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLocal().GetNextService(aIterator, aConfig); + error = instance.Get().GetNextService(aIterator, aConfig); exit: return error; @@ -95,7 +95,7 @@ otError otServerGetNextLeaderService(otInstance *aInstance, otNetworkDataIterato VerifyOrExit(aIterator && aConfig, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetNetworkDataLeader().GetNextService(aIterator, aConfig); + error = instance.Get().GetNextService(aIterator, aConfig); exit: return error; @@ -105,7 +105,7 @@ otError otServerRegister(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLocal().SendServerDataNotification(); + return instance.Get().SendServerDataNotification(); } #endif // OPENTHREAD_ENABLE_SERVICE diff --git a/src/core/api/sntp_api.cpp b/src/core/api/sntp_api.cpp index c4a46700b..15fb113ec 100644 --- a/src/core/api/sntp_api.cpp +++ b/src/core/api/sntp_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" using namespace ot; @@ -47,13 +48,13 @@ otError otSntpClientQuery(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetSntpClient().Query(aQuery, aHandler, aContext); + return instance.Get().Query(aQuery, aHandler, aContext); } void otSntpClientSetUnixEra(otInstance *aInstance, uint32_t aUnixEra) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetSntpClient().SetUnixEra(aUnixEra); + return instance.Get().SetUnixEra(aUnixEra); } #endif diff --git a/src/core/api/tasklet_api.cpp b/src/core/api/tasklet_api.cpp index 23900f681..eb35276ef 100644 --- a/src/core/api/tasklet_api.cpp +++ b/src/core/api/tasklet_api.cpp @@ -39,6 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" using namespace ot; @@ -48,7 +49,7 @@ void otTaskletsProcess(otInstance *aInstance) Instance &instance = *static_cast(aInstance); VerifyOrExit(otInstanceIsInitialized(aInstance)); - instance.GetTaskletScheduler().ProcessQueuedTasklets(); + instance.Get().ProcessQueuedTasklets(); exit: return; @@ -60,7 +61,7 @@ bool otTaskletsArePending(otInstance *aInstance) Instance &instance = *static_cast(aInstance); VerifyOrExit(otInstanceIsInitialized(aInstance)); - retval = instance.GetTaskletScheduler().AreTaskletsPending(); + retval = instance.Get().AreTaskletsPending(); exit: return retval; diff --git a/src/core/api/thread_api.cpp b/src/core/api/thread_api.cpp index 4c5703f9c..4da44669d 100644 --- a/src/core/api/thread_api.cpp +++ b/src/core/api/thread_api.cpp @@ -38,6 +38,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/settings.hpp" @@ -47,21 +48,21 @@ uint32_t otThreadGetChildTimeout(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetTimeout(); + return instance.Get().GetTimeout(); } void otThreadSetChildTimeout(otInstance *aInstance, uint32_t aTimeout) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetTimeout(aTimeout); + instance.Get().SetTimeout(aTimeout); } const otExtendedPanId *otThreadGetExtendedPanId(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMac().GetExtendedPanId(); + return &instance.Get().GetExtendedPanId(); } otError otThreadSetExtendedPanId(otInstance *aInstance, const otExtendedPanId *aExtendedPanId) @@ -70,19 +71,18 @@ otError otThreadSetExtendedPanId(otInstance *aInstance, const otExtendedPanId *a Instance & instance = *static_cast(aInstance); otMeshLocalPrefix prefix; - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMac().SetExtendedPanId(*aExtendedPanId); + instance.Get().SetExtendedPanId(*aExtendedPanId); prefix.m8[0] = 0xfd; memcpy(&prefix.m8[1], aExtendedPanId->m8, 5); prefix.m8[6] = 0x00; prefix.m8[7] = 0x00; - instance.GetThreadNetif().GetMle().SetMeshLocalPrefix(prefix); + instance.Get().SetMeshLocalPrefix(prefix); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -95,7 +95,7 @@ otError otThreadGetLeaderRloc(otInstance *aInstance, otIp6Address *aLeaderRloc) VerifyOrExit(aLeaderRloc != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetLeaderAddress(*static_cast(aLeaderRloc)); + error = instance.Get().GetLeaderAddress(*static_cast(aLeaderRloc)); exit: return error; @@ -105,7 +105,7 @@ otLinkModeConfig otThreadGetLinkMode(otInstance *aInstance) { otLinkModeConfig config; Instance & instance = *static_cast(aInstance); - uint8_t mode = instance.GetThreadNetif().GetMle().GetDeviceMode(); + uint8_t mode = instance.Get().GetDeviceMode(); memset(&config, 0, sizeof(otLinkModeConfig)); @@ -157,14 +157,14 @@ otError otThreadSetLinkMode(otInstance *aInstance, otLinkModeConfig aConfig) mode |= Mle::ModeTlv::kModeFullNetworkData; } - return instance.GetThreadNetif().GetMle().SetDeviceMode(mode); + return instance.Get().SetDeviceMode(mode); } const otMasterKey *otThreadGetMasterKey(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetKeyManager().GetMasterKey(); + return &instance.Get().GetMasterKey(); } otError otThreadSetMasterKey(otInstance *aInstance, const otMasterKey *aKey) @@ -173,12 +173,11 @@ otError otThreadSetMasterKey(otInstance *aInstance, const otMasterKey *aKey) Instance &instance = *static_cast(aInstance); VerifyOrExit(aKey != NULL, error = OT_ERROR_INVALID_ARGS); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - error = instance.GetThreadNetif().GetKeyManager().SetMasterKey(*aKey); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + error = instance.Get().SetMasterKey(*aKey); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -188,14 +187,14 @@ const otIp6Address *otThreadGetMeshLocalEid(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMle().GetMeshLocal64(); + return &instance.Get().GetMeshLocal64(); } const otMeshLocalPrefix *otThreadGetMeshLocalPrefix(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMle().GetMeshLocalPrefix(); + return &instance.Get().GetMeshLocalPrefix(); } otError otThreadSetMeshLocalPrefix(otInstance *aInstance, const otMeshLocalPrefix *aMeshLocalPrefix) @@ -203,12 +202,11 @@ otError otThreadSetMeshLocalPrefix(otInstance *aInstance, const otMeshLocalPrefi otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetMle().SetMeshLocalPrefix(*aMeshLocalPrefix); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + instance.Get().SetMeshLocalPrefix(*aMeshLocalPrefix); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -218,14 +216,14 @@ const otIp6Address *otThreadGetLinkLocalIp6Address(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMle().GetLinkLocalAddress(); + return &instance.Get().GetLinkLocalAddress(); } const char *otThreadGetNetworkName(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMac().GetNetworkName(); + return instance.Get().GetNetworkName(); } otError otThreadSetNetworkName(otInstance *aInstance, const char *aNetworkName) @@ -233,12 +231,11 @@ otError otThreadSetNetworkName(otInstance *aInstance, const char *aNetworkName) otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - error = instance.GetThreadNetif().GetMac().SetNetworkName(aNetworkName); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + error = instance.Get().SetNetworkName(aNetworkName); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -248,42 +245,42 @@ uint32_t otThreadGetKeySequenceCounter(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetKeyManager().GetCurrentKeySequence(); + return instance.Get().GetCurrentKeySequence(); } void otThreadSetKeySequenceCounter(otInstance *aInstance, uint32_t aKeySequenceCounter) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetKeyManager().SetCurrentKeySequence(aKeySequenceCounter); + instance.Get().SetCurrentKeySequence(aKeySequenceCounter); } uint32_t otThreadGetKeySwitchGuardTime(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetKeyManager().GetKeySwitchGuardTime(); + return instance.Get().GetKeySwitchGuardTime(); } void otThreadSetKeySwitchGuardTime(otInstance *aInstance, uint32_t aKeySwitchGuardTime) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetKeyManager().SetKeySwitchGuardTime(aKeySwitchGuardTime); + instance.Get().SetKeySwitchGuardTime(aKeySwitchGuardTime); } otError otThreadBecomeDetached(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().BecomeDetached(); + return instance.Get().BecomeDetached(); } otError otThreadBecomeChild(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().BecomeChild(Mle::kAttachAny); + return instance.Get().BecomeChild(Mle::kAttachAny); } otError otThreadGetNextNeighborInfo(otInstance *aInstance, otNeighborInfoIterator *aIterator, otNeighborInfo *aInfo) @@ -293,7 +290,7 @@ otError otThreadGetNextNeighborInfo(otInstance *aInstance, otNeighborInfoIterato VerifyOrExit((aInfo != NULL) && (aIterator != NULL), error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetNextNeighborInfo(*aIterator, *aInfo); + error = instance.Get().GetNextNeighborInfo(*aIterator, *aInfo); exit: return error; @@ -303,7 +300,7 @@ otDeviceRole otThreadGetDeviceRole(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return static_cast(instance.GetThreadNetif().GetMle().GetRole()); + return static_cast(instance.Get().GetRole()); } otError otThreadGetLeaderData(otInstance *aInstance, otLeaderData *aLeaderData) @@ -313,7 +310,7 @@ otError otThreadGetLeaderData(otInstance *aInstance, otLeaderData *aLeaderData) VerifyOrExit(aLeaderData != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetLeaderData(*aLeaderData); + error = instance.Get().GetLeaderData(*aLeaderData); exit: return error; @@ -323,28 +320,28 @@ uint8_t otThreadGetLeaderRouterId(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetLeaderRouterId(); + return instance.Get().GetLeaderDataTlv().GetLeaderRouterId(); } uint8_t otThreadGetLeaderWeight(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetWeighting(); + return instance.Get().GetLeaderDataTlv().GetWeighting(); } uint32_t otThreadGetPartitionId(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderDataTlv().GetPartitionId(); + return instance.Get().GetLeaderDataTlv().GetPartitionId(); } uint16_t otThreadGetRloc16(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetRloc16(); + return instance.Get().GetRloc16(); } otError otThreadGetParentInfo(otInstance *aInstance, otRouterInfo *aParentInfo) @@ -355,7 +352,7 @@ otError otThreadGetParentInfo(otInstance *aInstance, otRouterInfo *aParentInfo) VerifyOrExit(aParentInfo != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); + parent = instance.Get().GetParent(); aParentInfo->mExtAddress = parent->GetExtAddress(); aParentInfo->mRloc16 = parent->GetRloc16(); aParentInfo->mRouterId = Mle::Mle::GetRouterId(parent->GetRloc16()); @@ -379,7 +376,7 @@ otError otThreadGetParentAverageRssi(otInstance *aInstance, int8_t *aParentRssi) VerifyOrExit(aParentRssi != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); + parent = instance.Get().GetParent(); *aParentRssi = parent->GetLinkInfo().GetAverageRss(); VerifyOrExit(*aParentRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED); @@ -396,7 +393,7 @@ otError otThreadGetParentLastRssi(otInstance *aInstance, int8_t *aLastRssi) VerifyOrExit(aLastRssi != NULL, error = OT_ERROR_INVALID_ARGS); - parent = instance.GetThreadNetif().GetMle().GetParent(); + parent = instance.Get().GetParent(); *aLastRssi = parent->GetLinkInfo().GetLastRss(); VerifyOrExit(*aLastRssi != OT_RADIO_RSSI_INVALID, error = OT_ERROR_FAILED); @@ -412,7 +409,7 @@ void otThreadSetReceiveDiagnosticGetCallback(otInstance * aIns { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetNetworkDiagnostic().SetReceiveDiagnosticGetCallback(aCallback, aCallbackContext); + instance.Get().SetReceiveDiagnosticGetCallback(aCallback, aCallbackContext); } otError otThreadSendDiagnosticGet(otInstance * aInstance, @@ -422,7 +419,7 @@ otError otThreadSendDiagnosticGet(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticGet( + return instance.Get().SendDiagnosticGet( *static_cast(aDestination), aTlvTypes, aCount); } @@ -433,7 +430,7 @@ otError otThreadSendDiagnosticReset(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDiagnostic().SendDiagnosticReset( + return instance.Get().SendDiagnosticReset( *static_cast(aDestination), aTlvTypes, aCount); } #endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC @@ -445,13 +442,12 @@ otError otThreadSetEnabled(otInstance *aInstance, bool aEnabled) if (aEnabled) { - VerifyOrExit(instance.GetThreadNetif().GetMac().GetPanId() != Mac::kPanIdBroadcast, - error = OT_ERROR_INVALID_STATE); - error = instance.GetThreadNetif().GetMle().Start(/* aAnnounceAttach */ false); + VerifyOrExit(instance.Get().GetPanId() != Mac::kPanIdBroadcast, error = OT_ERROR_INVALID_STATE); + error = instance.Get().Start(/* aAnnounceAttach */ false); } else { - instance.GetThreadNetif().GetMle().Stop(true); + instance.Get().Stop(true); } exit: @@ -464,7 +460,7 @@ bool otThreadGetAutoStart(otInstance *aInstance) uint8_t autoStart = 0; Instance &instance = *static_cast(aInstance); - if (instance.GetSettings().ReadThreadAutoStart(autoStart) != OT_ERROR_NONE) + if (instance.Get().ReadThreadAutoStart(autoStart) != OT_ERROR_NONE) { autoStart = 0; } @@ -482,7 +478,7 @@ otError otThreadSetAutoStart(otInstance *aInstance, bool aStartAutomatically) uint8_t autoStart = aStartAutomatically ? 1 : 0; Instance &instance = *static_cast(aInstance); - return instance.GetSettings().SaveThreadAutoStart(autoStart); + return instance.Get().SaveThreadAutoStart(autoStart); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aStartAutomatically); @@ -494,7 +490,7 @@ bool otThreadIsSingleton(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().IsSingleton(); + return instance.Get().IsSingleton(); } otError otThreadDiscover(otInstance * aInstance, @@ -507,36 +503,36 @@ otError otThreadDiscover(otInstance * aInstance, { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().Discover(static_cast(aScanChannels), aPanId, aJoiner, - aEnableEui64Filtering, aCallback, aCallbackContext); + return instance.Get().Discover(static_cast(aScanChannels), aPanId, aJoiner, + aEnableEui64Filtering, aCallback, aCallbackContext); } bool otThreadIsDiscoverInProgress(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().IsDiscoverInProgress(); + return instance.Get().IsDiscoverInProgress(); } const otIpCounters *otThreadGetIp6Counters(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMeshForwarder().GetCounters(); + return &instance.Get().GetCounters(); } const otMleCounters *otThreadGetMleCounters(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return &instance.GetThreadNetif().GetMle().GetCounters(); + return &instance.Get().GetCounters(); } void otThreadResetMleCounters(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().ResetCounters(); + instance.Get().ResetCounters(); } otError otThreadRegisterParentResponseCallback(otInstance * aInstance, @@ -546,7 +542,7 @@ otError otThreadRegisterParentResponseCallback(otInstance * aI #if OPENTHREAD_FTD || OPENTHREAD_MTD Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().RegisterParentResponseStatsCallback(aCallback, aContext); + instance.Get().RegisterParentResponseStatsCallback(aCallback, aContext); return OT_ERROR_NONE; #else diff --git a/src/core/api/thread_ftd_api.cpp b/src/core/api/thread_ftd_api.cpp index 4e8c6c594..7ba22e1a9 100644 --- a/src/core/api/thread_ftd_api.cpp +++ b/src/core/api/thread_ftd_api.cpp @@ -40,6 +40,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "thread/mle_constants.hpp" #include "thread/topology.hpp" @@ -49,77 +50,77 @@ uint8_t otThreadGetMaxAllowedChildren(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetChildTable().GetMaxChildrenAllowed(); + return instance.Get().GetMaxChildrenAllowed(); } otError otThreadSetMaxAllowedChildren(otInstance *aInstance, uint8_t aMaxChildren) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetChildTable().SetMaxChildrenAllowed(aMaxChildren); + return instance.Get().SetMaxChildrenAllowed(aMaxChildren); } bool otThreadIsRouterRoleEnabled(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().IsRouterRoleEnabled(); + return instance.Get().IsRouterRoleEnabled(); } void otThreadSetRouterRoleEnabled(otInstance *aInstance, bool aEnabled) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetRouterRoleEnabled(aEnabled); + instance.Get().SetRouterRoleEnabled(aEnabled); } otError otThreadSetPreferredRouterId(otInstance *aInstance, uint8_t aRouterId) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().SetPreferredRouterId(aRouterId); + return instance.Get().SetPreferredRouterId(aRouterId); } uint8_t otThreadGetLocalLeaderWeight(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderWeight(); + return instance.Get().GetLeaderWeight(); } void otThreadSetLocalLeaderWeight(otInstance *aInstance, uint8_t aWeight) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetLeaderWeight(aWeight); + instance.Get().SetLeaderWeight(aWeight); } uint32_t otThreadGetLocalLeaderPartitionId(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetLeaderPartitionId(); + return instance.Get().GetLeaderPartitionId(); } void otThreadSetLocalLeaderPartitionId(otInstance *aInstance, uint32_t aPartitionId) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().SetLeaderPartitionId(aPartitionId); + return instance.Get().SetLeaderPartitionId(aPartitionId); } uint16_t otThreadGetJoinerUdpPort(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetJoinerRouter().GetJoinerUdpPort(); + return instance.Get().GetJoinerUdpPort(); } otError otThreadSetJoinerUdpPort(otInstance *aInstance, uint16_t aJoinerUdpPort) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetJoinerRouter().SetJoinerUdpPort(aJoinerUdpPort); + instance.Get().SetJoinerUdpPort(aJoinerUdpPort); return OT_ERROR_NONE; } @@ -128,42 +129,42 @@ uint32_t otThreadGetContextIdReuseDelay(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetNetworkDataLeader().GetContextIdReuseDelay(); + return instance.Get().GetContextIdReuseDelay(); } void otThreadSetContextIdReuseDelay(otInstance *aInstance, uint32_t aDelay) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetNetworkDataLeader().SetContextIdReuseDelay(aDelay); + instance.Get().SetContextIdReuseDelay(aDelay); } uint8_t otThreadGetNetworkIdTimeout(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetNetworkIdTimeout(); + return instance.Get().GetNetworkIdTimeout(); } void otThreadSetNetworkIdTimeout(otInstance *aInstance, uint8_t aTimeout) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetNetworkIdTimeout(aTimeout); + instance.Get().SetNetworkIdTimeout(aTimeout); } uint8_t otThreadGetRouterUpgradeThreshold(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetRouterUpgradeThreshold(); + return instance.Get().GetRouterUpgradeThreshold(); } void otThreadSetRouterUpgradeThreshold(otInstance *aInstance, uint8_t aThreshold) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetRouterUpgradeThreshold(aThreshold); + instance.Get().SetRouterUpgradeThreshold(aThreshold); } otError otThreadReleaseRouterId(otInstance *aInstance, uint8_t aRouterId) @@ -173,7 +174,7 @@ otError otThreadReleaseRouterId(otInstance *aInstance, uint8_t aRouterId) VerifyOrExit(aRouterId <= Mle::kMaxRouterId, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetRouterTable().Release(aRouterId); + error = instance.Get().Release(aRouterId); exit: return error; @@ -184,14 +185,14 @@ otError otThreadBecomeRouter(otInstance *aInstance) otError error = OT_ERROR_INVALID_STATE; Instance &instance = *static_cast(aInstance); - switch (instance.GetThreadNetif().GetMle().GetRole()) + switch (instance.Get().GetRole()) { case OT_DEVICE_ROLE_DISABLED: case OT_DEVICE_ROLE_DETACHED: break; case OT_DEVICE_ROLE_CHILD: - error = instance.GetThreadNetif().GetMle().BecomeRouter(ThreadStatusTlv::kHaveChildIdRequest); + error = instance.Get().BecomeRouter(ThreadStatusTlv::kHaveChildIdRequest); break; case OT_DEVICE_ROLE_ROUTER: @@ -207,35 +208,35 @@ otError otThreadBecomeLeader(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().BecomeLeader(); + return instance.Get().BecomeLeader(); } uint8_t otThreadGetRouterDowngradeThreshold(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetRouterDowngradeThreshold(); + return instance.Get().GetRouterDowngradeThreshold(); } void otThreadSetRouterDowngradeThreshold(otInstance *aInstance, uint8_t aThreshold) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetRouterDowngradeThreshold(aThreshold); + instance.Get().SetRouterDowngradeThreshold(aThreshold); } uint8_t otThreadGetRouterSelectionJitter(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetRouterSelectionJitter(); + return instance.Get().GetRouterSelectionJitter(); } void otThreadSetRouterSelectionJitter(otInstance *aInstance, uint8_t aRouterJitter) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetRouterSelectionJitter(aRouterJitter); + instance.Get().SetRouterSelectionJitter(aRouterJitter); } otError otThreadGetChildInfoById(otInstance *aInstance, uint16_t aChildId, otChildInfo *aChildInfo) @@ -245,7 +246,7 @@ otError otThreadGetChildInfoById(otInstance *aInstance, uint16_t aChildId, otChi VerifyOrExit(aChildInfo != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetChildInfoById(aChildId, *aChildInfo); + error = instance.Get().GetChildInfoById(aChildId, *aChildInfo); exit: return error; @@ -258,7 +259,7 @@ otError otThreadGetChildInfoByIndex(otInstance *aInstance, uint8_t aChildIndex, VerifyOrExit(aChildInfo != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetChildInfoByIndex(aChildIndex, *aChildInfo); + error = instance.Get().GetChildInfoByIndex(aChildIndex, *aChildInfo); exit: return error; @@ -279,7 +280,7 @@ otError otThreadGetChildNextIp6Address(otInstance * aInstance, address = static_cast(aAddress); iterator.Set(*aIterator); - SuccessOrExit(error = instance.GetThreadNetif().GetMle().GetChildNextIp6Address(aChildIndex, iterator, *address)); + SuccessOrExit(error = instance.Get().GetChildNextIp6Address(aChildIndex, iterator, *address)); *aIterator = iterator.Get(); @@ -291,7 +292,7 @@ uint8_t otThreadGetRouterIdSequence(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetRouterTable().GetRouterIdSequence(); + return instance.Get().GetRouterIdSequence(); } uint8_t otThreadGetMaxRouterId(otInstance *aInstance) @@ -307,7 +308,7 @@ otError otThreadGetRouterInfo(otInstance *aInstance, uint16_t aRouterId, otRoute VerifyOrExit(aRouterInfo != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetMle().GetRouterTable().GetRouterInfo(aRouterId, *aRouterInfo); + error = instance.Get().GetRouterInfo(aRouterId, *aRouterInfo); exit: return error; @@ -319,7 +320,7 @@ otError otThreadGetEidCacheEntry(otInstance *aInstance, uint8_t aIndex, otEidCac Instance &instance = *static_cast(aInstance); VerifyOrExit(aEntry != NULL, error = OT_ERROR_INVALID_ARGS); - error = instance.GetThreadNetif().GetAddressResolver().GetEntry(aIndex, *aEntry); + error = instance.Get().GetEntry(aIndex, *aEntry); exit: return error; @@ -332,7 +333,7 @@ otError otThreadSetSteeringData(otInstance *aInstance, const otExtAddress *aExtA #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB Instance &instance = *static_cast(aInstance); - error = instance.GetThreadNetif().GetMle().SetSteeringData(static_cast(aExtAddress)); + error = instance.Get().SetSteeringData(static_cast(aExtAddress)); #else OT_UNUSED_VARIABLE(aInstance); OT_UNUSED_VARIABLE(aExtAddress); @@ -347,7 +348,7 @@ const uint8_t *otThreadGetPSKc(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetKeyManager().GetPSKc(); + return instance.Get().GetPSKc(); } otError otThreadSetPSKc(otInstance *aInstance, const uint8_t *aPSKc) @@ -355,12 +356,11 @@ otError otThreadSetPSKc(otInstance *aInstance, const uint8_t *aPSKc) otError error = OT_ERROR_NONE; Instance &instance = *static_cast(aInstance); - VerifyOrExit(instance.GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, - error = OT_ERROR_INVALID_STATE); + VerifyOrExit(instance.Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - instance.GetThreadNetif().GetKeyManager().SetPSKc(aPSKc); - instance.GetThreadNetif().GetActiveDataset().Clear(); - instance.GetThreadNetif().GetPendingDataset().Clear(); + instance.Get().SetPSKc(aPSKc); + instance.Get().Clear(); + instance.Get().Clear(); exit: return error; @@ -370,28 +370,28 @@ int8_t otThreadGetParentPriority(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetAssignParentPriority(); + return instance.Get().GetAssignParentPriority(); } otError otThreadSetParentPriority(otInstance *aInstance, const int8_t aParentPriority) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().SetAssignParentPriority(aParentPriority); + return instance.Get().SetAssignParentPriority(aParentPriority); } otThreadChildTableCallback otThreadGetChildTableCallback(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.GetThreadNetif().GetMle().GetChildTableChangedCallback(); + return instance.Get().GetChildTableChangedCallback(); } void otThreadSetChildTableCallback(otInstance *aInstance, otThreadChildTableCallback aCallback) { Instance &instance = *static_cast(aInstance); - instance.GetThreadNetif().GetMle().SetChildTableChangedCallback(aCallback); + instance.Get().SetChildTableChangedCallback(aCallback); } #endif // OPENTHREAD_FTD diff --git a/src/core/api/udp_api.cpp b/src/core/api/udp_api.cpp index 8947a4765..785a1ef5d 100644 --- a/src/core/api/udp_api.cpp +++ b/src/core/api/udp_api.cpp @@ -36,6 +36,7 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/new.hpp" #include "net/udp6.hpp" @@ -51,7 +52,7 @@ otMessage *otUdpNewMessage(otInstance *aInstance, const otMessageSettings *aSett VerifyOrExit(aSettings->mPriority <= OT_MESSAGE_PRIORITY_HIGH, message = NULL); } - message = instance.GetIp6().GetUdp().NewMessage(0, aSettings); + message = instance.Get().NewMessage(0, aSettings); exit: return message; @@ -61,7 +62,7 @@ otError otUdpOpen(otInstance *aInstance, otUdpSocket *aSocket, otUdpReceive aCal { otError error = OT_ERROR_INVALID_ARGS; Instance & instance = *static_cast(aInstance); - Ip6::UdpSocket &socket = *new (aSocket) Ip6::UdpSocket(instance.GetIp6().GetUdp()); + Ip6::UdpSocket &socket = *new (aSocket) Ip6::UdpSocket(instance.Get()); error = socket.Open(aCallback, aContext); @@ -100,9 +101,8 @@ otError otUdpSend(otUdpSocket *aSocket, otMessage *aMessage, const otMessageInfo void otUdpForwardSetForwarder(otInstance *aInstance, otUdpForwarder aForwarder, void *aContext) { Instance &instance = *static_cast(aInstance); - Ip6::Ip6 &ip6 = instance.Get(); - ip6.GetUdp().SetUdpForwarder(aForwarder, aContext); + instance.Get().SetUdpForwarder(aForwarder, aContext); } void otUdpForwardReceive(otInstance * aInstance, @@ -113,17 +113,16 @@ void otUdpForwardReceive(otInstance * aInstance, { Ip6::MessageInfo messageInfo; Instance & instance = *static_cast(aInstance); - Ip6::Ip6 & ip6 = instance.Get(); assert(aMessage != NULL && aPeerAddr != NULL); - messageInfo.SetSockAddr(instance.GetThreadNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(instance.Get().GetMeshLocal16()); messageInfo.SetSockPort(aSockPort); messageInfo.SetPeerAddr(*static_cast(aPeerAddr)); messageInfo.SetPeerPort(aPeerPort); messageInfo.SetInterfaceId(OT_NETIF_INTERFACE_ID_HOST); - ip6.GetUdp().HandlePayload(*static_cast(aMessage), messageInfo); + instance.Get().HandlePayload(*static_cast(aMessage), messageInfo); static_cast(aMessage)->Free(); } @@ -134,7 +133,7 @@ otUdpSocket *otUdpGetSockets(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.Get().GetUdp().GetUdpSockets(); + return instance.Get().GetUdpSockets(); } #endif @@ -142,12 +141,12 @@ otError otUdpAddReceiver(otInstance *aInstance, otUdpReceiver *aUdpReceiver) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetUdp().AddReceiver(*static_cast(aUdpReceiver)); + return instance.Get().AddReceiver(*static_cast(aUdpReceiver)); } otError otUdpRemoveReceiver(otInstance *aInstance, otUdpReceiver *aUdpReceiver) { Instance &instance = *static_cast(aInstance); - return instance.GetIp6().GetUdp().RemoveReceiver(*static_cast(aUdpReceiver)); + return instance.Get().RemoveReceiver(*static_cast(aUdpReceiver)); } diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 82ce9fa4d..94a182162 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -33,8 +33,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "net/ip6.hpp" #include "net/udp6.hpp" @@ -129,7 +129,7 @@ Message *CoapBase::NewMessage(const otMessageSettings *aSettings) { Message *message = NULL; - VerifyOrExit((message = static_cast(GetInstance().GetIp6().GetUdp().NewMessage(0, aSettings))) != NULL); + VerifyOrExit((message = static_cast(Get().NewMessage(0, aSettings))) != NULL); message->SetOffset(0); exit: @@ -302,7 +302,7 @@ void CoapBase::HandleRetransmissionTimer(void) messageInfo.SetPeerAddr(coapMetadata.mDestinationAddress); messageInfo.SetPeerPort(coapMetadata.mDestinationPort); messageInfo.SetSockAddr(coapMetadata.mSourceAddress); - messageInfo.SetInterfaceId(GetNetif().GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); SendCopy(*message, messageInfo); } @@ -843,7 +843,7 @@ uint32_t EnqueuedResponseHeader::GetRemainingTime(void) const Coap::Coap(Instance &aInstance) : CoapBase(aInstance, &Coap::Send) - , mSocket(aInstance.GetIp6().GetUdp()) + , mSocket(aInstance.Get()) { } diff --git a/src/core/coap/coap_secure.cpp b/src/core/coap/coap_secure.cpp index cd5adb426..576fb5ae0 100644 --- a/src/core/coap/coap_secure.cpp +++ b/src/core/coap/coap_secure.cpp @@ -31,9 +31,9 @@ #include "coap_secure.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/new.hpp" -#include "common/owner-locator.hpp" #include "meshcop/dtls.hpp" #include "thread/thread_netif.hpp" @@ -219,8 +219,7 @@ void CoapSecure::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength) { ot::Message *message = NULL; - VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kTypeIp6, Message::GetHelpDataReserved())) != - NULL); + VerifyOrExit((message = Get().New(Message::kTypeIp6, Message::GetHelpDataReserved())) != NULL); SuccessOrExit(message->Append(aBuf, aLength)); CoapBase::Receive(*message, mDtls.GetPeerAddress()); diff --git a/src/core/common/instance.cpp b/src/core/common/instance.cpp index 6063001dc..788d427d7 100644 --- a/src/core/common/instance.cpp +++ b/src/core/common/instance.cpp @@ -46,7 +46,7 @@ namespace ot { #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES // Define the raw storage used for OpenThread instance (in single-instance case). -static otDEFINE_ALIGNED_VAR(sInstanceRaw, sizeof(Instance), uint64_t); +otDEFINE_ALIGNED_VAR(gInstanceRaw, sizeof(Instance), uint64_t); #endif @@ -102,7 +102,7 @@ Instance &Instance::InitSingle(void) VerifyOrExit(instance->mIsInitialized == false); - instance = new (&sInstanceRaw) Instance(); + instance = new (&gInstanceRaw) Instance(); instance->AfterInit(); @@ -112,7 +112,7 @@ exit: Instance &Instance::Get(void) { - void *instance = &sInstanceRaw; + void *instance = &gInstanceRaw; return *static_cast(instance); } @@ -152,8 +152,8 @@ void Instance::AfterInit(void) // Restore datasets and network information - GetSettings().Init(); - mThreadNetif.GetMle().Restore(); + Get().Init(); + Get().Restore(); #if OPENTHREAD_CONFIG_ENABLE_AUTO_START_SUPPORT @@ -174,7 +174,7 @@ void Instance::AfterInit(void) #endif // OPENTHREAD_MTD || OPENTHREAD_FTD #if OPENTHREAD_ENABLE_VENDOR_EXTENSION - GetExtension().SignalInstanceInit(); + Get().SignalInstanceInit(); #endif } @@ -197,7 +197,7 @@ exit: #if OPENTHREAD_MTD || OPENTHREAD_FTD void Instance::FactoryReset(void) { - GetSettings().Wipe(); + Get().Wipe(); otPlatReset(this); } @@ -205,8 +205,8 @@ otError Instance::ErasePersistentInfo(void) { otError error = OT_ERROR_NONE; - VerifyOrExit(mThreadNetif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); - GetSettings().Wipe(); + VerifyOrExit(Get().GetRole() == OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); + Get().Wipe(); exit: return error; diff --git a/src/core/common/instance.hpp b/src/core/common/instance.hpp index f2e0b0843..f6ccda378 100644 --- a/src/core/common/instance.hpp +++ b/src/core/common/instance.hpp @@ -154,32 +154,6 @@ public: */ void Reset(void); - /** - * This method returns a reference to the timer milli scheduler object. - * - * @returns A reference to the timer milli scheduler object. - * - */ - TimerMilliScheduler &GetTimerMilliScheduler(void) { return mTimerMilliScheduler; } - -#if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER - /** - * This method returns a reference to the timer micro scheduler object. - * - * @returns A reference to the timer micro scheduler object. - * - */ - TimerMicroScheduler &GetTimerMicroScheduler(void) { return mTimerMicroScheduler; } -#endif - - /** - * This method returns a reference to the tasklet scheduler object. - * - * @returns A reference to the tasklet scheduler object. - * - */ - TaskletScheduler &GetTaskletScheduler(void) { return mTaskletScheduler; } - /** * This method returns the active log level. * @@ -271,22 +245,6 @@ public: */ void InvokeEnergyScanCallback(otEnergyScanResult *aResult) const; - /** - * This method returns a reference to the `Notifier` object. - * - * @returns A reference to the `Notifier` object. - * - */ - Notifier &GetNotifier(void) { return mNotifier; } - - /** - * This method returns a reference to the `Settings` object. - * - * @returns A reference to the `Settings` object. - * - */ - Settings &GetSettings(void) { return mSettings; } - #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES /** * This method returns a reference to the Heap object. @@ -297,22 +255,6 @@ public: Utils::Heap &GetHeap(void) { return mHeap; } #endif - /** - * This method returns a reference to the Ip6 object. - * - * @returns A reference to the Ip6 object. - * - */ - Ip6::Ip6 &GetIp6(void) { return mIp6; } - - /** - * This method returns a reference to the Thread Netif object. - * - * @returns A reference to the Thread Netif object. - * - */ - ThreadNetif &GetThreadNetif(void) { return mThreadNetif; } - #if OPENTHREAD_ENABLE_APPLICATION_COAP /** * This method returns a reference to application COAP object. @@ -333,66 +275,8 @@ public: Coap::CoapSecure &GetApplicationCoapSecure(void) { return mApplicationCoapSecure; } #endif -#if OPENTHREAD_ENABLE_CHANNEL_MONITOR - /** - * This method returns a reference to ChannelMonitor object. - * - * @returns A reference to the ChannelMonitor object. - * - */ - Utils::ChannelMonitor &GetChannelMonitor(void) { return mChannelMonitor; } -#endif - -#if OPENTHREAD_ENABLE_CHANNEL_MANAGER - /** - * This method returns a reference to ChannelManager object. - * - * @returns A reference to the ChannelManager object. - * - */ - Utils::ChannelManager &GetChannelManager(void) { return mChannelManager; } -#endif - -#if OPENTHREAD_CONFIG_ENABLE_ANNOUNCE_SENDER - /** - * This method returns a reference to AnnounceSender object. - * - * @returns A reference to the AnnounceSender object. - * - */ - AnnounceSender &GetAnnounceSender(void) { return mAnnounceSender; } -#endif - - /** - * This method returns a reference to message pool object. - * - * @returns A reference to the message pool object. - * - */ - MessagePool &GetMessagePool(void) { return mMessagePool; } - -#if OPENTHREAD_ENABLE_VENDOR_EXTENSION - /** - * This method returns a reference to vendor extension object. - * - * @returns A reference to the vendor extension object. - * - */ - Extension::ExtensionBase &GetExtension(void) { return mExtension; } -#endif - #endif // OPENTHREAD_MTD || OPENTHREAD_FTD -#if OPENTHREAD_RADIO || OPENTHREAD_ENABLE_RAW_LINK_API - /** - * This method returns a reference to LinkRaw object. - * - * @returns A reference to the LinkRaw object. - * - */ - Mac::LinkRaw &GetLinkRaw(void) { return mLinkRaw; } -#endif - /** * This template method returns a reference to a given `Type` object belonging to the OpenThread instance. * @@ -402,9 +286,6 @@ public: * `Instance` through the member variable property hierarchy. * * Specializations of the `Get()` method are defined in this file after the `Instance` class definition. - * The specializations should be defined for any `Type` that can use `GetOwner` method, i.e., any - * `Type` that is an owner of a callback providing object such as a `Timer`,`Tasklet`, or any sub-class of - *`OwnerLocator`. * * @returns A reference to the `Type` object of the instance. * @@ -480,227 +361,307 @@ private: #if OPENTHREAD_MTD || OPENTHREAD_FTD template <> inline Notifier &Instance::Get(void) { - return GetNotifier(); + return mNotifier; +} + +template <> inline Settings &Instance::Get(void) +{ + return mSettings; } template <> inline MeshForwarder &Instance::Get(void) { - return GetThreadNetif().GetMeshForwarder(); + return mThreadNetif.mMeshForwarder; } template <> inline Mle::Mle &Instance::Get(void) { - return GetThreadNetif().GetMle(); + return mThreadNetif.mMleRouter; } template <> inline Mle::MleRouter &Instance::Get(void) { - return GetThreadNetif().GetMle(); + return mThreadNetif.mMleRouter; } template <> inline ChildTable &Instance::Get(void) { - return GetThreadNetif().GetMle().GetChildTable(); + return mThreadNetif.mMleRouter.mChildTable; } template <> inline RouterTable &Instance::Get(void) { - return GetThreadNetif().GetMle().GetRouterTable(); + return mThreadNetif.mMleRouter.mRouterTable; } template <> inline Ip6::Netif &Instance::Get(void) { - return GetThreadNetif(); + return mThreadNetif; +} + +template <> inline ThreadNetif &Instance::Get(void) +{ + return mThreadNetif; } template <> inline Ip6::Ip6 &Instance::Get(void) { - return GetIp6(); + return mIp6; } template <> inline Mac::Mac &Instance::Get(void) { - return GetThreadNetif().GetMac(); + return mThreadNetif.mMac; } template <> inline Mac::SubMac &Instance::Get(void) { - return GetThreadNetif().GetMac().GetSubMac(); + return mThreadNetif.mMac.mSubMac; +} + +#if OPENTHREAD_ENABLE_MAC_FILTER +template <> inline Mac::Filter &Instance::Get(void) +{ + return mThreadNetif.mMac.mFilter; +} +#endif + +template <> inline Lowpan::Lowpan &Instance::Get(void) +{ + return mThreadNetif.mLowpan; } template <> inline KeyManager &Instance::Get(void) { - return GetThreadNetif().GetKeyManager(); + return mThreadNetif.mKeyManager; +} + +template <> inline Ip6::Filter &Instance::Get(void) +{ + return mThreadNetif.mIp6Filter; } #if OPENTHREAD_FTD +template <> inline SourceMatchController &Instance::Get(void) +{ + return mThreadNetif.mMeshForwarder.mSourceMatchController; +} + template <> inline AddressResolver &Instance::Get(void) { - return GetThreadNetif().GetAddressResolver(); + return mThreadNetif.mAddressResolver; } template <> inline MeshCoP::Leader &Instance::Get(void) { - return GetThreadNetif().GetLeader(); + return mThreadNetif.mLeader; } template <> inline MeshCoP::JoinerRouter &Instance::Get(void) { - return GetThreadNetif().GetJoinerRouter(); + return mThreadNetif.mJoinerRouter; } #endif // OPENTHREAD_FTD template <> inline AnnounceBeginServer &Instance::Get(void) { - return GetThreadNetif().GetAnnounceBeginServer(); + return mThreadNetif.mAnnounceBegin; } template <> inline DataPollManager &Instance::Get(void) { - return GetThreadNetif().GetMeshForwarder().GetDataPollManager(); + return mThreadNetif.mMeshForwarder.mDataPollManager; } template <> inline EnergyScanServer &Instance::Get(void) { - return GetThreadNetif().GetEnergyScanServer(); + return mThreadNetif.mEnergyScan; } template <> inline PanIdQueryServer &Instance::Get(void) { - return GetThreadNetif().GetPanIdQueryServer(); + return mThreadNetif.mPanIdQuery; } +#if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE +template <> inline NetworkData::Local &Instance::Get(void) +{ + return mThreadNetif.mNetworkDataLocal; +} +#endif + template <> inline NetworkData::Leader &Instance::Get(void) { - return GetThreadNetif().GetNetworkDataLeader(); + return mThreadNetif.mNetworkDataLeader; +} + +template <> inline Ip6::Routes &Instance::Get(void) +{ + return mIp6.mRoutes; +} + +template <> inline Ip6::Udp &Instance::Get(void) +{ + return mIp6.mUdp; +} + +template <> inline Ip6::Icmp &Instance::Get(void) +{ + return mIp6.mIcmp; } template <> inline Ip6::Mpl &Instance::Get(void) { - return GetIp6().GetMpl(); + return mIp6.mMpl; } template <> inline Coap::Coap &Instance::Get(void) { - return GetThreadNetif().GetCoap(); + return mThreadNetif.mCoap; } +#if OPENTHREAD_ENABLE_DTLS +template <> inline Coap::CoapSecure &Instance::Get(void) +{ + return mThreadNetif.mCoapSecure; +} +#endif + template <> inline MeshCoP::ActiveDataset &Instance::Get(void) { - return GetThreadNetif().GetActiveDataset(); + return mThreadNetif.mActiveDataset; } template <> inline MeshCoP::PendingDataset &Instance::Get(void) { - return GetThreadNetif().GetPendingDataset(); + return mThreadNetif.mPendingDataset; } #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC template <> inline TimeSync &Instance::Get(void) { - return GetThreadNetif().GetTimeSync(); + return mThreadNetif.mTimeSync; } #endif #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD template <> inline MeshCoP::Commissioner &Instance::Get(void) { - return GetThreadNetif().GetCommissioner(); + return mThreadNetif.mCommissioner; } #endif #if OPENTHREAD_ENABLE_JOINER template <> inline MeshCoP::Joiner &Instance::Get(void) { - return GetThreadNetif().GetJoiner(); + return mThreadNetif.mJoiner; } #endif #if OPENTHREAD_ENABLE_DNS_CLIENT template <> inline Dns::Client &Instance::Get(void) { - return GetThreadNetif().GetDnsClient(); + return mThreadNetif.mDnsClient; +} +#endif + +#if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC +template <> inline NetworkDiagnostic::NetworkDiagnostic &Instance::Get(void) +{ + return mThreadNetif.mNetworkDiagnostic; } #endif #if OPENTHREAD_ENABLE_DHCP6_CLIENT template <> inline Dhcp6::Dhcp6Client &Instance::Get(void) { - return GetThreadNetif().GetDhcp6Client(); + return mThreadNetif.mDhcp6Client; +} +#endif + +#if OPENTHREAD_ENABLE_DHCP6_SERVER +template <> inline Dhcp6::Dhcp6Server &Instance::Get(void) +{ + return mThreadNetif.mDhcp6Server; } #endif #if OPENTHREAD_CONFIG_ENABLE_SLAAC template <> inline Utils::Slaac &Instance::Get(void) { - return GetThreadNetif().GetSlaac(); + return mThreadNetif.mSlaac; } #endif #if OPENTHREAD_ENABLE_JAM_DETECTION template <> inline Utils::JamDetector &Instance::Get(void) { - return GetThreadNetif().GetJamDetector(); + return mThreadNetif.mJamDetector; } #endif #if OPENTHREAD_ENABLE_SNTP_CLIENT template <> inline Sntp::Client &Instance::Get(void) { - return GetThreadNetif().GetSntpClient(); + return mThreadNetif.mSntpClient; } #endif template <> inline Utils::ChildSupervisor &Instance::Get(void) { - return GetThreadNetif().GetChildSupervisor(); + return mThreadNetif.mChildSupervisor; } template <> inline Utils::SupervisionListener &Instance::Get(void) { - return GetThreadNetif().GetSupervisionListener(); + return mThreadNetif.mSupervisionListener; } #if OPENTHREAD_ENABLE_CHANNEL_MONITOR template <> inline Utils::ChannelMonitor &Instance::Get(void) { - return GetChannelMonitor(); + return mChannelMonitor; } #endif #if OPENTHREAD_ENABLE_CHANNEL_MANAGER template <> inline Utils::ChannelManager &Instance::Get(void) { - return GetChannelManager(); + return mChannelManager; } #endif #if OPENTHREAD_ENABLE_BORDER_AGENT template <> inline MeshCoP::BorderAgent &Instance::Get(void) { - return GetThreadNetif().GetBorderAgent(); + return mThreadNetif.mBorderAgent; } #endif #if OPENTHREAD_CONFIG_ENABLE_ANNOUNCE_SENDER template <> inline AnnounceSender &Instance::Get(void) { - return GetAnnounceSender(); + return mAnnounceSender; } #endif +template <> inline MessagePool &Instance::Get(void) +{ + return mMessagePool; +} + #endif // OPENTHREAD_MTD || OPENTHREAD_FTD #if OPENTHREAD_RADIO || OPENTHREAD_ENABLE_RAW_LINK_API template <> inline Mac::LinkRaw &Instance::Get(void) { - return GetLinkRaw(); + return mLinkRaw; } #if OPENTHREAD_RADIO template <> inline Mac::SubMac &Instance::Get(void) { - return GetLinkRaw().GetSubMac(); + return mLinkRaw.mSubMac; } #endif @@ -708,13 +669,25 @@ template <> inline Mac::SubMac &Instance::Get(void) template <> inline TaskletScheduler &Instance::Get(void) { - return GetTaskletScheduler(); + return mTaskletScheduler; } +template <> inline TimerMilliScheduler &Instance::Get(void) +{ + return mTimerMilliScheduler; +} + +#if OPENTHREAD_CONFIG_ENABLE_PLATFORM_USEC_TIMER +template <> inline TimerMicroScheduler &Instance::Get(void) +{ + return mTimerMicroScheduler; +} +#endif + #if OPENTHREAD_ENABLE_VENDOR_EXTENSION template <> inline Extension::ExtensionBase &Instance::Get(void) { - return GetExtension(); + return mExtension; } #endif diff --git a/src/core/common/owner-locator.hpp b/src/core/common/locator-getters.hpp similarity index 76% rename from src/core/common/owner-locator.hpp rename to src/core/common/locator-getters.hpp index 608da5c18..7e22a9851 100644 --- a/src/core/common/owner-locator.hpp +++ b/src/core/common/locator-getters.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, The OpenThread Authors. + * Copyright (c) 2017-2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -28,11 +28,12 @@ /** * @file - * This file includes definitions for owner locator. + * This file includes definitions locator getter methods. + * */ -#ifndef OWNER_LOCATOR_HPP_ -#define OWNER_LOCATOR_HPP_ +#ifndef LOCATOR_GETTERS_HPP_ +#define LOCATOR_GETTERS_HPP_ #include "openthread-core-config.h" @@ -41,20 +42,31 @@ namespace ot { -#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES +/** + * This method returns a reference to the parent OpenThread Instance. + * + * This definition is a specialization of template `Get` for `Get()`, + * + * @returns A reference to `Instance` object. + * + */ +template <> inline Instance &InstanceLocator::Get(void) const +{ + return GetInstance(); +} -template OwnerType &OwnerLocator::GetOwner(void) +template inline Type &InstanceLocator::Get(void) const { // This method uses the `Instance` template method `Get` // to get to the given `Type` from the single OpenThread // instance. - // - // The specializations of `Instance::Get` should be defined - // for any class (type) which would use `GetOwner` method - // (i.e., any class that is an owner of a callback providing object - // such as a `Timer`, `Tasklet`, or in general any sub-class of - // `OwnerLocator`). + return GetInstance().Get(); +} +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES + +template OwnerType &OwnerLocator::GetOwner(void) +{ return Instance::Get().Get(); } @@ -62,4 +74,4 @@ template OwnerType &OwnerLocator::GetOwner(void) } // namespace ot -#endif // OWNER_LOCATOR_HPP_ +#endif // LOCATOR_GETTERS_HPP_ diff --git a/src/core/common/locator.cpp b/src/core/common/locator.cpp deleted file mode 100644 index 92cd4258d..000000000 --- a/src/core/common/locator.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 "locator.hpp" - -#include "common/instance.hpp" -#include "net/ip6.hpp" - -namespace ot { - -#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES -Instance &InstanceLocator::GetInstance(void) const -{ - return Instance::Get(); -} -#endif - -#if OPENTHREAD_MTD || OPENTHREAD_FTD -Ip6::Ip6 &InstanceLocator::GetIp6(void) const -{ - return GetInstance().GetIp6(); -} - -ThreadNetif &InstanceLocator::GetNetif(void) const -{ - return GetInstance().GetThreadNetif(); -} - -Notifier &InstanceLocator::GetNotifier(void) const -{ - return GetInstance().GetNotifier(); -} -#endif // OPENTHREAD_MTD || OPENTHREAD_FTD - -} // namespace ot diff --git a/src/core/common/locator.hpp b/src/core/common/locator.hpp index 61555cb99..4e3f997fa 100644 --- a/src/core/common/locator.hpp +++ b/src/core/common/locator.hpp @@ -38,14 +38,15 @@ #include +#include "utils/wrap_stdint.h" + namespace ot { class Instance; -class ThreadNetif; -class Notifier; -namespace Ip6 { -class Ip6; -} + +#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES +extern uint64_t gInstanceRaw[]; +#endif /** * @addtogroup core-locator @@ -61,8 +62,8 @@ class Ip6; * This class implements a locator for an OpenThread Instance object. * * The `InstanceLocator` is used as base class of almost all other OpenThread classes. It provides a way for an object - * to get to its owning/parent OpenThread `Instance` and other objects within the OpenTread hierarchy (e.g. the - * `ThreadNetif` or `Ip6::Ip6` objects). + * to get to its owning/parent OpenThread `Instance` and also any other `Type` within the `Instance` member variable + * property hierarchy (using `Get()` method). * * If multiple-instance feature is supported, the owning/parent OpenThread `Instance` is tracked as a reference. In the * single-instance case, this class becomes an empty base class. @@ -80,32 +81,21 @@ public: #if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES Instance &GetInstance(void) const { return mInstance; } #else - Instance &GetInstance(void) const; + Instance &GetInstance(void) const { return *reinterpret_cast(&gInstanceRaw); } #endif /** - * This method returns a reference to the Ip6. + * This template method returns a reference to a given `Type` object belonging to the OpenThread instance. * - * @returns A reference to the Ip6. + * For example, `Get()` returns a reference to the `MeshForwarder` object of the instance. + * + * Note that any `Type` for which the `Get` is defined MUST be uniquely accessible from the OpenThread + * `Instance` through the member variable property hierarchy. + * + * @returns A reference to the `Type` object of the instance. * */ - Ip6::Ip6 &GetIp6(void) const; - - /** - * This method returns a reference to the thread network interface. - * - * @returns A reference to the thread network interface. - * - */ - ThreadNetif &GetNetif(void) const; - - /** - * This method returns a reference to the Notifier. - * - * @returns A reference to the Notifier. - * - */ - Notifier &GetNotifier(void) const; + template inline Type &Get(void) const; // Implemented in `locator-getters.hpp`. protected: /** @@ -151,13 +141,13 @@ public: return *static_cast(mOwner); } #else - // Implemented in `owner-locator.hpp` + // Implemented in `locator-getters.hpp` ; #endif protected: /** - * This constructor initializes the object + * This constructor initializes the object. * * @param[in] aOwner A pointer to the owner object (as `void *`). * diff --git a/src/core/common/message.cpp b/src/core/common/message.cpp index f3e0c7113..ce379f11f 100644 --- a/src/core/common/message.cpp +++ b/src/core/common/message.cpp @@ -38,6 +38,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "net/ip6.hpp" @@ -178,8 +179,7 @@ otError MessagePool::ReclaimBuffers(int aNumBuffers, uint8_t aPriority) #if OPENTHREAD_MTD || OPENTHREAD_FTD while (aNumBuffers > GetFreeBufferCount()) { - MeshForwarder &meshForwarder = GetInstance().GetThreadNetif().GetMeshForwarder(); - SuccessOrExit(meshForwarder.EvictMessage(aPriority)); + SuccessOrExit(Get().EvictMessage(aPriority)); } exit: diff --git a/src/core/common/notifier.cpp b/src/core/common/notifier.cpp index 4d9d6e9a2..151662bd4 100644 --- a/src/core/common/notifier.cpp +++ b/src/core/common/notifier.cpp @@ -37,8 +37,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" namespace ot { @@ -48,7 +48,7 @@ Notifier::Callback::Callback(Instance &aInstance, Handler aHandler, void *aOwner , mNext(NULL) { assert(aHandler != NULL); - aInstance.GetNotifier().RegisterCallback(*this); + aInstance.Get().RegisterCallback(*this); } Notifier::Notifier(Instance &aInstance) diff --git a/src/core/common/tasklet.cpp b/src/core/common/tasklet.cpp index c824f9cf8..abe607e4c 100644 --- a/src/core/common/tasklet.cpp +++ b/src/core/common/tasklet.cpp @@ -36,6 +36,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "net/ip6.hpp" namespace ot { @@ -50,7 +51,7 @@ Tasklet::Tasklet(Instance &aInstance, Handler aHandler, void *aOwner) otError Tasklet::Post(void) { - return GetInstance().GetTaskletScheduler().Post(*this); + return Get().Post(*this); } TaskletScheduler::TaskletScheduler(void) @@ -65,7 +66,7 @@ otError TaskletScheduler::Post(Tasklet &aTasklet) VerifyOrExit(mTail != &aTasklet && aTasklet.mNext == NULL, error = OT_ERROR_ALREADY); - VerifyOrExit(&aTasklet.GetInstance().Get() == this); + VerifyOrExit(&aTasklet.Get() == this); if (mTail == NULL) { diff --git a/src/core/common/timer.cpp b/src/core/common/timer.cpp index d4a64c7b2..298f82594 100644 --- a/src/core/common/timer.cpp +++ b/src/core/common/timer.cpp @@ -38,6 +38,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" namespace ot { @@ -73,17 +74,12 @@ void TimerMilli::StartAt(uint32_t aT0, uint32_t aDt) { assert(aDt <= kMaxDt); mFireTime = aT0 + aDt; - GetTimerMilliScheduler().Add(*this); + Get().Add(*this); } void TimerMilli::Stop(void) { - GetTimerMilliScheduler().Remove(*this); -} - -TimerMilliScheduler &TimerMilli::GetTimerMilliScheduler(void) const -{ - return GetInstance().GetTimerMilliScheduler(); + Get().Remove(*this); } void TimerScheduler::Add(Timer &aTimer, const AlarmApi &aAlarmApi) @@ -212,7 +208,7 @@ extern "C" void otPlatAlarmMilliFired(otInstance *aInstance) Instance *instance = static_cast(aInstance); VerifyOrExit(otInstanceIsInitialized(aInstance)); - instance->GetTimerMilliScheduler().ProcessTimers(); + instance->Get().ProcessTimers(); exit: return; @@ -226,17 +222,12 @@ void TimerMicro::StartAt(uint32_t aT0, uint32_t aDt) { assert(aDt <= kMaxDt); mFireTime = aT0 + aDt; - GetTimerMicroScheduler().Add(*this); + Get().Add(*this); } void TimerMicro::Stop(void) { - GetTimerMicroScheduler().Remove(*this); -} - -TimerMicroScheduler &TimerMicro::GetTimerMicroScheduler(void) const -{ - return GetInstance().GetTimerMicroScheduler(); + Get().Remove(*this); } extern "C" void otPlatAlarmMicroFired(otInstance *aInstance) @@ -244,7 +235,7 @@ extern "C" void otPlatAlarmMicroFired(otInstance *aInstance) Instance *instance = static_cast(aInstance); VerifyOrExit(otInstanceIsInitialized(aInstance)); - instance->GetTimerMicroScheduler().ProcessTimers(); + instance->Get().ProcessTimers(); exit: return; diff --git a/src/core/common/timer.hpp b/src/core/common/timer.hpp index 0bd9dc9c7..d8ad92e94 100644 --- a/src/core/common/timer.hpp +++ b/src/core/common/timer.hpp @@ -204,15 +204,6 @@ public: * */ static uint32_t MsecToSec(uint32_t aMilliseconds) { return aMilliseconds / 1000u; } - -private: - /** - * This method returns a reference to the TimerMilliScheduler. - * - * @returns A reference to the TimerMilliScheduler. - * - */ - TimerMilliScheduler &GetTimerMilliScheduler(void) const; }; /** @@ -437,15 +428,6 @@ public: * */ static uint32_t GetNow(void) { return otPlatAlarmMicroGetNow(); } - -private: - /** - * This method returns a reference to the TimerMicroScheduler. - * - * @returns A reference to the TimerMicroScheduler. - * - */ - TimerMicroScheduler &GetTimerMicroScheduler(void) const; }; /** diff --git a/src/core/mac/link_raw.cpp b/src/core/mac/link_raw.cpp index ecbdb5a71..fef5c795f 100644 --- a/src/core/mac/link_raw.cpp +++ b/src/core/mac/link_raw.cpp @@ -39,6 +39,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/random.hpp" #include "mac/mac.hpp" @@ -72,7 +73,7 @@ otError LinkRaw::SetEnabled(bool aEnabled) otLogDebgMac("LinkRaw::Enabled(%s)", aEnabled ? "true" : "false"); #if OPENTHREAD_MTD || OPENTHREAD_FTD - VerifyOrExit(!GetInstance().GetThreadNetif().IsUp(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(!Get().IsUp(), error = OT_ERROR_INVALID_STATE); #endif if (aEnabled) diff --git a/src/core/mac/link_raw.hpp b/src/core/mac/link_raw.hpp index b7ba91e08..123ed8bfc 100644 --- a/src/core/mac/link_raw.hpp +++ b/src/core/mac/link_raw.hpp @@ -57,6 +57,8 @@ class LinkRaw : public InstanceLocator public SubMac::Callbacks #endif { + friend class ot::Instance; + public: /** * This constructor initializes the object. @@ -66,14 +68,6 @@ public: */ explicit LinkRaw(Instance &aInstance); - /** - * This method gets the associated `SubMac` object. - * - * @returns A reference to the `SubMac` object. - * - */ - SubMac &GetSubMac(void) { return mSubMac; } - /** * This method returns true if the raw link-layer is enabled. * diff --git a/src/core/mac/mac.cpp b/src/core/mac/mac.cpp index a722fedf3..a30ef01d7 100644 --- a/src/core/mac/mac.cpp +++ b/src/core/mac/mac.cpp @@ -42,8 +42,8 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "crypto/aes_ccm.hpp" #include "crypto/sha256.hpp" @@ -358,11 +358,11 @@ otError Mac::SetPanChannel(uint8_t aChannel) VerifyOrExit(mSupportedChannelMask.ContainsChannel(aChannel), error = OT_ERROR_INVALID_ARGS); - VerifyOrExit(mPanChannel != aChannel, GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_CHANNEL)); + VerifyOrExit(mPanChannel != aChannel, Get().SignalIfFirst(OT_CHANGED_THREAD_CHANNEL)); mPanChannel = aChannel; mCcaSuccessRateTracker.Reset(); - GetNotifier().Signal(OT_CHANGED_THREAD_CHANNEL); + Get().Signal(OT_CHANGED_THREAD_CHANNEL); VerifyOrExit(!mRadioChannelAcquisitionId); @@ -426,10 +426,10 @@ void Mac::SetSupportedChannelMask(const ChannelMask &aMask) ChannelMask newMask = aMask; newMask.Intersect(ChannelMask(Phy::kSupportedChannels)); - VerifyOrExit(newMask != mSupportedChannelMask, GetNotifier().SignalIfFirst(OT_CHANGED_SUPPORTED_CHANNEL_MASK)); + VerifyOrExit(newMask != mSupportedChannelMask, Get().SignalIfFirst(OT_CHANGED_SUPPORTED_CHANNEL_MASK)); mSupportedChannelMask = newMask; - GetNotifier().Signal(OT_CHANGED_SUPPORTED_CHANNEL_MASK); + Get().Signal(OT_CHANGED_SUPPORTED_CHANNEL_MASK); exit: return; @@ -447,11 +447,11 @@ otError Mac::SetNetworkName(const char *aBuffer, uint8_t aLength) VerifyOrExit(newLen <= OT_NETWORK_NAME_MAX_SIZE, error = OT_ERROR_INVALID_ARGS); VerifyOrExit(newLen != strlen(mNetworkName.m8) || memcmp(mNetworkName.m8, aBuffer, newLen) != 0, - GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_NETWORK_NAME)); + Get().SignalIfFirst(OT_CHANGED_THREAD_NETWORK_NAME)); memcpy(mNetworkName.m8, aBuffer, newLen); mNetworkName.m8[newLen] = 0; - GetNotifier().Signal(OT_CHANGED_THREAD_NETWORK_NAME); + Get().Signal(OT_CHANGED_THREAD_NETWORK_NAME); exit: return error; @@ -459,10 +459,10 @@ exit: void Mac::SetPanId(PanId aPanId) { - VerifyOrExit(mPanId != aPanId, GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_PANID)); + VerifyOrExit(mPanId != aPanId, Get().SignalIfFirst(OT_CHANGED_THREAD_PANID)); mPanId = aPanId; mSubMac.SetPanId(mPanId); - GetNotifier().Signal(OT_CHANGED_THREAD_PANID); + Get().Signal(OT_CHANGED_THREAD_PANID); exit: return; @@ -471,10 +471,10 @@ exit: void Mac::SetExtendedPanId(const otExtendedPanId &aExtendedPanId) { VerifyOrExit(memcmp(mExtendedPanId.m8, aExtendedPanId.m8, sizeof(mExtendedPanId)) != 0, - GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_EXT_PANID)); + Get().SignalIfFirst(OT_CHANGED_THREAD_EXT_PANID)); mExtendedPanId = aExtendedPanId; - GetNotifier().Signal(OT_CHANGED_THREAD_EXT_PANID); + Get().Signal(OT_CHANGED_THREAD_EXT_PANID); exit: return; @@ -751,12 +751,12 @@ void Mac::SendBeacon(Frame &aFrame) beaconPayload = reinterpret_cast(beacon->GetPayload()); - if (GetNetif().GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_BEACONS) + if (Get().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_BEACONS) { beaconPayload->Init(); // set the Joining Permitted flag - GetNetif().GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); + Get().GetUnsecurePorts(numUnsecurePorts); if (numUnsecurePorts) { @@ -798,7 +798,7 @@ bool Mac::ShouldSendBeacon(void) const uint8_t numUnsecurePorts; - GetNetif().GetIp6Filter().GetUnsecurePorts(numUnsecurePorts); + Get().GetUnsecurePorts(numUnsecurePorts); shouldSend = (numUnsecurePorts != 0); } #endif @@ -834,7 +834,7 @@ void Mac::ProcessTransmitAesCcm(Frame &aFrame, const ExtAddress *aExtAddress) void Mac::ProcessTransmitSecurity(Frame &aFrame, bool aProcessAesCcm) { - KeyManager & keyManager = GetNetif().GetKeyManager(); + KeyManager & keyManager = Get(); uint8_t keyIdMode; const ExtAddress *extAddress = NULL; @@ -938,7 +938,7 @@ void Mac::BeginTransmit(void) case kOperationTransmitData: sendFrame.SetChannel(mRadioChannel); - SuccessOrExit(error = GetNetif().GetMeshForwarder().HandleFrameRequest(sendFrame)); + SuccessOrExit(error = Get().HandleFrameRequest(sendFrame)); // If the frame is marked as a retransmission, then data sequence number is already set. if (!sendFrame.IsARetransmission()) @@ -966,8 +966,8 @@ void Mac::BeginTransmit(void) { // Transmit security will be processed after time IE content is updated. processTransmitAesCcm = false; - sendFrame.SetTimeSyncSeq(GetNetif().GetTimeSync().GetTimeSyncSeq()); - sendFrame.SetNetworkTimeOffset(GetNetif().GetTimeSync().GetNetworkTimeOffset()); + sendFrame.SetTimeSyncSeq(Get().GetTimeSyncSeq()); + sendFrame.SetNetworkTimeOffset(Get().GetNetworkTimeOffset()); } #endif @@ -1029,7 +1029,7 @@ void Mac::RecordFrameTransmitStatus(const Frame &aFrame, Neighbor *neighbor; aFrame.GetDstAddr(dstAddr); - neighbor = GetNetif().GetMle().GetNeighbor(dstAddr); + neighbor = Get().GetNeighbor(dstAddr); #if OPENTHREAD_CONFIG_ENABLE_TX_ERROR_RATE_TRACKING @@ -1188,7 +1188,7 @@ void Mac::HandleTransmitDone(Frame &aFrame, Frame *aAckFrame, otError aError) otDumpDebgMac("TX", aFrame.GetHeader(), aFrame.GetLength()); FinishOperation(); - GetNetif().GetMeshForwarder().HandleSentFrame(aFrame, aError); + Get().HandleSentFrame(aFrame, aError); PerformNextOperation(); break; @@ -1222,7 +1222,7 @@ void Mac::HandleTimer(void) case kOperationWaitingForData: otLogDebgMac("Data poll timeout"); FinishOperation(); - GetNetif().GetMeshForwarder().GetDataPollManager().HandlePollTimeout(); + Get().HandlePollTimeout(); PerformNextOperation(); break; @@ -1246,7 +1246,7 @@ void Mac::HandleTimer(void) otError Mac::ProcessReceiveSecurity(Frame &aFrame, const Address &aSrcAddr, Neighbor *aNeighbor) { - KeyManager & keyManager = GetNetif().GetKeyManager(); + KeyManager & keyManager = Get(); otError error = OT_ERROR_NONE; uint8_t securityLevel; uint8_t keyIdMode; @@ -1390,13 +1390,12 @@ exit: void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) { - ThreadNetif &netif = GetNetif(); - Address srcaddr; - Address dstaddr; - PanId panid; - Neighbor * neighbor; - bool receive = false; - otError error = aError; + Address srcaddr; + Address dstaddr; + PanId panid; + Neighbor *neighbor; + bool receive = false; + otError error = aError; #if OPENTHREAD_ENABLE_MAC_FILTER int8_t rssi = OT_MAC_FILTER_FIXED_RSS_DISABLED; #endif // OPENTHREAD_ENABLE_MAC_FILTER @@ -1413,7 +1412,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) aFrame->GetSrcAddr(srcaddr); aFrame->GetDstAddr(dstaddr); - neighbor = netif.GetMle().GetNeighbor(srcaddr); + neighbor = Get().GetNeighbor(srcaddr); // Destination Address Filtering switch (dstaddr.GetType()) @@ -1428,9 +1427,9 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); // Allow multicasts from neighbor routers if FTD - if (neighbor == NULL && dstaddr.IsBroadcast() && netif.GetMle().IsFullThreadDevice()) + if (neighbor == NULL && dstaddr.IsBroadcast() && Get().IsFullThreadDevice()) { - neighbor = netif.GetMle().GetRxOnlyNeighborRouter(srcaddr); + neighbor = Get().GetRxOnlyNeighborRouter(srcaddr); } break; @@ -1527,7 +1526,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) ExitNow(); } - netif.GetMeshForwarder().GetDataPollManager().CheckFramePending(*aFrame); + Get().CheckFramePending(*aFrame); #if OPENTHREAD_CONFIG_HEADER_IE_SUPPORT @@ -1650,7 +1649,7 @@ void Mac::HandleReceivedFrame(Frame *aFrame, otError aError) if (receive) { otDumpDebgMac("RX", aFrame->GetHeader(), aFrame->GetLength()); - netif.GetMeshForwarder().HandleReceivedFrame(*aFrame); + Get().HandleReceivedFrame(*aFrame); } exit: diff --git a/src/core/mac/mac.hpp b/src/core/mac/mac.hpp index a3b0f09ab..c545b6ad0 100644 --- a/src/core/mac/mac.hpp +++ b/src/core/mac/mac.hpp @@ -95,6 +95,8 @@ enum */ class Mac : public InstanceLocator, public SubMac::Callbacks { + friend class ot::Instance; + public: /** * This constructor initializes the MAC object. @@ -104,14 +106,6 @@ public: */ explicit Mac(Instance &aInstance); - /** - * This method gets the associated `SubMac` object. - * - * @returns A reference to the `SubMac` object. - * - */ - SubMac &GetSubMac(void) { return mSubMac; } - /** * This function pointer is called on receiving an IEEE 802.15.4 Beacon during an Active Scan. * @@ -410,16 +404,6 @@ public: */ void SetExtendedPanId(const otExtendedPanId &aExtendedPanId); -#if OPENTHREAD_ENABLE_MAC_FILTER - /** - * This method returns the MAC filter. - * - * @returns A reference to the MAC filter. - * - */ - Filter &GetFilter(void) { return mFilter; } -#endif // OPENTHREAD_ENABLE_MAC_FILTER - /** * This method is called to handle a received frame. * diff --git a/src/core/mac/sub_mac.cpp b/src/core/mac/sub_mac.cpp index 04178bac6..0b7d0a463 100644 --- a/src/core/mac/sub_mac.cpp +++ b/src/core/mac/sub_mac.cpp @@ -40,8 +40,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" namespace ot { @@ -495,7 +495,7 @@ bool SubMac::ShouldHandleCsmaBackOff(void) const VerifyOrExit(!RadioSupportsCsmaBackoff(), swCsma = false); #if OPENTHREAD_ENABLE_RAW_LINK_API - VerifyOrExit(GetInstance().GetLinkRaw().IsEnabled()); + VerifyOrExit(Get().IsEnabled()); #endif #if OPENTHREAD_ENABLE_RAW_LINK_API || OPENTHREAD_RADIO @@ -513,7 +513,7 @@ bool SubMac::ShouldHandleAckTimeout(void) const VerifyOrExit(!RadioSupportsAckTimeout(), swAckTimeout = false); #if OPENTHREAD_ENABLE_RAW_LINK_API - VerifyOrExit(GetInstance().GetLinkRaw().IsEnabled()); + VerifyOrExit(Get().IsEnabled()); #endif #if OPENTHREAD_ENABLE_RAW_LINK_API || OPENTHREAD_RADIO @@ -531,7 +531,7 @@ bool SubMac::ShouldHandleRetries(void) const VerifyOrExit(!RadioSupportsRetries(), swRetries = false); #if OPENTHREAD_ENABLE_RAW_LINK_API - VerifyOrExit(GetInstance().GetLinkRaw().IsEnabled()); + VerifyOrExit(Get().IsEnabled()); #endif #if OPENTHREAD_ENABLE_RAW_LINK_API || OPENTHREAD_RADIO @@ -549,7 +549,7 @@ bool SubMac::ShouldHandleEnergyScan(void) const VerifyOrExit(!RadioSupportsEnergyScan(), swEnergyScan = false); #if OPENTHREAD_ENABLE_RAW_LINK_API - VerifyOrExit(GetInstance().GetLinkRaw().IsEnabled()); + VerifyOrExit(Get().IsEnabled()); #endif #if OPENTHREAD_ENABLE_RAW_LINK_API || OPENTHREAD_RADIO diff --git a/src/core/mac/sub_mac_callbacks.cpp b/src/core/mac/sub_mac_callbacks.cpp index ac542cf8b..e95619c3d 100644 --- a/src/core/mac/sub_mac_callbacks.cpp +++ b/src/core/mac/sub_mac_callbacks.cpp @@ -37,6 +37,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "mac/mac.hpp" namespace ot { @@ -49,7 +50,7 @@ void SubMac::Callbacks::ReceiveDone(Frame *aFrame, otError aError) Mac &mac = *static_cast(this); #if OPENTHREAD_ENABLE_RAW_LINK_API - LinkRaw &linkRaw = mac.GetInstance().GetLinkRaw(); + LinkRaw &linkRaw = mac.Get(); if (linkRaw.IsEnabled()) { @@ -81,7 +82,7 @@ void SubMac::Callbacks::TransmitDone(Frame &aFrame, Frame *aAckFrame, otError aE Mac &mac = *static_cast(this); #if OPENTHREAD_ENABLE_RAW_LINK_API - LinkRaw &linkRaw = mac.GetInstance().GetLinkRaw(); + LinkRaw &linkRaw = mac.Get(); if (linkRaw.IsEnabled()) { @@ -99,7 +100,7 @@ void SubMac::Callbacks::EnergyScanDone(int8_t aMaxRssi) Mac &mac = *static_cast(this); #if OPENTHREAD_ENABLE_RAW_LINK_API - LinkRaw &linkRaw = mac.GetInstance().GetLinkRaw(); + LinkRaw &linkRaw = mac.Get(); if (linkRaw.IsEnabled()) { diff --git a/src/core/meshcop/announce_begin_client.cpp b/src/core/meshcop/announce_begin_client.cpp index 5191bdf9f..5b4d6b037 100644 --- a/src/core/meshcop/announce_begin_client.cpp +++ b/src/core/meshcop/announce_begin_client.cpp @@ -41,6 +41,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -70,8 +71,8 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, Ip6::MessageInfo messageInfo; Coap::Message * message = NULL; - VerifyOrExit(GetNetif().GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(GetNetif().GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit(Get().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -79,7 +80,7 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, message->SetPayloadMarker(); sessionId.Init(); - sessionId.SetCommissionerSessionId(GetNetif().GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(Get().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -94,12 +95,12 @@ otError AnnounceBeginClient::SendRequest(uint32_t aChannelMask, period.SetPeriod(aPeriod); SuccessOrExit(error = message->Append(&period, sizeof(period))); - messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(GetNetif().GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = GetNetif().GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent announce begin query"); diff --git a/src/core/meshcop/border_agent.cpp b/src/core/meshcop/border_agent.cpp index a6d4d9eaa..9a6de2d30 100644 --- a/src/core/meshcop/border_agent.cpp +++ b/src/core/meshcop/border_agent.cpp @@ -37,9 +37,9 @@ #include "coap/coap_message.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/new.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -220,12 +220,12 @@ void BorderAgent::HandleCoapResponse(void * aContext, ForwardContext & forwardContext = *static_cast(aContext); BorderAgent & borderAgent = forwardContext.GetBorderAgent(); - ThreadNetif & netif = borderAgent.GetNetif(); + Instance & instance = borderAgent.GetInstance(); const Coap::Message *response = static_cast(aMessage); Coap::Message * message = NULL; otError error; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(instance.Get())) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = aResult); if (forwardContext.IsPetition()) @@ -243,10 +243,10 @@ void BorderAgent::HandleCoapResponse(void * aContext, Tlv::GetTlv(*response, Tlv::kCommissionerSessionId, sizeof(sessionIdTlv), sessionIdTlv)); VerifyOrExit(sessionIdTlv.IsValid(), error = OT_ERROR_PARSE); - netif.GetMle().GetCommissionerAloc(borderAgent.mCommissionerAloc.GetAddress(), - sessionIdTlv.GetCommissionerSessionId()); - netif.AddUnicastAddress(borderAgent.mCommissionerAloc); - netif.GetIp6().GetUdp().AddReceiver(borderAgent.mUdpReceiver); + instance.Get().GetCommissionerAloc(borderAgent.mCommissionerAloc.GetAddress(), + sessionIdTlv.GetCommissionerSessionId()); + instance.Get().AddUnicastAddress(borderAgent.mCommissionerAloc); + instance.Get().AddReceiver(borderAgent.mUdpReceiver); } } @@ -270,10 +270,10 @@ exit: otLogWarnMeshCoP("Commissioner request[%hu] failed: %s", forwardContext.GetMessageId(), otThreadErrorToString(error)); - SendErrorMessage(netif.GetCoapSecure(), forwardContext); + SendErrorMessage(instance.Get(), forwardContext); } - borderAgent.GetInstance().GetHeap().Free(&forwardContext); + instance.GetHeap().Free(&forwardContext); } template <> @@ -363,12 +363,11 @@ void BorderAgent::HandleProxyTransmit(const Coap::Message &aMessage) SuccessOrExit(error = Tlv::GetOffset(aMessage, Tlv::kUdpEncapsulation, offset)); VerifyOrExit(aMessage.Read(offset, sizeof(tlv), &tlv) == sizeof(tlv), error = OT_ERROR_PARSE); - VerifyOrExit((message = GetInstance().GetIp6().GetUdp().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(tlv.GetUdpLength())); aMessage.CopyTo(offset + sizeof(tlv), 0, tlv.GetUdpLength(), *message); - messageInfo.SetSockPort(tlv.GetSourcePort() != 0 ? tlv.GetSourcePort() - : GetInstance().GetIp6().GetUdp().GetEphemeralPort()); + messageInfo.SetSockPort(tlv.GetSourcePort() != 0 ? tlv.GetSourcePort() : Get().GetEphemeralPort()); messageInfo.SetSockAddr(mCommissionerAloc.GetAddress()); messageInfo.SetPeerPort(tlv.GetDestinationPort()); } @@ -380,7 +379,7 @@ void BorderAgent::HandleProxyTransmit(const Coap::Message &aMessage) messageInfo.SetPeerAddr(tlv.GetAddress()); } - SuccessOrExit(error = GetInstance().GetIp6().GetUdp().SendDatagram(*message, messageInfo, Ip6::kProtoUdp)); + SuccessOrExit(error = Get().SendDatagram(*message, messageInfo, Ip6::kProtoUdp)); otLogInfoMeshCoP("Proxy transmit sent"); exit: @@ -399,14 +398,13 @@ bool BorderAgent::HandleUdpReceive(const Message &aMessage, const Ip6::MessageIn { otError error; Coap::Message *message = NULL; - ThreadNetif & netif = GetNetif(); VerifyOrExit(aMessageInfo.GetSockAddr() == mCommissionerAloc.GetAddress(), error = OT_ERROR_DESTINATION_ADDRESS_FILTERED); VerifyOrExit(aMessage.GetLength() > 0, error = OT_ERROR_NONE); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_PROXY_RX); @@ -436,7 +434,7 @@ bool BorderAgent::HandleUdpReceive(const Message &aMessage, const Ip6::MessageIn SuccessOrExit(error = message->Append(&tlv, sizeof(tlv))); } - SuccessOrExit(error = netif.GetCoapSecure().SendMessage(*message, netif.GetCoapSecure().GetPeerAddress())); + SuccessOrExit(error = Get().SendMessage(*message, Get().GetPeerAddress())); otLogInfoMeshCoP("Sent to commissioner on %s", OT_URI_PATH_PROXY_RX); @@ -457,7 +455,7 @@ void BorderAgent::HandleRelayReceive(const Coap::Message &aMessage) VerifyOrExit(aMessage.GetType() == OT_COAP_TYPE_NON_CONFIRMABLE && aMessage.GetCode() == OT_COAP_CODE_POST, error = OT_ERROR_DROP); - VerifyOrExit((message = NewMeshCoPMessage(GetNetif().GetCoapSecure())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_RELAY_RX); @@ -479,15 +477,15 @@ exit: otError BorderAgent::ForwardToCommissioner(Coap::Message &aForwardMessage, const Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - uint16_t offset = 0; + otError error = OT_ERROR_NONE; + uint16_t offset = 0; offset = aForwardMessage.GetLength(); SuccessOrExit(error = aForwardMessage.SetLength(offset + aMessage.GetLength() - aMessage.GetOffset())); aMessage.CopyTo(aMessage.GetOffset(), offset, aMessage.GetLength() - aMessage.GetOffset(), aForwardMessage); - SuccessOrExit(error = netif.GetCoapSecure().SendMessage(aForwardMessage, netif.GetCoapSecure().GetPeerAddress())); + SuccessOrExit(error = + Get().SendMessage(aForwardMessage, Get().GetPeerAddress())); otLogInfoMeshCoP("Sent to commissioner"); @@ -514,7 +512,6 @@ void BorderAgent::HandleKeepAlive(const Coap::Message &aMessage, const Ip6::Mess void BorderAgent::HandleRelayTransmit(const Coap::Message &aMessage) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; JoinerRouterLocatorTlv joinerRouterRloc; Coap::Message * message = NULL; @@ -526,7 +523,7 @@ void BorderAgent::HandleRelayTransmit(const Coap::Message &aMessage) SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kJoinerRouterLocator, sizeof(joinerRouterRloc), joinerRouterRloc)); VerifyOrExit(joinerRouterRloc.IsValid(), error = OT_ERROR_PARSE); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -538,12 +535,12 @@ void BorderAgent::HandleRelayTransmit(const Coap::Message &aMessage) aMessage.CopyTo(aMessage.GetOffset(), offset, aMessage.GetLength() - aMessage.GetOffset(), *message); messageInfo.SetSockPort(kCoapUdpPort); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetPeerAddr(Get().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(joinerRouterRloc.GetJoinerRouterLocator()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("Sent to joiner router request on %s", OT_URI_PATH_RELAY_TX); @@ -565,18 +562,17 @@ otError BorderAgent::ForwardToLeader(const Coap::Message & aMessage, bool aPetition, bool aSeparate) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ForwardContext * forwardContext = NULL; Ip6::MessageInfo messageInfo; Coap::Message * message = NULL; uint16_t offset = 0; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); if (aSeparate) { - SuccessOrExit(error = netif.GetCoapSecure().SendAck(aMessage, aMessageInfo)); + SuccessOrExit(error = Get().SendAck(aMessage, aMessageInfo)); } forwardContext = static_cast(GetInstance().GetHeap().CAlloc(1, sizeof(ForwardContext))); @@ -598,12 +594,12 @@ otError BorderAgent::ForwardToLeader(const Coap::Message & aMessage, SuccessOrExit(error = message->SetLength(offset + aMessage.GetLength() - aMessage.GetOffset())); aMessage.CopyTo(aMessage.GetOffset(), offset, aMessage.GetLength() - aMessage.GetOffset(), *message); - SuccessOrExit(error = netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr())); + SuccessOrExit(error = Get().GetLeaderAloc(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetSockPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, HandleCoapResponse, forwardContext)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, HandleCoapResponse, forwardContext)); // HandleCoapResponse is responsible to free this forward context. forwardContext = NULL; @@ -625,7 +621,7 @@ exit: otLogWarnMeshCoP("Failed to forward to leader: %s", otThreadErrorToString(error)); - SendErrorMessage(netif.GetCoapSecure(), aMessage, aSeparate); + SendErrorMessage(Get(), aMessage, aSeparate); } return error; @@ -642,7 +638,7 @@ void BorderAgent::HandleConnected(bool aConnected) else { otLogInfoMeshCoP("Commissioner disconnected"); - GetNetif().RemoveUnicastAddress(mCommissionerAloc); + Get().RemoveUnicastAddress(mCommissionerAloc); SetState(OT_BORDER_AGENT_STATE_STARTED); } } @@ -650,14 +646,12 @@ void BorderAgent::HandleConnected(bool aConnected) otError BorderAgent::Start(void) { otError error; - ThreadNetif & netif = GetNetif(); - Coap::CoapSecure &coaps = netif.GetCoapSecure(); - Coap::Coap & coap = netif.GetCoap(); + Coap::CoapSecure &coaps = Get(); VerifyOrExit(mState == OT_BORDER_AGENT_STATE_STOPPED, error = OT_ERROR_ALREADY); SuccessOrExit(error = coaps.Start(kBorderAgentUdpPort)); - SuccessOrExit(error = coaps.SetPsk(netif.GetKeyManager().GetPSKc(), OT_PSKC_MAX_SIZE)); + SuccessOrExit(error = coaps.SetPsk(Get().GetPSKc(), OT_PSKC_MAX_SIZE)); coaps.SetConnectedCallback(HandleConnected, this); coaps.AddResource(mActiveGet); @@ -671,7 +665,7 @@ otError BorderAgent::Start(void) coaps.AddResource(mProxyTransmit); coaps.AddResource(mRelayTransmit); - coap.AddResource(mRelayReceive); + Get().AddResource(mRelayReceive); SetState(OT_BORDER_AGENT_STATE_STARTED); @@ -686,12 +680,9 @@ void BorderAgent::HandleTimeout(Timer &aTimer) void BorderAgent::HandleTimeout(void) { - ThreadNetif & netif = GetNetif(); - Coap::CoapSecure &coaps = netif.GetCoapSecure(); - - if (coaps.IsConnected()) + if (Get().IsConnected()) { - coaps.Disconnect(); + Get().Disconnect(); otLogWarnMeshCoP("Reset commissioner session"); } } @@ -699,9 +690,7 @@ void BorderAgent::HandleTimeout(void) otError BorderAgent::Stop(void) { otError error = OT_ERROR_NONE; - ThreadNetif & netif = GetNetif(); - Coap::CoapSecure &coaps = netif.GetCoapSecure(); - Coap::Coap & coap = netif.GetCoap(); + Coap::CoapSecure &coaps = Get(); VerifyOrExit(mState != OT_BORDER_AGENT_STATE_STOPPED, error = OT_ERROR_ALREADY); @@ -718,7 +707,7 @@ otError BorderAgent::Stop(void) coaps.RemoveResource(mProxyTransmit); coaps.RemoveResource(mRelayTransmit); - coap.RemoveResource(mRelayReceive); + Get().RemoveResource(mRelayReceive); coaps.Stop(); @@ -733,7 +722,7 @@ void BorderAgent::SetState(otBorderAgentState aState) if (mState != aState) { mState = aState; - GetNotifier().Signal(OT_CHANGED_BORDER_AGENT_STATE); + Get().Signal(OT_CHANGED_BORDER_AGENT_STATE); } } diff --git a/src/core/meshcop/commissioner.cpp b/src/core/meshcop/commissioner.cpp index 6c9bce589..9fda4d2fe 100644 --- a/src/core/meshcop/commissioner.cpp +++ b/src/core/meshcop/commissioner.cpp @@ -43,8 +43,8 @@ #include "coap/coap_message.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "crypto/pbkdf2_cmac.h" #include "meshcop/joiner_router.hpp" #include "meshcop/meshcop.hpp" @@ -85,20 +85,16 @@ Commissioner::Commissioner(Instance &aInstance) void Commissioner::AddCoapResources(void) { - ThreadNetif &netif = GetNetif(); - - netif.GetCoap().AddResource(mRelayReceive); - netif.GetCoap().AddResource(mDatasetChanged); - netif.GetCoapSecure().AddResource(mJoinerFinalize); + Get().AddResource(mRelayReceive); + Get().AddResource(mDatasetChanged); + Get().AddResource(mJoinerFinalize); } void Commissioner::RemoveCoapResources(void) { - ThreadNetif &netif = GetNetif(); - - netif.GetCoap().RemoveResource(mRelayReceive); - netif.GetCoap().RemoveResource(mDatasetChanged); - netif.GetCoapSecure().RemoveResource(mJoinerFinalize); + Get().RemoveResource(mRelayReceive); + Get().RemoveResource(mDatasetChanged); + Get().RemoveResource(mJoinerFinalize); } otError Commissioner::Start(void) @@ -107,7 +103,7 @@ otError Commissioner::Start(void) VerifyOrExit(mState == OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); - SuccessOrExit(error = GetNetif().GetCoapSecure().Start(SendRelayTransmit, this)); + SuccessOrExit(error = Get().Start(SendRelayTransmit, this)); mState = OT_COMMISSIONER_STATE_PETITION; mTransmitAttempts = 0; @@ -124,18 +120,18 @@ otError Commissioner::Stop(void) VerifyOrExit(mState != OT_COMMISSIONER_STATE_DISABLED, error = OT_ERROR_INVALID_STATE); - GetNetif().GetCoapSecure().Stop(); + Get().Stop(); mState = OT_COMMISSIONER_STATE_DISABLED; - GetNetif().RemoveUnicastAddress(mCommissionerAloc); - GetNotifier().Signal(OT_CHANGED_COMMISSIONER_STATE); + Get().RemoveUnicastAddress(mCommissionerAloc); + Get().Signal(OT_CHANGED_COMMISSIONER_STATE); RemoveCoapResources(); ClearJoiners(); mTransmitAttempts = 0; mTimer.Stop(); - GetNetif().GetCoapSecure().Stop(); + Get().Stop(); SendKeepAlive(); @@ -318,7 +314,7 @@ exit: const char *Commissioner::GetProvisioningUrl(uint16_t &aLength) const { - ProvisioningUrlTlv &provisioningUrl = GetNetif().GetCoapSecure().GetDtls().mProvisioningUrl; + ProvisioningUrlTlv &provisioningUrl = Get().GetDtls().mProvisioningUrl; aLength = provisioningUrl.GetLength(); @@ -327,7 +323,7 @@ const char *Commissioner::GetProvisioningUrl(uint16_t &aLength) const otError Commissioner::SetProvisioningUrl(const char *aProvisioningUrl) { - return GetNetif().GetCoapSecure().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); + return Get().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); } uint16_t Commissioner::GetSessionId(void) const @@ -424,13 +420,12 @@ void Commissioner::UpdateJoinerExpirationTimer(void) otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8_t aLength) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; MeshCoP::Tlv tlv; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -449,11 +444,11 @@ otError Commissioner::SendMgmtCommissionerGetRequest(const uint8_t *aTlvs, uint8 SuccessOrExit(error = message->Append(aTlvs, aLength)); } - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleMgmtCommissionerGetResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, + Commissioner::HandleMgmtCommissionerGetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_GET.req to leader"); @@ -493,12 +488,11 @@ otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDatase const uint8_t * aTlvs, uint8_t aLength) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -549,11 +543,11 @@ otError Commissioner::SendMgmtCommissionerSetRequest(const otCommissioningDatase message->SetLength(message->GetLength() - 1); } - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, - Commissioner::HandleMgmtCommissionerSetResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, + Commissioner::HandleMgmtCommissionerSetResponse, this)); otLogInfoMeshCoP("sent MGMT_COMMISSIONER_SET.req to leader"); @@ -591,7 +585,6 @@ exit: otError Commissioner::SendPetition(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; @@ -599,7 +592,7 @@ otError Commissioner::SendPetition(void) mTransmitAttempts++; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -611,11 +604,11 @@ otError Commissioner::SendPetition(void) SuccessOrExit(error = message->Append(&commissionerId, sizeof(Tlv) + commissionerId.GetLength())); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); SuccessOrExit( - error = netif.GetCoap().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); + error = Get().SendMessage(*message, messageInfo, Commissioner::HandleLeaderPetitionResponse, this)); otLogInfoMeshCoP("sent petition"); @@ -644,7 +637,6 @@ void Commissioner::HandleLeaderPetitionResponse(Coap::Message * aMessage { OT_UNUSED_VARIABLE(aMessageInfo); - ThreadNetif & netif = GetNetif(); StateTlv state; CommissionerSessionIdTlv sessionId; bool retransmit = false; @@ -663,8 +655,8 @@ void Commissioner::HandleLeaderPetitionResponse(Coap::Message * aMessage VerifyOrExit(sessionId.IsValid()); mSessionId = sessionId.GetCommissionerSessionId(); - netif.GetMle().GetCommissionerAloc(mCommissionerAloc.GetAddress(), mSessionId); - netif.AddUnicastAddress(mCommissionerAloc); + Get().GetCommissionerAloc(mCommissionerAloc.GetAddress(), mSessionId); + Get().AddUnicastAddress(mCommissionerAloc); AddCoapResources(); mState = OT_COMMISSIONER_STATE_ACTIVE; @@ -686,19 +678,18 @@ exit: } } - GetNotifier().Signal(OT_CHANGED_COMMISSIONER_STATE); + Get().Signal(OT_CHANGED_COMMISSIONER_STATE); } otError Commissioner::SendKeepAlive(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; StateTlv state; CommissionerSessionIdTlv sessionId; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -713,11 +704,11 @@ otError Commissioner::SendKeepAlive(void) sessionId.SetCommissionerSessionId(mSessionId); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit( - error = netif.GetCoap().SendMessage(*message, messageInfo, Commissioner::HandleLeaderKeepAliveResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, + Commissioner::HandleLeaderKeepAliveResponse, this)); otLogInfoMeshCoP("sent keep alive"); @@ -765,7 +756,7 @@ exit: if (mState != OT_COMMISSIONER_STATE_ACTIVE) { - GetNetif().RemoveUnicastAddress(mCommissionerAloc); + Get().RemoveUnicastAddress(mCommissionerAloc); RemoveCoapResources(); } } @@ -780,7 +771,6 @@ void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::Messag { OT_UNUSED_VARIABLE(aMessageInfo); - ThreadNetif & netif = GetNetif(); otError error; JoinerUdpPortTlv joinerPort; JoinerIidTlv joinerIid; @@ -807,7 +797,7 @@ void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::Messag SuccessOrExit(error = Tlv::GetValueOffset(aMessage, Tlv::kJoinerDtlsEncapsulation, offset, length)); VerifyOrExit(length <= aMessage.GetLength() - offset, error = OT_ERROR_PARSE); - if (!netif.GetCoapSecure().IsConnectionActive()) + if (!Get().IsConnectionActive()) { memcpy(mJoinerIid, joinerIid.GetIid(), sizeof(mJoinerIid)); mJoinerIid[0] ^= 0x2; @@ -823,8 +813,8 @@ void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::Messag if (mJoiners[i].mAny || !memcmp(&joinerId, mJoinerIid, sizeof(joinerId))) { - error = netif.GetCoapSecure().SetPsk(reinterpret_cast(mJoiners[i].mPsk), - static_cast(strlen(mJoiners[i].mPsk))); + error = Get().SetPsk(reinterpret_cast(mJoiners[i].mPsk), + static_cast(strlen(mJoiners[i].mPsk))); SuccessOrExit(error); otLogInfoMeshCoP("found joiner, starting new session"); enableJoiner = true; @@ -851,11 +841,11 @@ void Commissioner::HandleRelayReceive(Coap::Message &aMessage, const Ip6::Messag aMessage.SetOffset(offset); SuccessOrExit(error = aMessage.SetLength(offset + length)); - joinerMessageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal64()); + joinerMessageInfo.SetPeerAddr(Get().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); - netif.GetCoapSecure().HandleUdpReceive(aMessage, joinerMessageInfo); + Get().HandleUdpReceive(aMessage, joinerMessageInfo); exit: return; @@ -873,7 +863,7 @@ void Commissioner::HandleDatasetChanged(Coap::Message &aMessage, const Ip6::Mess otLogInfoMeshCoP("received dataset changed"); - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoMeshCoP("sent dataset changed acknowledgment"); @@ -898,9 +888,9 @@ void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::Mess if (Tlv::GetTlv(aMessage, Tlv::kProvisioningUrl, sizeof(provisioningUrl), provisioningUrl) == OT_ERROR_NONE) { - if (provisioningUrl.GetLength() != GetNetif().GetCoapSecure().GetDtls().mProvisioningUrl.GetLength() || + if (provisioningUrl.GetLength() != Get().GetDtls().mProvisioningUrl.GetLength() || memcmp(provisioningUrl.GetProvisioningUrl(), - GetNetif().GetCoapSecure().GetDtls().mProvisioningUrl.GetProvisioningUrl(), + Get().GetDtls().mProvisioningUrl.GetProvisioningUrl(), provisioningUrl.GetLength()) != 0) { state = StateTlv::kReject; @@ -923,14 +913,13 @@ void Commissioner::HandleJoinerFinalize(Coap::Message &aMessage, const Ip6::Mess void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, StateTlv::State aState) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::MessageInfo joinerMessageInfo; MeshCoP::StateTlv stateTlv; Coap::Message * message; Mac::ExtAddress extAddr; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -941,7 +930,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, State stateTlv.SetState(aState); SuccessOrExit(error = message->Append(&stateTlv, sizeof(stateTlv))); - joinerMessageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal64()); + joinerMessageInfo.SetPeerAddr(Get().GetMeshLocal64()); joinerMessageInfo.GetPeerAddr().SetIid(mJoinerIid); joinerMessageInfo.SetPeerPort(mJoinerPort); @@ -953,7 +942,7 @@ void Commissioner::SendJoinFinalizeResponse(const Coap::Message &aRequest, State otDumpCertMeshCoP("[THCI] direction=send | type=JOIN_FIN.rsp |", buf, message->GetLength() - message->GetOffset()); #endif - SuccessOrExit(error = netif.GetCoapSecure().SendMessage(*message, joinerMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, joinerMessageInfo)); memcpy(extAddr.m8, mJoinerIid, sizeof(extAddr.m8)); extAddr.SetLocal(!extAddr.IsLocal()); @@ -978,7 +967,6 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf { OT_UNUSED_VARIABLE(aMessageInfo); - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; JoinerUdpPortTlv udpPort; JoinerIidTlv iid; @@ -988,7 +976,7 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf uint16_t offset; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_RELAY_TX); @@ -1010,7 +998,7 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf { JoinerRouterKekTlv kek; kek.Init(); - kek.SetKek(netif.GetKeyManager().GetKek()); + kek.SetKek(Get().GetKek()); SuccessOrExit(error = message->Append(&kek, sizeof(kek))); } @@ -1021,12 +1009,12 @@ otError Commissioner::SendRelayTransmit(Message &aMessage, const Ip6::MessageInf SuccessOrExit(error = message->SetLength(offset + aMessage.GetLength())); aMessage.CopyTo(0, offset, aMessage.GetLength(), *message); - messageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetPeerAddr(Get().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(mJoinerRloc); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); aMessage.Free(); diff --git a/src/core/meshcop/dataset.cpp b/src/core/meshcop/dataset.cpp index b52a09eef..d6b0b86a9 100644 --- a/src/core/meshcop/dataset.cpp +++ b/src/core/meshcop/dataset.cpp @@ -40,6 +40,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/mle_tlvs.hpp" @@ -515,11 +516,11 @@ void Dataset::Remove(uint8_t *aStart, uint8_t aLength) otError Dataset::ApplyConfiguration(Instance &aInstance, bool *aIsMasterKeyUpdated) const { - ThreadNetif &netif = aInstance.GetThreadNetif(); - Mac::Mac & mac = netif.GetMac(); - otError error = OT_ERROR_NONE; - const Tlv * cur = reinterpret_cast(mTlvs); - const Tlv * end = reinterpret_cast(mTlvs + mLength); + Mac::Mac & mac = aInstance.Get(); + KeyManager &keyManager = aInstance.Get(); + otError error = OT_ERROR_NONE; + const Tlv * cur = reinterpret_cast(mTlvs); + const Tlv * end = reinterpret_cast(mTlvs + mLength); VerifyOrExit(IsValid(), error = OT_ERROR_PARSE); @@ -568,12 +569,12 @@ otError Dataset::ApplyConfiguration(Instance &aInstance, bool *aIsMasterKeyUpdat const NetworkMasterKeyTlv *key = static_cast(cur); if (aIsMasterKeyUpdated && - memcmp(&key->GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE)) + memcmp(&key->GetNetworkMasterKey(), &keyManager.GetMasterKey(), OT_MASTER_KEY_SIZE)) { *aIsMasterKeyUpdated = true; } - netif.GetKeyManager().SetMasterKey(key->GetNetworkMasterKey()); + keyManager.SetMasterKey(key->GetNetworkMasterKey()); break; } @@ -582,7 +583,7 @@ otError Dataset::ApplyConfiguration(Instance &aInstance, bool *aIsMasterKeyUpdat case Tlv::kPSKc: { const PSKcTlv *pskc = static_cast(cur); - netif.GetKeyManager().SetPSKc(pskc->GetPSKc()); + keyManager.SetPSKc(pskc->GetPSKc()); break; } @@ -591,15 +592,15 @@ otError Dataset::ApplyConfiguration(Instance &aInstance, bool *aIsMasterKeyUpdat case Tlv::kMeshLocalPrefix: { const MeshLocalPrefixTlv *prefix = static_cast(cur); - netif.GetMle().SetMeshLocalPrefix(prefix->GetMeshLocalPrefix()); + aInstance.Get().SetMeshLocalPrefix(prefix->GetMeshLocalPrefix()); break; } case Tlv::kSecurityPolicy: { const SecurityPolicyTlv *securityPolicy = static_cast(cur); - netif.GetKeyManager().SetKeyRotation(securityPolicy->GetRotationTime()); - netif.GetKeyManager().SetSecurityPolicyFlags(securityPolicy->GetFlags()); + keyManager.SetKeyRotation(securityPolicy->GetRotationTime()); + keyManager.SetSecurityPolicyFlags(securityPolicy->GetFlags()); break; } diff --git a/src/core/meshcop/dataset_local.cpp b/src/core/meshcop/dataset_local.cpp index e32c2ba05..9af9b5a67 100644 --- a/src/core/meshcop/dataset_local.cpp +++ b/src/core/meshcop/dataset_local.cpp @@ -40,6 +40,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/settings.hpp" #include "meshcop/dataset.hpp" @@ -62,7 +63,7 @@ void DatasetLocal::Clear(void) { mTimestamp.Init(); mTimestampPresent = false; - GetInstance().GetSettings().DeleteOperationalDataset(IsActive()); + Get().DeleteOperationalDataset(IsActive()); } otError DatasetLocal::Restore(Dataset &aDataset) @@ -95,7 +96,7 @@ otError DatasetLocal::Read(Dataset &aDataset) const uint32_t elapsed; otError error; - error = GetInstance().GetSettings().ReadOperationalDataset(IsActive(), aDataset); + error = Get().ReadOperationalDataset(IsActive(), aDataset); VerifyOrExit(error == OT_ERROR_NONE, aDataset.mLength = 0); if (mType == Tlv::kActiveTimestamp) @@ -164,12 +165,12 @@ otError DatasetLocal::Save(const Dataset &aDataset) if (aDataset.GetSize() == 0) { - error = GetInstance().GetSettings().DeleteOperationalDataset(IsActive()); + error = Get().DeleteOperationalDataset(IsActive()); otLogInfoMeshCoP("%s dataset deleted", mType == Tlv::kActiveTimestamp ? "Active" : "Pending"); } else { - error = GetInstance().GetSettings().SaveOperationalDataset(IsActive(), aDataset); + error = Get().SaveOperationalDataset(IsActive(), aDataset); otLogInfoMeshCoP("%s dataset set", mType == Tlv::kActiveTimestamp ? "Active" : "Pending"); } diff --git a/src/core/meshcop/dataset_manager.cpp b/src/core/meshcop/dataset_manager.cpp index 474df19c3..04a64f3a8 100644 --- a/src/core/meshcop/dataset_manager.cpp +++ b/src/core/meshcop/dataset_manager.cpp @@ -39,8 +39,8 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "phy/phy.hpp" @@ -163,10 +163,10 @@ otError DatasetManager::Save(const Dataset &aDataset) mLocal.Save(aDataset); #if OPENTHREAD_FTD - if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { - GetNetif().GetNetworkDataLeader().IncrementVersion(); - GetNetif().GetNetworkDataLeader().IncrementStableVersion(); + Get().IncrementVersion(); + Get().IncrementStableVersion(); } #endif } @@ -181,12 +181,11 @@ exit: otError DatasetManager::Save(const otOperationalDataset &aDataset) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; SuccessOrExit(error = mLocal.Save(aDataset)); - switch (netif.GetMle().GetRole()) + switch (Get().GetRole()) { case OT_DEVICE_ROLE_DISABLED: Restore(); @@ -202,8 +201,8 @@ otError DatasetManager::Save(const otOperationalDataset &aDataset) case OT_DEVICE_ROLE_LEADER: Restore(); - netif.GetNetworkDataLeader().IncrementVersion(); - netif.GetNetworkDataLeader().IncrementStableVersion(); + Get().IncrementVersion(); + Get().IncrementStableVersion(); break; #endif @@ -238,16 +237,14 @@ exit: void DatasetManager::HandleTimer(void) { - ThreadNetif &netif = GetNetif(); - - VerifyOrExit(netif.GetMle().IsAttached()); + VerifyOrExit(Get().IsAttached()); VerifyOrExit(mLocal.Compare(GetTimestamp()) < 0); if (mLocal.GetType() == Tlv::kActiveTimestamp) { Dataset dataset(Tlv::kPendingTimestamp); - netif.GetPendingDataset().Read(dataset); + Get().Read(dataset); const ActiveTimestampTlv *tlv = static_cast(dataset.Get(Tlv::kActiveTimestamp)); const Timestamp * pendingActiveTimestamp = static_cast(tlv); @@ -268,13 +265,12 @@ exit: otError DatasetManager::Register(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; Dataset dataset(mLocal.GetType()); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -284,10 +280,10 @@ otError DatasetManager::Register(void) mLocal.Read(dataset); SuccessOrExit(error = message->Append(dataset.GetBytes(), dataset.GetSize())); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent dataset to leader"); @@ -349,14 +345,13 @@ void DatasetManager::SendGetResponse(const Coap::Message & aRequest, uint8_t * aTlvs, uint8_t aLength) const { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message *message; Dataset dataset(mLocal.GetType()); mLocal.Read(dataset); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -369,7 +364,7 @@ void DatasetManager::SendGetResponse(const Coap::Message & aRequest, while (cur < end) { if (cur->GetType() != Tlv::kNetworkMasterKey || - (netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) + (Get().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) { SuccessOrExit(error = message->Append(cur, sizeof(Tlv) + cur->GetLength())); } @@ -384,7 +379,7 @@ void DatasetManager::SendGetResponse(const Coap::Message & aRequest, const Tlv *tlv; if (aTlvs[index] == Tlv::kNetworkMasterKey && - !(netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) + !(Get().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_OBTAIN_MASTER_KEY)) { continue; } @@ -402,7 +397,7 @@ void DatasetManager::SendGetResponse(const Coap::Message & aRequest, message->SetLength(message->GetLength() - 1); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent dataset get response"); @@ -416,12 +411,11 @@ exit: otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, const uint8_t *aTlvs, uint8_t aLength) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -430,7 +424,7 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con #if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - if (netif.GetCommissioner().IsActive()) + if (Get().IsActive()) { const Tlv *cur = reinterpret_cast(aTlvs); const Tlv *end = reinterpret_cast(aTlvs + aLength); @@ -451,7 +445,7 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con { CommissionerSessionIdTlv sessionId; sessionId.Init(); - sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(Get().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); } } @@ -551,10 +545,10 @@ otError DatasetManager::SendSetRequest(const otOperationalDataset &aDataset, con message->SetLength(message->GetLength() - 1); } - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent dataset set request to leader"); @@ -573,7 +567,6 @@ otError DatasetManager::SendGetRequest(const otOperationalDatasetComponents &aDa uint8_t aLength, const otIp6Address * aAddress) const { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo messageInfo; @@ -643,7 +636,7 @@ otError DatasetManager::SendGetRequest(const otOperationalDatasetComponents &aDa datasetTlvs[length++] = Tlv::kChannelMask; } - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -677,12 +670,12 @@ otError DatasetManager::SendGetRequest(const otOperationalDatasetComponents &aDa } else { - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); } - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent dataset get request"); @@ -707,7 +700,7 @@ ActiveDataset::ActiveDataset(Instance &aInstance) , mResourceSet(OT_URI_PATH_ACTIVE_SET, &ActiveDataset::HandleSet, this) #endif { - GetNetif().GetCoap().AddResource(mResourceGet); + Get().AddResource(mResourceGet); } otError ActiveDataset::Save(const Timestamp &aTimestamp, const Message &aMessage, uint16_t aOffset, uint8_t aLength) @@ -751,7 +744,7 @@ PendingDataset::PendingDataset(Instance &aInstance) , mResourceSet(OT_URI_PATH_PENDING_SET, &PendingDataset::HandleSet, this) #endif { - GetNetif().GetCoap().AddResource(mResourceGet); + Get().AddResource(mResourceGet); } void PendingDataset::Clear(void) @@ -847,7 +840,8 @@ void PendingDataset::HandleDelayTimer(void) otLogInfoMeshCoP("pending delay timer expired"); dataset.ConvertToActive(); - GetNetif().GetActiveDataset().Save(dataset); + + Get().Save(dataset); Clear(); diff --git a/src/core/meshcop/dataset_manager.hpp b/src/core/meshcop/dataset_manager.hpp index 4d2bdd0af..27a8ad8ba 100644 --- a/src/core/meshcop/dataset_manager.hpp +++ b/src/core/meshcop/dataset_manager.hpp @@ -241,6 +241,13 @@ protected: */ void HandleTimer(void); + /** + * This method re-defines template `Get()` as the `InstanceLoctaor` (base class) definition is shadowed by + * the public `Get(dataset)` methods in this class. + * + */ + template inline Type &Get(void) const { return InstanceLocator::Get(); } + DatasetLocal mLocal; Timestamp mTimestamp; bool mTimestampValid : 1; diff --git a/src/core/meshcop/dataset_manager_ftd.cpp b/src/core/meshcop/dataset_manager_ftd.cpp index 24523d61a..073ee6534 100644 --- a/src/core/meshcop/dataset_manager_ftd.cpp +++ b/src/core/meshcop/dataset_manager_ftd.cpp @@ -44,6 +44,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/timer.hpp" #include "meshcop/dataset.hpp" @@ -69,7 +70,6 @@ otError DatasetManager::AppendMleDatasetTlv(Message &aMessage) const otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); Tlv tlv; Timestamp * timestamp; uint16_t offset = aMessage.GetOffset(); @@ -97,7 +97,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf pendingTimestamp.SetLength(0); sessionId.SetLength(0); - VerifyOrExit(netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, state = StateTlv::kReject); + VerifyOrExit(Get().GetRole() == OT_DEVICE_ROLE_LEADER, state = StateTlv::kReject); // verify that TLV data size is less than maximum TLV value size while (offset < aMessage.GetLength()) @@ -135,7 +135,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf { VerifyOrExit(channel.IsValid(), state = StateTlv::kReject); - if (channel.GetChannel() != netif.GetMac().GetPanChannel()) + if (channel.GetChannel() != Get().GetPanChannel()) { doesAffectConnectivity = true; } @@ -143,7 +143,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf // check PAN ID if (Tlv::GetTlv(aMessage, Tlv::kPanId, sizeof(panId), panId) == OT_ERROR_NONE && panId.IsValid() && - panId.GetPanId() != netif.GetMac().GetPanId()) + panId.GetPanId() != Get().GetPanId()) { doesAffectConnectivity = true; } @@ -151,7 +151,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf // check mesh local prefix if (Tlv::GetTlv(aMessage, Tlv::kMeshLocalPrefix, sizeof(meshLocalPrefix), meshLocalPrefix) == OT_ERROR_NONE && meshLocalPrefix.IsValid() && - memcmp(&meshLocalPrefix.GetMeshLocalPrefix(), &netif.GetMle().GetMeshLocalPrefix(), + memcmp(&meshLocalPrefix.GetMeshLocalPrefix(), &Get().GetMeshLocalPrefix(), meshLocalPrefix.GetLength())) { doesAffectConnectivity = true; @@ -160,7 +160,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf // check network master key if (Tlv::GetTlv(aMessage, Tlv::kNetworkMasterKey, sizeof(masterKey), masterKey) == OT_ERROR_NONE && masterKey.IsValid() && - memcmp(&masterKey.GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE)) + memcmp(&masterKey.GetNetworkMasterKey(), &Get().GetMasterKey(), OT_MASTER_KEY_SIZE)) { doesAffectConnectivity = true; doesAffectMasterKey = true; @@ -169,10 +169,10 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf // check active timestamp rollback if (type == Tlv::kPendingTimestamp && (masterKey.GetLength() == 0 || - memcmp(&masterKey.GetNetworkMasterKey(), &netif.GetKeyManager().GetMasterKey(), OT_MASTER_KEY_SIZE) == 0)) + memcmp(&masterKey.GetNetworkMasterKey(), &Get().GetMasterKey(), OT_MASTER_KEY_SIZE) == 0)) { // no change to master key, active timestamp must be ahead - const Timestamp *localActiveTimestamp = netif.GetActiveDataset().GetTimestamp(); + const Timestamp *localActiveTimestamp = Get().GetTimestamp(); VerifyOrExit(localActiveTimestamp == NULL || localActiveTimestamp->Compare(activeTimestamp) > 0, state = StateTlv::kReject); @@ -186,7 +186,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf isUpdateFromCommissioner = true; localId = static_cast( - netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kCommissionerSessionId)); + Get().GetCommissioningDataSubTlv(Tlv::kCommissionerSessionId)); VerifyOrExit(sessionId.IsValid() && localId != NULL && localId->GetCommissionerSessionId() == sessionId.GetCommissionerSessionId(), @@ -201,7 +201,7 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf { // Thread specification allows partial dataset changes for MGMT_ACTIVE_SET.req/MGMT_PENDING_SET.req // from Commissioner based on existing active dataset. - netif.GetActiveDataset().Read(dataset); + Get().Read(dataset); } if (type == Tlv::kPendingTimestamp || !doesAffectConnectivity) @@ -236,9 +236,9 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf { delayTimerTlv->SetDelayTimer(DelayTimerTlv::kDelayTimerDefault); } - else if (delayTimerTlv->GetDelayTimer() < netif.GetLeader().GetDelayTimerMinimal()) + else if (delayTimerTlv->GetDelayTimer() < Get().GetDelayTimerMinimal()) { - delayTimerTlv->SetDelayTimer(netif.GetLeader().GetDelayTimerMinimal()); + delayTimerTlv->SetDelayTimer(Get().GetDelayTimerMinimal()); } } @@ -253,12 +253,12 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf } VerifyOrExit(Save(dataset) == OT_ERROR_NONE, state = StateTlv::kReject); - netif.GetNetworkDataLeader().IncrementVersion(); - netif.GetNetworkDataLeader().IncrementStableVersion(); + Get().IncrementVersion(); + Get().IncrementStableVersion(); } else { - netif.GetPendingDataset().ApplyActiveDataset(activeTimestamp, aMessage); + Get().ApplyActiveDataset(activeTimestamp, aMessage); } // notify commissioner if update is from thread device @@ -268,19 +268,19 @@ otError DatasetManager::HandleSet(Coap::Message &aMessage, const Ip6::MessageInf Ip6::Address destination; borderAgentLocator = static_cast( - netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); + Get().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL); memset(&destination, 0, sizeof(destination)); - destination = netif.GetMle().GetMeshLocal16(); + destination = Get().GetMeshLocal16(); destination.mFields.m16[7] = HostSwap16(borderAgentLocator->GetBorderAgentLocator()); - netif.GetLeader().SendDatasetChanged(destination); + Get().SendDatasetChanged(destination); } exit: - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { SendSetResponse(aMessage, aMessageInfo, state); } @@ -292,12 +292,11 @@ void DatasetManager::SendSetResponse(const Coap::Message & aRequest, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message *message; StateTlv state; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -306,7 +305,7 @@ void DatasetManager::SendSetResponse(const Coap::Message & aRequest, state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent dataset set response"); @@ -320,11 +319,10 @@ exit: otError ActiveDataset::GenerateLocal(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Dataset dataset(mLocal.GetType()); + otError error = OT_ERROR_NONE; + Dataset dataset(mLocal.GetType()); - VerifyOrExit(netif.GetMle().IsAttached(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(Get().IsAttached(), error = OT_ERROR_INVALID_STATE); mLocal.Read(dataset); @@ -343,7 +341,7 @@ otError ActiveDataset::GenerateLocal(void) { ChannelTlv tlv; tlv.Init(); - tlv.SetChannel(netif.GetMac().GetPanChannel()); + tlv.SetChannel(Get().GetPanChannel()); dataset.Set(tlv); } @@ -352,7 +350,7 @@ otError ActiveDataset::GenerateLocal(void) { ChannelMaskTlv tlv; tlv.Init(); - tlv.SetChannelMask(netif.GetMac().GetSupportedChannelMask().GetMask()); + tlv.SetChannelMask(Get().GetSupportedChannelMask().GetMask()); dataset.Set(tlv); } @@ -361,7 +359,7 @@ otError ActiveDataset::GenerateLocal(void) { ExtendedPanIdTlv tlv; tlv.Init(); - tlv.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); + tlv.SetExtendedPanId(Get().GetExtendedPanId()); dataset.Set(tlv); } @@ -370,7 +368,7 @@ otError ActiveDataset::GenerateLocal(void) { MeshLocalPrefixTlv tlv; tlv.Init(); - tlv.SetMeshLocalPrefix(netif.GetMle().GetMeshLocalPrefix()); + tlv.SetMeshLocalPrefix(Get().GetMeshLocalPrefix()); dataset.Set(tlv); } @@ -379,7 +377,7 @@ otError ActiveDataset::GenerateLocal(void) { NetworkMasterKeyTlv tlv; tlv.Init(); - tlv.SetNetworkMasterKey(netif.GetKeyManager().GetMasterKey()); + tlv.SetNetworkMasterKey(Get().GetMasterKey()); dataset.Set(tlv); } @@ -388,7 +386,7 @@ otError ActiveDataset::GenerateLocal(void) { NetworkNameTlv tlv; tlv.Init(); - tlv.SetNetworkName(netif.GetMac().GetNetworkName()); + tlv.SetNetworkName(Get().GetNetworkName()); dataset.Set(tlv); } @@ -397,7 +395,7 @@ otError ActiveDataset::GenerateLocal(void) { PanIdTlv tlv; tlv.Init(); - tlv.SetPanId(netif.GetMac().GetPanId()); + tlv.SetPanId(Get().GetPanId()); dataset.Set(tlv); } @@ -406,7 +404,7 @@ otError ActiveDataset::GenerateLocal(void) { PSKcTlv tlv; tlv.Init(); - tlv.SetPSKc(netif.GetKeyManager().GetPSKc()); + tlv.SetPSKc(Get().GetPSKc()); dataset.Set(tlv); } @@ -415,8 +413,8 @@ otError ActiveDataset::GenerateLocal(void) { SecurityPolicyTlv tlv; tlv.Init(); - tlv.SetRotationTime(static_cast(netif.GetKeyManager().GetKeyRotation())); - tlv.SetFlags(netif.GetKeyManager().GetSecurityPolicyFlags()); + tlv.SetRotationTime(static_cast(Get().GetKeyRotation())); + tlv.SetFlags(Get().GetSecurityPolicyFlags()); dataset.Set(tlv); } @@ -432,12 +430,12 @@ exit: void ActiveDataset::StartLeader(void) { GenerateLocal(); - GetNetif().GetCoap().AddResource(mResourceSet); + Get().AddResource(mResourceSet); } void ActiveDataset::StopLeader(void) { - GetNetif().GetCoap().RemoveResource(mResourceSet); + Get().RemoveResource(mResourceSet); } void ActiveDataset::HandleSet(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -458,12 +456,12 @@ exit: void PendingDataset::StartLeader(void) { StartDelayTimer(); - GetNetif().GetCoap().AddResource(mResourceSet); + Get().AddResource(mResourceSet); } void PendingDataset::StopLeader(void) { - GetNetif().GetCoap().RemoveResource(mResourceSet); + Get().RemoveResource(mResourceSet); } void PendingDataset::HandleSet(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -483,12 +481,11 @@ exit: void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Coap::Message &aMessage) { - ThreadNetif & netif = GetNetif(); uint16_t offset = aMessage.GetOffset(); Dataset dataset(mLocal.GetType()); DelayTimerTlv delayTimer; - VerifyOrExit(netif.GetMle().IsAttached()); + VerifyOrExit(Get().IsAttached()); while (offset < aMessage.GetLength()) { @@ -507,7 +504,7 @@ void PendingDataset::ApplyActiveDataset(const Timestamp &aTimestamp, Coap::Messa // add delay timer tlv delayTimer.Init(); - delayTimer.SetDelayTimer(netif.GetLeader().GetDelayTimerMinimal()); + delayTimer.SetDelayTimer(Get().GetDelayTimerMinimal()); dataset.Set(delayTimer); // add pending timestamp tlv diff --git a/src/core/meshcop/dtls.cpp b/src/core/meshcop/dtls.cpp index 1651cd829..7eab9d839 100644 --- a/src/core/meshcop/dtls.cpp +++ b/src/core/meshcop/dtls.cpp @@ -45,9 +45,9 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/new.hpp" -#include "common/owner-locator.hpp" #include "common/timer.hpp" #include "crypto/sha256.hpp" #include "thread/thread_netif.hpp" @@ -73,7 +73,7 @@ Dtls::Dtls(Instance &aInstance, bool aLayerTwoSecurity) , mReceiveHandler(NULL) , mSendHandler(NULL) , mContext(NULL) - , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mSocket(Get()) , mTransportCallback(NULL) , mTransportContext(NULL) , mMessageSubType(Message::kSubTypeNone) @@ -206,8 +206,6 @@ void Dtls::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessage void Dtls::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - switch (mState) { case MeshCoP::Dtls::kStateClosed: @@ -225,7 +223,7 @@ void Dtls::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageI mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort()); mPeerAddress.SetInterfaceId(aMessageInfo.GetInterfaceId()); - if (netif.IsUnicastAddress(aMessageInfo.GetSockAddr())) + if (Get().IsUnicastAddress(aMessageInfo.GetSockAddr())) { mPeerAddress.SetSockAddr(aMessageInfo.GetSockAddr()); } @@ -815,7 +813,7 @@ int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret, sha256.Update(aKeyBlock, 2 * static_cast(aMacLength + aKeyLength + aIvLength)); sha256.Finish(kek); - GetNetif().GetKeyManager().SetKek(kek); + Get().SetKek(kek); if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8) { diff --git a/src/core/meshcop/energy_scan_client.cpp b/src/core/meshcop/energy_scan_client.cpp index 1229099f2..05da7fc20 100644 --- a/src/core/meshcop/energy_scan_client.cpp +++ b/src/core/meshcop/energy_scan_client.cpp @@ -42,6 +42,7 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -58,7 +59,7 @@ EnergyScanClient::EnergyScanClient(Instance &aInstance) { mContext = NULL; mCallback = NULL; - GetNetif().GetCoap().AddResource(mEnergyScan); + Get().AddResource(mEnergyScan); } otError EnergyScanClient::SendQuery(uint32_t aChannelMask, @@ -69,7 +70,6 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelM otCommissionerEnergyReportCallback aCallback, void * aContext) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; MeshCoP::CommissionerSessionIdTlv sessionId; MeshCoP::ChannelMaskTlv channelMask; @@ -79,8 +79,8 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelM Ip6::MessageInfo messageInfo; Coap::Message * message = NULL; - VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit(Get().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -88,7 +88,7 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelM message->SetPayloadMarker(); sessionId.Init(); - sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(Get().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -107,11 +107,11 @@ otError EnergyScanClient::SendQuery(uint32_t aChannelM scanDuration.SetScanDuration(aScanDuration); SuccessOrExit(error = message->Append(&scanDuration, sizeof(scanDuration))); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent energy scan query"); @@ -136,8 +136,7 @@ void EnergyScanClient::HandleReport(void *aContext, otMessage *aMessage, const o void EnergyScanClient::HandleReport(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - uint32_t mask; + uint32_t mask; OT_TOOL_PACKED_BEGIN struct @@ -160,7 +159,7 @@ void EnergyScanClient::HandleReport(Coap::Message &aMessage, const Ip6::MessageI mCallback(mask, energyList.list, energyList.tlv.GetLength(), mContext); } - SuccessOrExit(netif.GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoMeshCoP("sent energy scan report response"); diff --git a/src/core/meshcop/joiner.cpp b/src/core/meshcop/joiner.cpp index 50207c407..cea472d7d 100644 --- a/src/core/meshcop/joiner.cpp +++ b/src/core/meshcop/joiner.cpp @@ -45,8 +45,8 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "mac/mac_frame.hpp" #include "meshcop/meshcop.hpp" #include "thread/thread_netif.hpp" @@ -74,7 +74,7 @@ Joiner::Joiner(Instance &aInstance) , mJoinerEntrust(OT_URI_PATH_JOINER_ENTRUST, &Joiner::HandleJoinerEntrust, this) { memset(mJoinerRouters, 0, sizeof(mJoinerRouters)); - GetNetif().GetCoap().AddResource(mJoinerEntrust); + Get().AddResource(mJoinerEntrust); } void Joiner::GetJoinerId(Mac::ExtAddress &aJoinerId) const @@ -92,7 +92,6 @@ otError Joiner::Start(const char * aPSKd, otJoinerCallback aCallback, void * aContext) { - ThreadNetif & netif = GetNetif(); otError error; Mac::ExtAddress joinerId; Crc16 ccitt(Crc16::kCcitt); @@ -100,12 +99,12 @@ otError Joiner::Start(const char * aPSKd, VerifyOrExit(mState == OT_JOINER_STATE_IDLE, error = OT_ERROR_BUSY); - GetNotifier().Signal(OT_CHANGED_JOINER_STATE); + Get().Signal(OT_CHANGED_JOINER_STATE); // use extended address based on factory-assigned IEEE EUI-64 GetJoinerId(joinerId); - netif.GetMac().SetExtAddress(joinerId); - netif.GetMle().UpdateLinkLocalAddress(); + Get().SetExtAddress(joinerId); + Get().UpdateLinkLocalAddress(); for (size_t i = 0; i < sizeof(joinerId); i++) { @@ -116,19 +115,20 @@ otError Joiner::Start(const char * aPSKd, mCcitt = ccitt.Get(); mAnsi = ansi.Get(); - error = netif.GetCoapSecure().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT); + error = Get().Start(OPENTHREAD_CONFIG_JOINER_UDP_PORT); SuccessOrExit(error); - error = netif.GetCoapSecure().SetPsk(reinterpret_cast(aPSKd), static_cast(strlen(aPSKd))); + error = + Get().SetPsk(reinterpret_cast(aPSKd), static_cast(strlen(aPSKd))); SuccessOrExit(error); - error = netif.GetCoapSecure().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); + error = Get().GetDtls().mProvisioningUrl.SetProvisioningUrl(aProvisioningUrl); SuccessOrExit(error); memset(mJoinerRouters, 0, sizeof(mJoinerRouters)); - SuccessOrExit(error = netif.GetMle().Discover(Mac::ChannelMask(0), netif.GetMac().GetPanId(), true, false, - HandleDiscoverResult, this)); + SuccessOrExit(error = Get().Discover(Mac::ChannelMask(0), Get().GetPanId(), true, false, + HandleDiscoverResult, this)); mVendorName = aVendorName; mVendorModel = aVendorModel; @@ -154,20 +154,17 @@ otJoinerState Joiner::GetState(void) const void Joiner::Close(void) { - ThreadNetif &netif = GetNetif(); - - netif.GetCoapSecure().Disconnect(); - netif.GetIp6Filter().RemoveUnsecurePort(OPENTHREAD_CONFIG_JOINER_UDP_PORT); + Get().Disconnect(); + Get().RemoveUnsecurePort(OPENTHREAD_CONFIG_JOINER_UDP_PORT); } void Joiner::Complete(otError aError) { - ThreadNetif &netif = GetNetif(); - mState = OT_JOINER_STATE_IDLE; - otError error = OT_ERROR_NOT_FOUND; - GetNotifier().Signal(OT_CHANGED_JOINER_STATE); + mState = OT_JOINER_STATE_IDLE; + otError error = OT_ERROR_NOT_FOUND; + Get().Signal(OT_CHANGED_JOINER_STATE); - netif.GetCoapSecure().Disconnect(); + Get().Disconnect(); if (aError != OT_ERROR_NONE && aError != OT_ERROR_NOT_FOUND) { @@ -176,7 +173,7 @@ void Joiner::Complete(otError aError) if (error == OT_ERROR_NOT_FOUND && mCallback) { - netif.GetCoapSecure().Stop(); + Get().Stop(); otJoinerCallback callback = mCallback; mCallback = NULL; callback(aError, mContext); @@ -268,7 +265,6 @@ void Joiner::AddJoinerRouter(JoinerRouter &aJoinerRouter) otError Joiner::TryNextJoin() { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NOT_FOUND; JoinerRouter *joinerRouter = &mJoinerRouters[0]; @@ -286,16 +282,16 @@ otError Joiner::TryNextJoin() joinerRouter->mPriority = 0; - netif.GetMac().SetPanId(joinerRouter->mPanId); - netif.GetMac().SetPanChannel(joinerRouter->mChannel); - netif.GetIp6Filter().AddUnsecurePort(OPENTHREAD_CONFIG_JOINER_UDP_PORT); + Get().SetPanId(joinerRouter->mPanId); + Get().SetPanChannel(joinerRouter->mChannel); + Get().AddUnsecurePort(OPENTHREAD_CONFIG_JOINER_UDP_PORT); sockaddr.GetAddress().mFields.m16[0] = HostSwap16(0xfe80); sockaddr.GetAddress().SetIid(joinerRouter->mExtAddr); sockaddr.mPort = joinerRouter->mJoinerUdpPort; sockaddr.mScopeId = OT_NETIF_INTERFACE_ID_THREAD; - netif.GetCoapSecure().Connect(sockaddr, Joiner::HandleSecureCoapClientConnect, this); + Get().Connect(sockaddr, Joiner::HandleSecureCoapClientConnect, this); mState = OT_JOINER_STATE_CONNECT; error = OT_ERROR_NONE; } @@ -337,7 +333,6 @@ void Joiner::HandleSecureCoapClientConnect(bool aConnected) void Joiner::SendJoinerFinalize(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; StateTlv stateTlv; @@ -346,7 +341,7 @@ void Joiner::SendJoinerFinalize(void) VendorSwVersionTlv vendorSwVersionTlv; VendorStackVersionTlv vendorStackVersionTlv; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoapSecure())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_JOINER_FINALIZE); @@ -384,10 +379,10 @@ void Joiner::SendJoinerFinalize(void) SuccessOrExit(error = message->Append(&vendorDataTlv, vendorDataTlv.GetSize())); } - if (netif.GetCoapSecure().GetDtls().mProvisioningUrl.GetLength() > 0) + if (Get().GetDtls().mProvisioningUrl.GetLength() > 0) { - SuccessOrExit(error = message->Append(&netif.GetCoapSecure().GetDtls().mProvisioningUrl, - netif.GetCoapSecure().GetDtls().mProvisioningUrl.GetSize())); + SuccessOrExit(error = message->Append(&Get().GetDtls().mProvisioningUrl, + Get().GetDtls().mProvisioningUrl.GetSize())); } #if OPENTHREAD_ENABLE_CERT_LOG @@ -398,7 +393,7 @@ void Joiner::SendJoinerFinalize(void) otDumpCertMeshCoP("[THCI] direction=send | type=JOIN_FIN.req |", buf, message->GetLength() - message->GetOffset()); #endif - SuccessOrExit(error = netif.GetCoapSecure().SendMessage(*message, Joiner::HandleJoinerFinalizeResponse, this)); + SuccessOrExit(error = Get().SendMessage(*message, Joiner::HandleJoinerFinalizeResponse, this)); otLogInfoMeshCoP("Sent joiner finalize"); @@ -457,7 +452,6 @@ void Joiner::HandleJoinerEntrust(void *aContext, otMessage *aMessage, const otMe void Joiner::HandleJoinerEntrust(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error; NetworkMasterKeyTlv masterKey; MeshLocalPrefixTlv meshLocalPrefix; @@ -491,17 +485,17 @@ void Joiner::HandleJoinerEntrust(Coap::Message &aMessage, const Ip6::MessageInfo SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kNetworkKeySequence, sizeof(networkKeySeq), networkKeySeq)); VerifyOrExit(networkKeySeq.IsValid(), error = OT_ERROR_PARSE); - netif.GetKeyManager().SetMasterKey(masterKey.GetNetworkMasterKey()); - netif.GetKeyManager().SetCurrentKeySequence(networkKeySeq.GetNetworkKeySequence()); - netif.GetMle().SetMeshLocalPrefix(meshLocalPrefix.GetMeshLocalPrefix()); - netif.GetMac().SetExtendedPanId(extendedPanId.GetExtendedPanId()); + Get().SetMasterKey(masterKey.GetNetworkMasterKey()); + Get().SetCurrentKeySequence(networkKeySeq.GetNetworkKeySequence()); + Get().SetMeshLocalPrefix(meshLocalPrefix.GetMeshLocalPrefix()); + Get().SetExtendedPanId(extendedPanId.GetExtendedPanId()); { otNetworkName name; memcpy(name.m8, networkName.GetNetworkName(), networkName.GetLength()); name.m8[networkName.GetLength()] = '\0'; - netif.GetMac().SetNetworkName(name.m8); + Get().SetNetworkName(name.m8); } otLogInfoMeshCoP("join success!"); @@ -522,17 +516,16 @@ exit: void Joiner::SendJoinerEntrustResponse(const Coap::Message &aRequest, const Ip6::MessageInfo &aRequestInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; Ip6::MessageInfo responseInfo(aRequestInfo); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetSubType(Message::kSubTypeJoinerEntrust); memset(&responseInfo.mSockAddr, 0, sizeof(responseInfo.mSockAddr)); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, responseInfo)); + SuccessOrExit(error = Get().SendMessage(*message, responseInfo)); mState = OT_JOINER_STATE_JOINED; @@ -556,8 +549,7 @@ void Joiner::HandleTimer(Timer &aTimer) void Joiner::HandleTimer(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; switch (mState) { @@ -576,8 +568,8 @@ void Joiner::HandleTimer(void) Mac::ExtAddress extAddress; extAddress.GenerateRandom(); - netif.GetMac().SetExtAddress(extAddress); - netif.GetMle().UpdateLinkLocalAddress(); + Get().SetExtAddress(extAddress); + Get().UpdateLinkLocalAddress(); error = OT_ERROR_NONE; break; diff --git a/src/core/meshcop/joiner_router.cpp b/src/core/meshcop/joiner_router.cpp index b22e3a1ea..bf9833c7f 100644 --- a/src/core/meshcop/joiner_router.cpp +++ b/src/core/meshcop/joiner_router.cpp @@ -42,8 +42,8 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/mle.hpp" @@ -57,7 +57,7 @@ namespace MeshCoP { JoinerRouter::JoinerRouter(Instance &aInstance) : InstanceLocator(aInstance) - , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mSocket(aInstance.Get()) , mRelayTransmit(OT_URI_PATH_RELAY_TX, &JoinerRouter::HandleRelayTransmit, this) , mTimer(aInstance, &JoinerRouter::HandleTimer, this) , mNotifierCallback(aInstance, &JoinerRouter::HandleStateChanged, this) @@ -65,7 +65,7 @@ JoinerRouter::JoinerRouter(Instance &aInstance) , mIsJoinerPortConfigured(false) , mExpectJoinEntRsp(false) { - GetNetif().GetCoap().AddResource(mRelayTransmit); + Get().AddResource(mRelayTransmit); } void JoinerRouter::HandleStateChanged(Notifier::Callback &aCallback, otChangedFlags aFlags) @@ -75,14 +75,12 @@ void JoinerRouter::HandleStateChanged(Notifier::Callback &aCallback, otChangedFl void JoinerRouter::HandleStateChanged(otChangedFlags aFlags) { - ThreadNetif &netif = GetNetif(); - - VerifyOrExit(netif.GetMle().IsFullThreadDevice()); + VerifyOrExit(Get().IsFullThreadDevice()); VerifyOrExit(aFlags & OT_CHANGED_THREAD_NETDATA); - netif.GetIp6Filter().RemoveUnsecurePort(mSocket.GetSockName().mPort); + Get().RemoveUnsecurePort(mSocket.GetSockName().mPort); - if (netif.GetNetworkDataLeader().IsJoiningEnabled()) + if (Get().IsJoiningEnabled()) { Ip6::SockAddr sockaddr; @@ -90,7 +88,7 @@ void JoinerRouter::HandleStateChanged(otChangedFlags aFlags) mSocket.Open(&JoinerRouter::HandleUdpReceive, this); mSocket.Bind(sockaddr); - netif.GetIp6Filter().AddUnsecurePort(sockaddr.mPort); + Get().AddUnsecurePort(sockaddr.mPort); otLogInfoMeshCoP("Joiner Router: start"); } else @@ -109,8 +107,8 @@ uint16_t JoinerRouter::GetJoinerUdpPort(void) VerifyOrExit(!mIsJoinerPortConfigured, rval = mJoinerUdpPort); - joinerUdpPort = static_cast( - GetNetif().GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kJoinerUdpPort)); + joinerUdpPort = + static_cast(Get().GetCommissioningDataSubTlv(Tlv::kJoinerUdpPort)); VerifyOrExit(joinerUdpPort != NULL); rval = joinerUdpPort->GetUdpPort(); @@ -134,7 +132,6 @@ void JoinerRouter::HandleUdpReceive(void *aContext, otMessage *aMessage, const o void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; @@ -147,9 +144,9 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a otLogInfoMeshCoP("JoinerRouter::HandleUdpReceive"); - SuccessOrExit(error = GetBorderAgentRloc(GetNetif(), borderAgentRloc)); + SuccessOrExit(error = GetBorderAgentRloc(Get(), borderAgentRloc)); - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -165,7 +162,7 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(error = message->Append(&iid, sizeof(iid))); rloc.Init(); - rloc.SetJoinerRouterLocator(netif.GetMle().GetRloc16()); + rloc.SetJoinerRouterLocator(Get().GetRloc16()); SuccessOrExit(error = message->Append(&rloc, sizeof(rloc))); tlv.SetType(Tlv::kJoinerDtlsEncapsulation); @@ -175,12 +172,12 @@ void JoinerRouter::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &a SuccessOrExit(error = message->SetLength(offset + tlv.GetLength())); aMessage.CopyTo(aMessage.GetOffset(), offset, tlv.GetLength(), *message); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); - messageInfo.SetPeerAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); + messageInfo.SetPeerAddr(Get().GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(borderAgentRloc); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("Sent relay rx"); @@ -249,7 +246,7 @@ void JoinerRouter::HandleRelayTransmit(Coap::Message &aMessage, const Ip6::Messa messageInfo.mPeerAddr.mFields.m16[0] = HostSwap16(0xfe80); memcpy(messageInfo.mPeerAddr.mFields.m8 + 8, joinerIid.GetIid(), 8); messageInfo.SetPeerPort(joinerPort.GetUdpPort()); - messageInfo.SetInterfaceId(GetNetif().GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); @@ -269,7 +266,6 @@ exit: otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessageInfo, const JoinerRouterKekTlv &aKek) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; @@ -284,7 +280,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage DelayedJoinEntHeader delayedMessage; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_JOINER_ENTRUST); @@ -292,22 +288,23 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage message->SetSubType(Message::kSubTypeJoinerEntrust); masterKey.Init(); - masterKey.SetNetworkMasterKey(netif.GetKeyManager().GetMasterKey()); + masterKey.SetNetworkMasterKey(Get().GetMasterKey()); SuccessOrExit(error = message->Append(&masterKey, sizeof(masterKey))); meshLocalPrefix.Init(); - meshLocalPrefix.SetMeshLocalPrefix(netif.GetMle().GetMeshLocalPrefix()); + meshLocalPrefix.SetMeshLocalPrefix(Get().GetMeshLocalPrefix()); SuccessOrExit(error = message->Append(&meshLocalPrefix, sizeof(meshLocalPrefix))); extendedPanId.Init(); - extendedPanId.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); + extendedPanId.SetExtendedPanId(Get().GetExtendedPanId()); SuccessOrExit(error = message->Append(&extendedPanId, sizeof(extendedPanId))); networkName.Init(); - networkName.SetNetworkName(netif.GetMac().GetNetworkName()); + networkName.SetNetworkName(Get().GetNetworkName()); SuccessOrExit(error = message->Append(&networkName, sizeof(Tlv) + networkName.GetLength())); - netif.GetActiveDataset().Read(dataset); + Get().Read(dataset); + if ((tlv = dataset.Get(Tlv::kActiveTimestamp)) != NULL) { SuccessOrExit(error = message->Append(tlv, sizeof(Tlv) + tlv->GetLength())); @@ -353,7 +350,7 @@ otError JoinerRouter::DelaySendingJoinerEntrust(const Ip6::MessageInfo &aMessage } networkKeySequence.Init(); - networkKeySequence.SetNetworkKeySequence(netif.GetKeyManager().GetCurrentKeySequence()); + networkKeySequence.SetNetworkKeySequence(Get().GetCurrentKeySequence()); SuccessOrExit(error = message->Append(&networkKeySequence, networkKeySequence.GetSize())); messageInfo = aMessageInfo; @@ -390,7 +387,6 @@ void JoinerRouter::HandleTimer(void) void JoinerRouter::SendDelayedJoinerEntrust(void) { - ThreadNetif & netif = GetNetif(); DelayedJoinEntHeader delayedJoinEnt; Coap::Message * message = static_cast(mDelayedJoinEnts.GetHead()); uint32_t now = TimerMilli::GetNow(); @@ -403,7 +399,7 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) // The message can be sent during CoAP transaction if KEK did not change (i.e. retransmission). VerifyOrExit(!mExpectJoinEntRsp || - memcmp(netif.GetKeyManager().GetKek(), delayedJoinEnt.GetKek(), KeyManager::kMaxKeyLength) == 0); + memcmp(Get().GetKek(), delayedJoinEnt.GetKek(), KeyManager::kMaxKeyLength) == 0); if (delayedJoinEnt.IsLater(now)) { @@ -417,7 +413,7 @@ void JoinerRouter::SendDelayedJoinerEntrust(void) DelayedJoinEntHeader::RemoveFrom(*message); // Set KEK to one used for this message. - netif.GetKeyManager().SetKek(delayedJoinEnt.GetKek()); + Get().SetKek(delayedJoinEnt.GetKek()); // Send the message. memcpy(&messageInfo, delayedJoinEnt.GetMessageInfo(), sizeof(messageInfo)); @@ -435,14 +431,13 @@ exit: otError JoinerRouter::SendJoinerEntrust(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif &netif = GetNetif(); - otError error; + otError error; - netif.GetCoap().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this); + Get().AbortTransaction(&JoinerRouter::HandleJoinerEntrustResponse, this); otLogInfoMeshCoP("Sending JOIN_ENT.ntf"); - SuccessOrExit( - error = netif.GetCoap().SendMessage(aMessage, aMessageInfo, &JoinerRouter::HandleJoinerEntrustResponse, this)); + SuccessOrExit(error = Get().SendMessage(aMessage, aMessageInfo, + &JoinerRouter::HandleJoinerEntrustResponse, this)); otLogInfoMeshCoP("Sent joiner entrust length = %d", aMessage.GetLength()); otLogCertMeshCoP("[THCI] direction=send | type=JOIN_ENT.ntf"); diff --git a/src/core/meshcop/leader.cpp b/src/core/meshcop/leader.cpp index 03f747ab5..fc390bd2f 100644 --- a/src/core/meshcop/leader.cpp +++ b/src/core/meshcop/leader.cpp @@ -44,8 +44,8 @@ #include "coap/coap_message.hpp" #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -63,8 +63,8 @@ Leader::Leader(Instance &aInstance) , mDelayTimerMinimal(DelayTimerTlv::kDelayTimerMinimal) , mSessionId(Random::GetUint16()) { - GetNetif().GetCoap().AddResource(mPetition); - GetNetif().GetCoap().AddResource(mKeepAlive); + Get().AddResource(mPetition); + Get().AddResource(mKeepAlive); } void Leader::HandlePetition(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -83,7 +83,7 @@ void Leader::HandlePetition(Coap::Message &aMessage, const Ip6::MessageInfo &aMe otLogInfoMeshCoP("received petition"); - VerifyOrExit(GetNetif().GetMle().IsRoutingLocator(aMessageInfo.GetPeerAddr())); + VerifyOrExit(Get().IsRoutingLocator(aMessageInfo.GetPeerAddr())); SuccessOrExit(Tlv::GetTlv(aMessage, Tlv::kCommissionerId, sizeof(commissionerId), commissionerId)); VerifyOrExit(commissionerId.IsValid()); @@ -107,7 +107,7 @@ void Leader::HandlePetition(Coap::Message &aMessage, const Ip6::MessageInfo &aMe data.mSteeringData.Clear(); SuccessOrExit( - GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&data), data.GetLength())); + Get().SetCommissioningData(reinterpret_cast(&data), data.GetLength())); mCommissionerId = commissionerId; @@ -122,13 +122,12 @@ otError Leader::SendPetitionResponse(const Coap::Message & aRequest, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; StateTlv state; CommissionerSessionIdTlv sessionId; Coap::Message * message; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -150,7 +149,7 @@ otError Leader::SendPetitionResponse(const Coap::Message & aRequest, SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent petition response"); @@ -172,7 +171,6 @@ void Leader::HandleKeepAlive(void *aContext, otMessage *aMessage, const otMessag void Leader::HandleKeepAlive(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - NetworkData::Leader & netdata = GetNetif().GetNetworkDataLeader(); StateTlv state; CommissionerSessionIdTlv sessionId; BorderAgentLocatorTlv * borderAgentLocator; @@ -186,8 +184,8 @@ void Leader::HandleKeepAlive(Coap::Message &aMessage, const Ip6::MessageInfo &aM SuccessOrExit(Tlv::GetTlv(aMessage, Tlv::kCommissionerSessionId, sizeof(sessionId), sessionId)); VerifyOrExit(sessionId.IsValid()); - borderAgentLocator = - static_cast(netdata.GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); + borderAgentLocator = static_cast( + Get().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); if ((borderAgentLocator == NULL) || (sessionId.GetCommissionerSessionId() != mSessionId)) { @@ -205,7 +203,7 @@ void Leader::HandleKeepAlive(Coap::Message &aMessage, const Ip6::MessageInfo &aM if (borderAgentLocator->GetBorderAgentLocator() != rloc) { borderAgentLocator->SetBorderAgentLocator(rloc); - netdata.IncrementVersion(); + Get().IncrementVersion(); } responseState = StateTlv::kAccept; @@ -222,12 +220,11 @@ otError Leader::SendKeepAliveResponse(const Coap::Message & aRequest, const Ip6::MessageInfo &aMessageInfo, StateTlv::State aState) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; StateTlv state; Coap::Message *message; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -236,7 +233,7 @@ otError Leader::SendKeepAliveResponse(const Coap::Message & aRequest, state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent keep alive response"); @@ -252,21 +249,20 @@ exit: otError Leader::SendDatasetChanged(const Ip6::Address &aAddress) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::MessageInfo messageInfo; Coap::Message * message; - VerifyOrExit((message = NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); message->AppendUriPathOptions(OT_URI_PATH_DATASET_CHANGED); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent dataset changed"); @@ -303,7 +299,7 @@ void Leader::HandleTimer(Timer &aTimer) void Leader::HandleTimer(void) { - VerifyOrExit(GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER); + VerifyOrExit(Get().GetRole() == OT_DEVICE_ROLE_LEADER); ResignCommissioner(); @@ -318,8 +314,8 @@ void Leader::SetEmptyCommissionerData(void) mCommissionerSessionId.Init(); mCommissionerSessionId.SetCommissionerSessionId(++mSessionId); - GetNetif().GetNetworkDataLeader().SetCommissioningData(reinterpret_cast(&mCommissionerSessionId), - sizeof(Tlv) + mCommissionerSessionId.GetLength()); + Get().SetCommissioningData(reinterpret_cast(&mCommissionerSessionId), + sizeof(Tlv) + mCommissionerSessionId.GetLength()); } void Leader::ResignCommissioner(void) diff --git a/src/core/meshcop/meshcop.cpp b/src/core/meshcop/meshcop.cpp index 2d1dc1c76..e6c8c68c3 100644 --- a/src/core/meshcop/meshcop.cpp +++ b/src/core/meshcop/meshcop.cpp @@ -31,6 +31,7 @@ * This file implements common MeshCoP utility functions. */ +#include "common/locator-getters.hpp" #include "crypto/sha256.hpp" #include "mac/mac_frame.hpp" #include "thread/thread_netif.hpp" @@ -57,7 +58,7 @@ otError GetBorderAgentRloc(ThreadNetif &aNetif, uint16_t &aRloc) BorderAgentLocatorTlv *borderAgentLocator; borderAgentLocator = static_cast( - aNetif.GetNetworkDataLeader().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); + aNetif.Get().GetCommissioningDataSubTlv(Tlv::kBorderAgentLocator)); VerifyOrExit(borderAgentLocator != NULL, error = OT_ERROR_NOT_FOUND); aRloc = borderAgentLocator->GetBorderAgentLocator(); diff --git a/src/core/meshcop/panid_query_client.cpp b/src/core/meshcop/panid_query_client.cpp index f125ca97c..44344af7c 100644 --- a/src/core/meshcop/panid_query_client.cpp +++ b/src/core/meshcop/panid_query_client.cpp @@ -41,6 +41,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -57,7 +58,7 @@ PanIdQueryClient::PanIdQueryClient(Instance &aInstance) , mContext(NULL) , mPanIdQuery(OT_URI_PATH_PANID_CONFLICT, &PanIdQueryClient::HandleConflict, this) { - GetNetif().GetCoap().AddResource(mPanIdQuery); + Get().AddResource(mPanIdQuery); } otError PanIdQueryClient::SendQuery(uint16_t aPanId, @@ -66,7 +67,6 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, otCommissionerPanIdConflictCallback aCallback, void * aContext) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; MeshCoP::CommissionerSessionIdTlv sessionId; MeshCoP::ChannelMaskTlv channelMask; @@ -74,8 +74,8 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, Ip6::MessageInfo messageInfo; Coap::Message * message = NULL; - VerifyOrExit(netif.GetCommissioner().IsActive(), error = OT_ERROR_INVALID_STATE); - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit(Get().IsActive(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(aAddress.IsMulticast() ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -83,7 +83,7 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, message->SetPayloadMarker(); sessionId.Init(); - sessionId.SetCommissionerSessionId(netif.GetCommissioner().GetSessionId()); + sessionId.SetCommissionerSessionId(Get().GetSessionId()); SuccessOrExit(error = message->Append(&sessionId, sizeof(sessionId))); channelMask.Init(); @@ -94,11 +94,11 @@ otError PanIdQueryClient::SendQuery(uint16_t aPanId, panId.SetPanId(aPanId); SuccessOrExit(error = message->Append(&panId, sizeof(panId))); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aAddress); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent panid query"); @@ -123,7 +123,6 @@ void PanIdQueryClient::HandleConflict(void *aContext, otMessage *aMessage, const void PanIdQueryClient::HandleConflict(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); MeshCoP::PanIdTlv panId; Ip6::MessageInfo responseInfo(aMessageInfo); uint32_t mask; @@ -142,7 +141,7 @@ void PanIdQueryClient::HandleConflict(Coap::Message &aMessage, const Ip6::Messag mCallback(panId.GetPanId(), mask, mContext); } - SuccessOrExit(netif.GetCoap().SendEmptyAck(aMessage, responseInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); otLogInfoMeshCoP("sent panid query conflict response"); diff --git a/src/core/net/dhcp6_client.cpp b/src/core/net/dhcp6_client.cpp index 8e3878b2f..edbe4a5b6 100644 --- a/src/core/net/dhcp6_client.cpp +++ b/src/core/net/dhcp6_client.cpp @@ -38,8 +38,8 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "mac/mac.hpp" #include "net/dhcp6.hpp" @@ -55,7 +55,7 @@ namespace Dhcp6 { Dhcp6Client::Dhcp6Client(Instance &aInstance) : InstanceLocator(aInstance) - , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mSocket(Get()) , mTrickleTimer(aInstance, &Dhcp6Client::HandleTrickleTimer, NULL, this) , mStartTime(0) , mIdentityAssociationCurrent(NULL) @@ -105,7 +105,7 @@ void Dhcp6Client::UpdateAddresses(void) if (!found) { - GetNetif().RemoveUnicastAddress(*static_cast(&ia.mNetifAddress)); + Get().RemoveUnicastAddress(*static_cast(&ia.mNetifAddress)); mIdentityAssociations[i].mStatus = kIaStatusInvalid; } } @@ -263,7 +263,6 @@ exit: otError Dhcp6Client::Solicit(uint16_t aRloc16) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Message * message; Ip6::MessageInfo messageInfo; @@ -278,14 +277,15 @@ otError Dhcp6Client::Solicit(uint16_t aRloc16) SuccessOrExit(error = AppendIaAddress(*message, aRloc16)); SuccessOrExit(error = AppendRapidCommit(*message)); - memcpy(messageInfo.GetPeerAddr().mFields.m8, netif.GetMle().GetMeshLocalPrefix().m8, sizeof(otMeshLocalPrefix)); + memcpy(messageInfo.GetPeerAddr().mFields.m8, Get().GetMeshLocalPrefix().m8, + sizeof(otMeshLocalPrefix)); 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(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.mPeerPort = kDhcpServerPort; - messageInfo.mInterfaceId = netif.GetInterfaceId(); + messageInfo.mInterfaceId = Get().GetInterfaceId(); SuccessOrExit(error = mSocket.SendTo(*message, messageInfo)); otLogInfoIp6("solicit"); @@ -582,7 +582,7 @@ otError Dhcp6Client::ProcessIaAddress(Message &aMessage, uint16_t aOffset) mIdentityAssociations[i].mNetifAddress.mPreferred = option.GetPreferredLifetime() != 0; mIdentityAssociations[i].mNetifAddress.mValid = option.GetValidLifetime() != 0; mIdentityAssociations[i].mStatus = kIaStatusSolicitReplied; - GetNetif().AddUnicastAddress(*static_cast(&ia.mNetifAddress)); + Get().AddUnicastAddress(*static_cast(&ia.mNetifAddress)); break; } } diff --git a/src/core/net/dhcp6_server.cpp b/src/core/net/dhcp6_server.cpp index 1afd2bc47..a36d902a5 100644 --- a/src/core/net/dhcp6_server.cpp +++ b/src/core/net/dhcp6_server.cpp @@ -38,6 +38,7 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "thread/mle.hpp" #include "thread/thread_netif.hpp" @@ -49,7 +50,7 @@ namespace Dhcp6 { Dhcp6Server::Dhcp6Server(Instance &aInstance) : InstanceLocator(aInstance) - , mSocket(GetNetif().GetIp6().GetUdp()) + , mSocket(Get()) , mPrefixAgentsCount(0) , mPrefixAgentsMask(0) { @@ -59,8 +60,7 @@ Dhcp6Server::Dhcp6Server(Instance &aInstance) otError Dhcp6Server::UpdateService(void) { otError error = OT_ERROR_NONE; - ThreadNetif & netif = GetNetif(); - uint16_t rloc16 = netif.GetMle().GetRloc16(); + uint16_t rloc16 = Get().GetRloc16(); otNetworkDataIterator iterator; otBorderRouterConfig config; Lowpan::Context lowpanContext; @@ -77,14 +77,14 @@ otError Dhcp6Server::UpdateService(void) iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (netif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) + while (Get().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) { if (!config.mDhcp) { continue; } - error = netif.GetNetworkDataLeader().GetContext(mPrefixAgents[i].GetPrefix(), lowpanContext); + error = Get().GetContext(mPrefixAgents[i].GetPrefix(), lowpanContext); if ((error == OT_ERROR_NONE) && (mPrefixAgents[i].GetContextId() == lowpanContext.mContextId)) { @@ -104,15 +104,15 @@ otError Dhcp6Server::UpdateService(void) // add dhcp agent aloc and prefix delegation iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (netif.GetNetworkDataLeader().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) + while (Get().GetNextOnMeshPrefix(&iterator, rloc16, &config) == OT_ERROR_NONE) { if (!config.mDhcp) { continue; } - error = netif.GetNetworkDataLeader().GetContext(static_cast(config.mPrefix.mPrefix), - lowpanContext); + error = Get().GetContext(static_cast(config.mPrefix.mPrefix), + lowpanContext); if (error == OT_ERROR_NONE) { @@ -166,8 +166,8 @@ otError Dhcp6Server::AddPrefixAgent(const otIp6Prefix &aIp6Prefix, const Lowpan: VerifyOrExit(newEntry != NULL, error = OT_ERROR_NO_BUFS); - newEntry->Set(aIp6Prefix, GetNetif().GetMle().GetMeshLocalPrefix(), aContext.mContextId); - GetNetif().AddUnicastAddress(newEntry->GetAloc()); + newEntry->Set(aIp6Prefix, Get().GetMeshLocalPrefix(), aContext.mContextId); + Get().AddUnicastAddress(newEntry->GetAloc()); mPrefixAgentsCount++; exit: diff --git a/src/core/net/dns_client.cpp b/src/core/net/dns_client.cpp index a48ee4c46..dc7144ae0 100644 --- a/src/core/net/dns_client.cpp +++ b/src/core/net/dns_client.cpp @@ -33,7 +33,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" -#include "common/owner-locator.hpp" +#include "common/locator-getters.hpp" #include "net/udp6.hpp" #include "thread/thread_netif.hpp" @@ -49,6 +49,13 @@ using ot::Encoding::BigEndian::HostSwap16; namespace ot { namespace Dns { +Client::Client(Ip6::Netif &aNetif) + : mSocket(aNetif.Get()) + , mMessageId(0) + , mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this) +{ +} + otError Client::Start(void) { otError error; diff --git a/src/core/net/dns_client.hpp b/src/core/net/dns_client.hpp index 55499297e..56efc941c 100644 --- a/src/core/net/dns_client.hpp +++ b/src/core/net/dns_client.hpp @@ -158,10 +158,7 @@ public: * @param[in] aNetif A reference to the network interface that DNS client should be assigned to. * */ - explicit Client(Ip6::Netif &aNetif) - : mSocket(aNetif.GetIp6().GetUdp()) - , mMessageId(0) - , mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this){}; + explicit Client(Ip6::Netif &aNetif); /** * This method starts the DNS client. diff --git a/src/core/net/icmp6.cpp b/src/core/net/icmp6.cpp index 67454099a..3edc95a53 100644 --- a/src/core/net/icmp6.cpp +++ b/src/core/net/icmp6.cpp @@ -40,6 +40,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" #include "net/ip6.hpp" @@ -59,7 +60,7 @@ Icmp::Icmp(Instance &aInstance) Message *Icmp::NewMessage(uint16_t aReserved) { - return GetIp6().NewMessage(sizeof(IcmpHeader) + aReserved); + return Get().NewMessage(sizeof(IcmpHeader) + aReserved); } otError Icmp::RegisterHandler(IcmpHandler &aHandler) @@ -96,7 +97,7 @@ otError Icmp::SendEchoRequest(Message &aMessage, const MessageInfo &aMessageInfo SuccessOrExit(error = aMessage.Prepend(&icmpHeader, sizeof(icmpHeader))); aMessage.SetOffset(0); - SuccessOrExit(error = GetIp6().SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6)); + SuccessOrExit(error = Get().SendDatagram(aMessage, messageInfoLocal, kProtoIcmp6)); otLogInfoIcmp("Sent echo request: (seq = %d)", icmpHeader.GetSequence()); @@ -116,7 +117,7 @@ otError Icmp::SendError(IcmpHeader::Type aType, messageInfoLocal = aMessageInfo; - VerifyOrExit((message = GetIp6().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(sizeof(icmp6Header) + sizeof(aHeader))); message->Write(sizeof(icmp6Header), sizeof(aHeader), &aHeader); @@ -126,7 +127,7 @@ otError Icmp::SendError(IcmpHeader::Type aType, icmp6Header.SetCode(aCode); message->Write(0, sizeof(icmp6Header), &icmp6Header); - SuccessOrExit(error = GetIp6().SendDatagram(*message, messageInfoLocal, kProtoIcmp6)); + SuccessOrExit(error = Get().SendDatagram(*message, messageInfoLocal, kProtoIcmp6)); otLogInfoIcmp("Sent ICMPv6 Error"); @@ -213,7 +214,7 @@ otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMe icmp6Header.Init(); icmp6Header.SetType(IcmpHeader::kTypeEchoReply); - if ((replyMessage = GetIp6().NewMessage(0)) == NULL) + if ((replyMessage = Get().NewMessage(0)) == NULL) { otLogDebgIcmp("Failed to allocate a new message"); ExitNow(); @@ -235,7 +236,7 @@ otError Icmp::HandleEchoRequest(Message &aRequestMessage, const MessageInfo &aMe replyMessageInfo.SetInterfaceId(aMessageInfo.mInterfaceId); - SuccessOrExit(error = GetIp6().SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6)); + SuccessOrExit(error = Get().SendDatagram(*replyMessage, replyMessageInfo, kProtoIcmp6)); replyMessage->Read(replyMessage->GetOffset(), sizeof(icmp6Header), &icmp6Header); otLogInfoIcmp("Sent Echo Reply (seq = %d)", icmp6Header.GetSequence()); diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index 912f0f62b..0e2c14e62 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -38,9 +38,9 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "net/icmp6.hpp" #include "net/ip6_address.hpp" #include "net/ip6_routes.hpp" @@ -69,8 +69,8 @@ Ip6::Ip6(Instance &aInstance) Message *Ip6::NewMessage(uint16_t aReserved, const otMessageSettings *aSettings) { - return GetInstance().GetMessagePool().New( - Message::kTypeIp6, sizeof(Header) + sizeof(HopByHopHeader) + sizeof(OptionMpl) + aReserved, aSettings); + return Get().New(Message::kTypeIp6, + sizeof(Header) + sizeof(HopByHopHeader) + sizeof(OptionMpl) + aReserved, aSettings); } Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength, const otMessageSettings *aSettings) @@ -84,7 +84,7 @@ Message *Ip6::NewMessage(const uint8_t *aData, uint16_t aDataLength, const otMes } SuccessOrExit(GetDatagramPriority(aData, aDataLength, *reinterpret_cast(&settings.mPriority))); - VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kTypeIp6, 0, &settings)) != NULL); + VerifyOrExit((message = Get().New(Message::kTypeIp6, 0, &settings)) != NULL); if (message->Append(aData, aDataLength) != OT_ERROR_NONE) { @@ -304,7 +304,7 @@ otError Ip6::InsertMplOption(Message &aMessage, Header &aHeader, MessageInfo &aM else { if (aHeader.GetDestination().IsMulticastLargerThanRealmLocal() && - GetInstance().GetThreadNetif().GetMle().HasSleepyChildrenSubscribed(aHeader.GetDestination())) + Get().HasSleepyChildrenSubscribed(aHeader.GetDestination())) { Message *messageCopy = NULL; @@ -500,7 +500,7 @@ otError Ip6::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto if (aMessageInfo.GetPeerAddr().IsMulticastLargerThanRealmLocal()) { - if (GetInstance().GetThreadNetif().GetMle().HasSleepyChildrenSubscribed(header.GetDestination())) + if (Get().HasSleepyChildrenSubscribed(header.GetDestination())) { Message *messageCopy = NULL; @@ -742,7 +742,7 @@ otError Ip6::ProcessReceiveCallback(const Message & aMessage, case kCoapUdpPort: // do not pass TMF messages - if (GetInstance().GetThreadNetif().IsTmfMessage(aMessageInfo)) + if (Get().IsTmfMessage(aMessageInfo)) { ExitNow(error = OT_ERROR_NO_ROUTE); } @@ -752,7 +752,7 @@ otError Ip6::ProcessReceiveCallback(const Message & aMessage, default: #if OPENTHREAD_FTD - if (udp.GetDestinationPort() == GetInstance().Get().GetJoinerUdpPort()) + if (udp.GetDestinationPort() == Get().GetJoinerUdpPort()) { ExitNow(error = OT_ERROR_NO_ROUTE); } @@ -865,7 +865,7 @@ otError Ip6::HandleDatagram(Message & aMessage, } if (header.GetDestination().IsMulticastLargerThanRealmLocal() && - GetInstance().GetThreadNetif().GetMle().HasSleepyChildrenSubscribed(header.GetDestination())) + Get().HasSleepyChildrenSubscribed(header.GetDestination())) { forward = true; } diff --git a/src/core/net/ip6.hpp b/src/core/net/ip6.hpp index 212c5582f..e78e52d70 100644 --- a/src/core/net/ip6.hpp +++ b/src/core/net/ip6.hpp @@ -100,6 +100,8 @@ using ot::Encoding::BigEndian::HostSwap32; */ class Ip6 : public InstanceLocator { + friend class ot::Instance; + public: enum { @@ -378,38 +380,6 @@ public: */ const PriorityQueue &GetSendQueue(void) const { return mSendQueue; } - /** - * This method returns a reference to the IPv6 route management instance. - * - * @returns A reference to the route management instance. - * - */ - Routes &GetRoutes(void) { return mRoutes; } - - /** - * This method returns a reference to the ICMP6 controller instance. - * - * @returns A reference to the ICMP6 instance. - * - */ - Icmp &GetIcmp(void) { return mIcmp; } - - /** - * This method returns a reference to the UDP controller instance. - * - * @returns A reference to the UDP instance. - * - */ - Udp &GetUdp(void) { return mUdp; } - - /** - * This method returns a reference to the MPL message processing controller instance. - * - * @returns A reference to the Mpl instance. - * - */ - Mpl &GetMpl(void) { return mMpl; } - /** * This static method converts an `IpProto` enumeration to a string. * diff --git a/src/core/net/ip6_mpl.cpp b/src/core/net/ip6_mpl.cpp index ec47f449c..bde8c0f4f 100644 --- a/src/core/net/ip6_mpl.cpp +++ b/src/core/net/ip6_mpl.cpp @@ -35,8 +35,8 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "net/ip6.hpp" @@ -244,8 +244,7 @@ void Mpl::AddBufferedMessage(Message &aMessage, uint16_t aSeedId, uint8_t aSeque #if OPENTHREAD_CONFIG_ENABLE_DYNAMIC_MPL_INTERVAL // adjust the first MPL forward interval dynamically according to the network scale - uint8_t interval = (kDataMessageInterval / Mle::kMaxRouters) * - GetInstance().GetThreadNetif().GetMle().GetRouterTable().GetNeighborCount(); + uint8_t interval = (kDataMessageInterval / Mle::kMaxRouters) * Get().GetNeighborCount(); #else uint8_t interval = kDataMessageInterval; #endif @@ -370,7 +369,7 @@ void Mpl::HandleRetransmissionTimer(void) messageCopy->SetSubType(Message::kSubTypeMplRetransmission); } - GetIp6().EnqueueDatagram(*messageCopy); + Get().EnqueueDatagram(*messageCopy); } messageMetadata.GenerateNextTransmissionTime(now, kDataMessageInterval); @@ -395,7 +394,7 @@ void Mpl::HandleRetransmissionTimer(void) // Remove the extra metadata from the MPL Data Message. messageMetadata.RemoveFrom(*message); - GetIp6().EnqueueDatagram(*message); + Get().EnqueueDatagram(*message); } else { diff --git a/src/core/net/ip6_routes.cpp b/src/core/net/ip6_routes.cpp index a8dc8b1cd..57410635e 100644 --- a/src/core/net/ip6_routes.cpp +++ b/src/core/net/ip6_routes.cpp @@ -35,6 +35,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/message.hpp" #include "net/ip6.hpp" #include "net/netif.hpp" @@ -114,7 +115,7 @@ int8_t Routes::Lookup(const Address &aSource, const Address &aDestination) rval = cur->mInterfaceId; } - for (Netif *netif = GetIp6().GetNetifList(); netif; netif = netif->GetNext()) + for (Netif *netif = Get().GetNetifList(); netif; netif = netif->GetNext()) { if (netif->RouteLookup(aSource, aDestination, &prefixMatch) == OT_ERROR_NONE && static_cast(prefixMatch) > maxPrefixMatch) diff --git a/src/core/net/netif.cpp b/src/core/net/netif.cpp index f4d406a5c..e6abd7387 100644 --- a/src/core/net/netif.cpp +++ b/src/core/net/netif.cpp @@ -36,8 +36,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "net/ip6.hpp" namespace ot { @@ -135,7 +135,7 @@ void Netif::SubscribeAllNodesMulticast(void) } } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); } void Netif::UnsubscribeAllNodesMulticast(void) @@ -153,7 +153,7 @@ void Netif::UnsubscribeAllNodesMulticast(void) } } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); } otError Netif::SubscribeAllRoutersMulticast(void) @@ -191,7 +191,7 @@ otError Netif::SubscribeAllRoutersMulticast(void) } } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); exit: return error; @@ -232,7 +232,7 @@ exit: } } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); } return error; @@ -258,7 +258,7 @@ otError Netif::SubscribeMulticast(NetifMulticastAddress &aAddress) mAddressCallback(&aAddress.mAddress, kMulticastPrefixLength, true, mAddressCallbackContext); } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); exit: return error; @@ -296,7 +296,7 @@ exit: mAddressCallback(&aAddress.mAddress, kMulticastPrefixLength, false, mAddressCallbackContext); } - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); } return error; @@ -357,7 +357,7 @@ otError Netif::SubscribeExternalMulticast(const Address &aAddress) entry->mAddress = aAddress; entry->mNext = mMulticastAddresses; mMulticastAddresses = entry; - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_SUBSRCRIBED); exit: return error; @@ -397,7 +397,7 @@ otError Netif::UnsubscribeExternalMulticast(const Address &aAddress) // To mark the address entry as unused/available, set the `mNext` pointer back to the entry itself. entry->mNext = entry; - GetNotifier().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); + Get().Signal(OT_CHANGED_IP6_MULTICAST_UNSUBSRCRIBED); exit: return error; @@ -443,7 +443,7 @@ otError Netif::AddUnicastAddress(NetifUnicastAddress &aAddress) mAddressCallback(&aAddress.mAddress, aAddress.mPrefixLength, true, mAddressCallbackContext); } - GetNotifier().Signal(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_ADDED : OT_CHANGED_IP6_ADDRESS_ADDED); + Get().Signal(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_ADDED : OT_CHANGED_IP6_ADDRESS_ADDED); exit: return error; @@ -481,7 +481,7 @@ exit: mAddressCallback(&aAddress.mAddress, aAddress.mPrefixLength, false, mAddressCallbackContext); } - GetNotifier().Signal(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_REMOVED : OT_CHANGED_IP6_ADDRESS_REMOVED); + Get().Signal(aAddress.mRloc ? OT_CHANGED_THREAD_RLOC_REMOVED : OT_CHANGED_IP6_ADDRESS_REMOVED); } return error; @@ -526,7 +526,7 @@ otError Netif::AddExternalUnicastAddress(const NetifUnicastAddress &aAddress) entry->mNext = mUnicastAddresses; mUnicastAddresses = entry; - GetNotifier().Signal(OT_CHANGED_IP6_ADDRESS_ADDED); + Get().Signal(OT_CHANGED_IP6_ADDRESS_ADDED); exit: return error; @@ -566,7 +566,7 @@ otError Netif::RemoveExternalUnicastAddress(const Address &aAddress) // To mark the address entry as unused/available, set the `mNext` pointer back to the entry itself. entry->mNext = entry; - GetNotifier().Signal(OT_CHANGED_IP6_ADDRESS_REMOVED); + Get().Signal(OT_CHANGED_IP6_ADDRESS_REMOVED); exit: return error; diff --git a/src/core/net/sntp_client.cpp b/src/core/net/sntp_client.cpp index 6c0f7a4c2..ccd58d851 100644 --- a/src/core/net/sntp_client.cpp +++ b/src/core/net/sntp_client.cpp @@ -33,8 +33,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "net/udp6.hpp" #include "thread/thread_netif.hpp" @@ -48,6 +48,13 @@ namespace ot { namespace Sntp { +Client::Client(Ip6::Netif &aNetif) + : mSocket(aNetif.Get()) + , mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this) + , mUnixEra(0) +{ +} + otError Client::Start(void) { otError error; diff --git a/src/core/net/sntp_client.hpp b/src/core/net/sntp_client.hpp index 617568e63..d4ecaf5f8 100644 --- a/src/core/net/sntp_client.hpp +++ b/src/core/net/sntp_client.hpp @@ -528,10 +528,7 @@ public: * @param[in] aNetif A reference to the network interface that SNTP client should be assigned to. * */ - explicit Client(Ip6::Netif &aNetif) - : mSocket(aNetif.GetIp6().GetUdp()) - , mRetransmissionTimer(aNetif.GetInstance(), &Client::HandleRetransmissionTimer, this) - , mUnixEra(0){}; + explicit Client(Ip6::Netif &aNetif); /** * This method starts the SNTP client. diff --git a/src/core/net/udp6.cpp b/src/core/net/udp6.cpp index 2be2e48aa..5727dc44c 100644 --- a/src/core/net/udp6.cpp +++ b/src/core/net/udp6.cpp @@ -40,6 +40,7 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "net/ip6.hpp" using ot::Encoding::BigEndian::HostSwap16; @@ -64,14 +65,9 @@ UdpSocket::UdpSocket(Udp &aUdp) mHandle = NULL; } -Udp &UdpSocket::GetUdp(void) -{ - return GetInstance().GetIp6().GetUdp(); -} - Message *UdpSocket::NewMessage(uint16_t aReserved, const otMessageSettings *aSettings) { - return GetUdp().NewMessage(aReserved, aSettings); + return Get().NewMessage(aReserved, aSettings); } otError UdpSocket::Open(otUdpReceive aHandler, void *aContext) @@ -87,7 +83,7 @@ otError UdpSocket::Open(otUdpReceive aHandler, void *aContext) SuccessOrExit(error = otPlatUdpSocket(this)); #endif - GetUdp().AddSocket(*this); + Get().AddSocket(*this); #if OPENTHREAD_ENABLE_PLATFORM_UDP exit: @@ -105,7 +101,7 @@ otError UdpSocket::Bind(const SockAddr &aSockAddr) { do { - mSockName.mPort = GetUdp().GetEphemeralPort(); + mSockName.mPort = Get().GetEphemeralPort(); #if OPENTHREAD_ENABLE_PLATFORM_UDP error = otPlatUdpBind(this); #endif @@ -144,7 +140,7 @@ otError UdpSocket::Close(void) SuccessOrExit(error = otPlatUdpClose(this)); #endif - GetUdp().RemoveSocket(*this); + Get().RemoveSocket(*this); memset(&mSockName, 0, sizeof(mSockName)); memset(&mPeerName, 0, sizeof(mPeerName)); @@ -198,7 +194,7 @@ otError UdpSocket::SendTo(Message &aMessage, const MessageInfo &aMessageInfo) else #endif { - SuccessOrExit(error = GetUdp().SendDatagram(aMessage, messageInfoLocal, kProtoUdp)); + SuccessOrExit(error = Get().SendDatagram(aMessage, messageInfoLocal, kProtoUdp)); } exit: @@ -319,7 +315,7 @@ uint16_t Udp::GetEphemeralPort(void) Message *Udp::NewMessage(uint16_t aReserved, const otMessageSettings *aSettings) { - return GetIp6().NewMessage(sizeof(UdpHeader) + aReserved, aSettings); + return Get().NewMessage(sizeof(UdpHeader) + aReserved, aSettings); } otError Udp::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto) @@ -347,7 +343,7 @@ otError Udp::SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto SuccessOrExit(error = aMessage.Prepend(&udpHeader, sizeof(udpHeader))); aMessage.SetOffset(0); - error = GetIp6().SendDatagram(aMessage, aMessageInfo, aIpProto); + error = Get().SendDatagram(aMessage, aMessageInfo, aIpProto); } exit: diff --git a/src/core/net/udp6.hpp b/src/core/net/udp6.hpp index 160535646..ff6f340a0 100644 --- a/src/core/net/udp6.hpp +++ b/src/core/net/udp6.hpp @@ -209,8 +209,6 @@ private: { mHandler(mContext, &aMessage, &aMessageInfo); } - - Udp &GetUdp(void); }; /** diff --git a/src/core/thread/address_resolver.cpp b/src/core/thread/address_resolver.cpp index 2955286fc..e76437e3d 100644 --- a/src/core/thread/address_resolver.cpp +++ b/src/core/thread/address_resolver.cpp @@ -44,8 +44,8 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "mac/mac_frame.hpp" #include "thread/mesh_forwarder.hpp" #include "thread/mle_router.hpp" @@ -66,11 +66,11 @@ AddressResolver::AddressResolver(Instance &aInstance) { Clear(); - GetNetif().GetCoap().AddResource(mAddressError); - GetNetif().GetCoap().AddResource(mAddressQuery); - GetNetif().GetCoap().AddResource(mAddressNotification); + Get().AddResource(mAddressError); + Get().AddResource(mAddressQuery); + Get().AddResource(mAddressNotification); - GetNetif().GetIp6().GetIcmp().RegisterHandler(mIcmpHandler); + Get().RegisterHandler(mIcmpHandler); } void AddressResolver::Clear(void) @@ -238,7 +238,7 @@ void AddressResolver::UpdateCacheEntry(const Ip6::Address &aEid, Mac::ShortAddre mCache[i].mFailures = 0; mCache[i].mState = Cache::kStateCached; - GetNetif().GetMeshForwarder().HandleResolved(aEid, OT_ERROR_NONE); + Get().HandleResolved(aEid, OT_ERROR_NONE); } otLogNoteArp("Cache entry updated (snoop): %s, 0x%04x", aEid.ToString().AsCString(), aRloc16); @@ -318,13 +318,12 @@ exit: otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message; ThreadTargetTlv targetTlv; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_ADDRESS_QUERY); @@ -336,11 +335,11 @@ otError AddressResolver::SendAddressQuery(const Ip6::Address &aEid) messageInfo.GetPeerAddr().mFields.m16[0] = HostSwap16(0xff03); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(0x0002); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoArp("Sending address query for %s", aEid.ToString().AsCString()); @@ -367,7 +366,6 @@ void AddressResolver::HandleAddressNotification(void *aContext, otMessage *aMess void AddressResolver::HandleAddressNotification(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; ThreadRloc16Tlv rloc16Tlv; @@ -440,12 +438,12 @@ void AddressResolver::HandleAddressNotification(Coap::Message &aMessage, const I otLogNoteArp("Cache entry updated (notification): %s, 0x%04x, lastTrans:%d", targetTlv.GetTarget().ToString().AsCString(), rloc16Tlv.GetRloc16(), lastTransactionTime); - if (netif.GetCoap().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) + if (Get().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) { otLogInfoArp("Sending address notification acknowledgment"); } - netif.GetMeshForwarder().HandleResolved(targetTlv.GetTarget(), OT_ERROR_NONE); + Get().HandleResolved(targetTlv.GetTarget(), OT_ERROR_NONE); break; } } @@ -458,12 +456,11 @@ otError AddressResolver::SendAddressError(const ThreadTargetTlv & aTarget, const ThreadMeshLocalEidTlv &aEid, const Ip6::Address * aDestination) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(aDestination == NULL ? OT_COAP_TYPE_NON_CONFIRMABLE : OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_ADDRESS_ERROR); @@ -482,11 +479,11 @@ otError AddressResolver::SendAddressError(const ThreadTargetTlv & aTarget, memcpy(&messageInfo.GetPeerAddr(), aDestination, sizeof(messageInfo.GetPeerAddr())); } - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoArp("Sending address error for target %s", aTarget.GetTarget().ToString().AsCString()); @@ -508,7 +505,6 @@ void AddressResolver::HandleAddressError(void *aContext, otMessage *aMessage, co void AddressResolver::HandleAddressError(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; @@ -522,7 +518,7 @@ void AddressResolver::HandleAddressError(Coap::Message &aMessage, const Ip6::Mes if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - if (netif.GetCoap().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) + if (Get().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) { otLogInfoArp("Sent address error notification acknowledgment"); } @@ -534,13 +530,14 @@ void AddressResolver::HandleAddressError(Coap::Message &aMessage, const Ip6::Mes SuccessOrExit(error = ThreadTlv::GetTlv(aMessage, ThreadTlv::kMeshLocalEid, sizeof(mlIidTlv), mlIidTlv)); VerifyOrExit(mlIidTlv.IsValid(), error = OT_ERROR_PARSE); - for (const Ip6::NetifUnicastAddress *address = netif.GetUnicastAddresses(); address; address = address->GetNext()) + for (const Ip6::NetifUnicastAddress *address = Get().GetUnicastAddresses(); address; + address = address->GetNext()) { if (address->GetAddress() == targetTlv.GetTarget() && - memcmp(netif.GetMle().GetMeshLocal64().GetIid(), mlIidTlv.GetIid(), 8)) + memcmp(Get().GetMeshLocal64().GetIid(), mlIidTlv.GetIid(), 8)) { // Target EID matches address and Mesh Local EID differs - netif.RemoveUnicastAddress(*address); + Get().RemoveUnicastAddress(*address); ExitNow(); } } @@ -590,7 +587,6 @@ void AddressResolver::HandleAddressQuery(void *aContext, otMessage *aMessage, co void AddressResolver::HandleAddressQuery(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); ThreadTargetTlv targetTlv; ThreadMeshLocalEidTlv mlIidTlv; ThreadLastTransactionTimeTlv lastTransactionTimeTlv; @@ -607,9 +603,9 @@ void AddressResolver::HandleAddressQuery(Coap::Message &aMessage, const Ip6::Mes otLogInfoArp("Received address query from 0x%04x for target %s", HostSwap16(aMessageInfo.GetPeerAddr().mFields.m16[7]), targetTlv.GetTarget().ToString().AsCString()); - if (netif.IsUnicastAddress(targetTlv.GetTarget())) + if (Get().IsUnicastAddress(targetTlv.GetTarget())) { - mlIidTlv.SetIid(netif.GetMle().GetMeshLocal64().GetIid()); + mlIidTlv.SetIid(Get().GetMeshLocal64().GetIid()); SendAddressQueryResponse(targetTlv, mlIidTlv, NULL, aMessageInfo.GetPeerAddr()); ExitNow(); } @@ -641,13 +637,12 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv & const ThreadLastTransactionTimeTlv *aLastTransactionTimeTlv, const Ip6::Address & aDestination) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message; ThreadRloc16Tlv rloc16Tlv; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->AppendUriPathOptions(OT_URI_PATH_ADDRESS_NOTIFY); @@ -657,7 +652,7 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv & SuccessOrExit(error = message->Append(&aMlEidTlv, sizeof(aMlEidTlv))); rloc16Tlv.Init(); - rloc16Tlv.SetRloc16(netif.GetMle().GetRloc16()); + rloc16Tlv.SetRloc16(Get().GetRloc16()); SuccessOrExit(error = message->Append(&rloc16Tlv, sizeof(rloc16Tlv))); if (aLastTransactionTimeTlv != NULL) @@ -666,10 +661,10 @@ void AddressResolver::SendAddressQueryResponse(const ThreadTargetTlv & } messageInfo.SetPeerAddr(aDestination); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoArp("Sending address notification for target %s", aTargetTlv.GetTarget().ToString().AsCString()); @@ -720,7 +715,7 @@ void AddressResolver::HandleTimer(void) otLogInfoArp("Timed out waiting for address notification for %s, retry: %d", mCache[i].mTarget.ToString().AsCString(), mCache[i].mRetryTimeout); - GetNetif().GetMeshForwarder().HandleResolved(mCache[i].mTarget, OT_ERROR_DROP); + Get().HandleResolved(mCache[i].mTarget, OT_ERROR_DROP); } } else if (mCache[i].mRetryTimeout > 0) diff --git a/src/core/thread/announce_begin_server.cpp b/src/core/thread/announce_begin_server.cpp index 7f3b095bf..d15a25c92 100644 --- a/src/core/thread/announce_begin_server.cpp +++ b/src/core/thread/announce_begin_server.cpp @@ -41,8 +41,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" #include "thread/thread_uri_paths.hpp" @@ -53,7 +53,7 @@ AnnounceBeginServer::AnnounceBeginServer(Instance &aInstance) : AnnounceSenderBase(aInstance, &AnnounceBeginServer::HandleTimer) , mAnnounceBegin(OT_URI_PATH_ANNOUNCE_BEGIN, &AnnounceBeginServer::HandleRequest, this) { - GetNetif().GetCoap().AddResource(mAnnounceBegin); + Get().AddResource(mAnnounceBegin); } otError AnnounceBeginServer::SendAnnounce(uint32_t aChannelMask) @@ -92,7 +92,7 @@ void AnnounceBeginServer::HandleRequest(Coap::Message &aMessage, const Ip6::Mess if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, responseInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); otLogInfoMeshCoP("sent announce begin response"); } diff --git a/src/core/thread/announce_sender.cpp b/src/core/thread/announce_sender.cpp index ead5ea371..7349569f6 100644 --- a/src/core/thread/announce_sender.cpp +++ b/src/core/thread/announce_sender.cpp @@ -39,8 +39,8 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" @@ -104,7 +104,7 @@ void AnnounceSenderBase::HandleTimer(void) assert(error == OT_ERROR_NONE); - GetNetif().GetMle().SendAnnounce(mChannel, false); + Get().SendAnnounce(mChannel, false); mTimer.Start(Random::AddJitter(mPeriod, mJitter)); @@ -127,7 +127,7 @@ void AnnounceSender::HandleTimer(Timer &aTimer) void AnnounceSender::CheckState(void) { - Mle::MleRouter & mle = GetInstance().Get(); + Mle::MleRouter & mle = Get(); uint32_t interval = kRouterTxInterval; uint32_t period; Mac::ChannelMask channelMask; @@ -154,7 +154,7 @@ void AnnounceSender::CheckState(void) ExitNow(); } - SuccessOrExit(GetNetif().GetActiveDataset().GetChannelMask(channelMask) == OT_ERROR_NONE, Stop()); + SuccessOrExit(Get().GetChannelMask(channelMask) == OT_ERROR_NONE, Stop()); period = interval / channelMask.GetNumberOfChannels(); diff --git a/src/core/thread/child_table.cpp b/src/core/thread/child_table.cpp index d514cf10f..49ee72b14 100644 --- a/src/core/thread/child_table.cpp +++ b/src/core/thread/child_table.cpp @@ -35,6 +35,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" namespace ot { @@ -60,11 +61,9 @@ ChildTable::Iterator::Iterator(Instance &aInstance, StateFilter aFilter, Child * void ChildTable::Iterator::Reset(void) { - ChildTable &childTable = GetInstance().Get(); - if (mStart == NULL) { - mStart = &childTable.mChildren[0]; + mStart = &Get().mChildren[0]; } mChild = mStart; @@ -77,7 +76,7 @@ void ChildTable::Iterator::Reset(void) void ChildTable::Iterator::Advance(void) { - ChildTable &childTable = GetInstance().Get(); + ChildTable &childTable = Get(); Child * listStart = &childTable.mChildren[0]; Child * listEnd = &childTable.mChildren[childTable.mMaxChildrenAllowed]; diff --git a/src/core/thread/data_poll_manager.cpp b/src/core/thread/data_poll_manager.cpp index 8eb9537e2..2b42f38e5 100644 --- a/src/core/thread/data_poll_manager.cpp +++ b/src/core/thread/data_poll_manager.cpp @@ -39,9 +39,9 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "net/ip6.hpp" #include "net/netif.hpp" #include "thread/mesh_forwarder.hpp" @@ -71,7 +71,7 @@ otError DataPollManager::StartPolling(void) otError error = OT_ERROR_NONE; VerifyOrExit(!mEnabled, error = OT_ERROR_ALREADY); - VerifyOrExit(!GetNetif().GetMle().IsRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(!Get().IsRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); mEnabled = true; ScheduleNextPoll(kRecalculatePollPeriod); @@ -94,28 +94,27 @@ void DataPollManager::StopPolling(void) otError DataPollManager::SendDataPoll(void) { - ThreadNetif &netif = GetNetif(); - otError error; - Message * message; - Neighbor * parent; + otError error; + Message * message; + Neighbor *parent; VerifyOrExit(mEnabled, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(!netif.GetMac().GetRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(!Get().GetRxOnWhenIdle(), error = OT_ERROR_INVALID_STATE); - parent = netif.GetMle().GetParentCandidate(); + parent = Get().GetParentCandidate(); VerifyOrExit((parent != NULL) && parent->IsStateValidOrRestoring(), error = OT_ERROR_INVALID_STATE); mTimer.Stop(); - for (message = netif.GetMeshForwarder().GetSendQueue().GetHead(); message; message = message->GetNext()) + for (message = Get().GetSendQueue().GetHead(); message; message = message->GetNext()) { VerifyOrExit(message->GetType() != Message::kTypeMacDataPoll, error = OT_ERROR_ALREADY); } - message = GetInstance().GetMessagePool().New(Message::kTypeMacDataPoll, 0); + message = Get().New(Message::kTypeMacDataPoll, 0); VerifyOrExit(message != NULL, error = OT_ERROR_NO_BUFS); - error = netif.GetMeshForwarder().SendMessage(*message); + error = Get().SendMessage(*message); if (error != OT_ERROR_NONE) { @@ -431,7 +430,7 @@ void DataPollManager::HandlePollTimer(Timer &aTimer) uint32_t DataPollManager::GetDefaultPollPeriod(void) const { - return TimerMilli::SecToMsec(GetNetif().GetMle().GetTimeout()) - + return TimerMilli::SecToMsec(Get().GetTimeout()) - static_cast(kRetxPollPeriod) * kMaxPollRetxAttempts; } diff --git a/src/core/thread/energy_scan_server.cpp b/src/core/thread/energy_scan_server.cpp index 576e439e2..f752212f0 100644 --- a/src/core/thread/energy_scan_server.cpp +++ b/src/core/thread/energy_scan_server.cpp @@ -41,8 +41,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -63,7 +63,7 @@ EnergyScanServer::EnergyScanServer(Instance &aInstance) , mNotifierCallback(aInstance, &EnergyScanServer::HandleStateChanged, this) , mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this) { - GetNetif().GetCoap().AddResource(mEnergyScan); + Get().AddResource(mEnergyScan); } void EnergyScanServer::HandleRequest(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -106,7 +106,7 @@ void EnergyScanServer::HandleRequest(Coap::Message &aMessage, const Ip6::Message if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, responseInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); otLogInfoMeshCoP("sent energy scan query response"); } @@ -127,7 +127,7 @@ void EnergyScanServer::HandleTimer(void) { // grab the lowest channel to scan uint32_t channelMask = mChannelMaskCurrent & ~(mChannelMaskCurrent - 1); - GetNetif().GetMac().EnergyScan(channelMask, mScanDuration, HandleScanResult); + Get().EnergyScan(channelMask, mScanDuration, HandleScanResult); } else { @@ -184,7 +184,7 @@ otError EnergyScanServer::SendReport(void) Ip6::MessageInfo messageInfo; Coap::Message * message; - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(GetNetif().GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -200,10 +200,10 @@ otError EnergyScanServer::SendReport(void) SuccessOrExit(error = message->Append(&energyList, sizeof(energyList))); SuccessOrExit(error = message->Append(mScanResults, mScanResultsLength)); - messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(mCommissioner); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = GetNetif().GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent scan results"); @@ -227,7 +227,7 @@ void EnergyScanServer::HandleStateChanged(Notifier::Callback &aCallback, otChang void EnergyScanServer::HandleStateChanged(otChangedFlags aFlags) { if ((aFlags & OT_CHANGED_THREAD_NETDATA) != 0 && !mActive && - GetNetif().GetNetworkDataLeader().GetCommissioningData() == NULL) + Get().GetCommissioningData() == NULL) { mActive = false; mTimer.Stop(); diff --git a/src/core/thread/key_manager.cpp b/src/core/thread/key_manager.cpp index 6ca11e4ae..76703d7da 100644 --- a/src/core/thread/key_manager.cpp +++ b/src/core/thread/key_manager.cpp @@ -35,7 +35,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" -#include "common/owner-locator.hpp" +#include "common/locator-getters.hpp" #include "common/timer.hpp" #include "crypto/hmac_sha256.hpp" #include "thread/mle_router.hpp" @@ -104,9 +104,9 @@ const uint8_t *KeyManager::GetPSKc(void) const void KeyManager::SetPSKc(const uint8_t *aPSKc) { - VerifyOrExit(memcmp(mPSKc, aPSKc, sizeof(mPSKc)) != 0, GetNotifier().SignalIfFirst(OT_CHANGED_PSKC)); + VerifyOrExit(memcmp(mPSKc, aPSKc, sizeof(mPSKc)) != 0, Get().SignalIfFirst(OT_CHANGED_PSKC)); memcpy(mPSKc, aPSKc, sizeof(mPSKc)); - GetNotifier().Signal(OT_CHANGED_PSKC); + Get().Signal(OT_CHANGED_PSKC); exit: return; @@ -120,19 +120,18 @@ const otMasterKey &KeyManager::GetMasterKey(void) const otError KeyManager::SetMasterKey(const otMasterKey &aKey) { - Mle::MleRouter &mle = GetNetif().GetMle(); - otError error = OT_ERROR_NONE; - Router * routers; + otError error = OT_ERROR_NONE; + Router *routers; VerifyOrExit(memcmp(&mMasterKey, &aKey, sizeof(mMasterKey)) != 0, - GetNotifier().SignalIfFirst(OT_CHANGED_MASTER_KEY)); + Get().SignalIfFirst(OT_CHANGED_MASTER_KEY)); mMasterKey = aKey; mKeySequence = 0; ComputeKey(mKeySequence, mKey); // reset parent frame counters - routers = mle.GetParent(); + routers = Get().GetParent(); routers->SetKeySequence(0); routers->SetLinkFrameCounter(0); routers->SetMleFrameCounter(0); @@ -153,7 +152,7 @@ otError KeyManager::SetMasterKey(const otMasterKey &aKey) iter.GetChild()->SetMleFrameCounter(0); } - GetNotifier().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER | OT_CHANGED_MASTER_KEY); + Get().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER | OT_CHANGED_MASTER_KEY); exit: return error; @@ -178,7 +177,7 @@ void KeyManager::ComputeKey(uint32_t aKeySequence, uint8_t *aKey) void KeyManager::SetCurrentKeySequence(uint32_t aKeySequence) { - VerifyOrExit(aKeySequence != mKeySequence, GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER)); + VerifyOrExit(aKeySequence != mKeySequence, Get().SignalIfFirst(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER)); // Check if the guard timer has expired if key rotation is requested. if ((aKeySequence == (mKeySequence + 1)) && (mKeySwitchGuardTime != 0) && mKeyRotationTimer.IsRunning() && @@ -199,7 +198,7 @@ void KeyManager::SetCurrentKeySequence(uint32_t aKeySequence) StartKeyRotationTimer(); } - GetNotifier().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); + Get().Signal(OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER); exit: return; @@ -223,7 +222,7 @@ void KeyManager::IncrementMacFrameCounter(void) if (mMacFrameCounter >= mStoredMacFrameCounter) { - GetNetif().GetMle().Store(); + Get().Store(); } } @@ -233,7 +232,7 @@ void KeyManager::IncrementMleFrameCounter(void) if (mMleFrameCounter >= mStoredMleFrameCounter) { - GetNetif().GetMle().Store(); + Get().Store(); } } @@ -257,7 +256,7 @@ exit: void KeyManager::SetSecurityPolicyFlags(uint8_t aSecurityPolicyFlags) { - Notifier ¬ifier = GetNotifier(); + Notifier ¬ifier = Get(); if (!notifier.HasSignaled(OT_CHANGED_SECURITY_POLICY) || (mSecurityPolicyFlags != aSecurityPolicyFlags)) { diff --git a/src/core/thread/lowpan.cpp b/src/core/thread/lowpan.cpp index 43716318c..655abbee8 100644 --- a/src/core/thread/lowpan.cpp +++ b/src/core/thread/lowpan.cpp @@ -37,6 +37,7 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "net/ip6.hpp" #include "net/udp6.hpp" #include "thread/network_data_leader.hpp" @@ -186,10 +187,9 @@ exit: otError Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, BufferWriter &aBuf) { - otError error = OT_ERROR_NONE; - BufferWriter buf = aBuf; - NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); - Context multicastContext; + otError error = OT_ERROR_NONE; + BufferWriter buf = aBuf; + Context multicastContext; aHcCtl |= kHcMulticast; @@ -220,7 +220,7 @@ otError Lowpan::CompressMulticast(const Ip6::Address &aIpAddr, uint16_t &aHcCtl, else { // Check if multicast address can be compressed using Context ID 0. - if (networkData.GetContext(0, multicastContext) == OT_ERROR_NONE && + if (Get().GetContext(0, multicastContext) == OT_ERROR_NONE && multicastContext.mPrefixLength == aIpAddr.mFields.m8[3] && memcmp(multicastContext.mPrefix, aIpAddr.mFields.m8 + 4, 8) == 0) { @@ -253,7 +253,7 @@ otError Lowpan::Compress(Message & aMessage, BufferWriter & aBuf) { otError error = OT_ERROR_NONE; - NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); + NetworkData::Leader &networkData = Get(); uint16_t startOffset = aMessage.GetOffset(); BufferWriter buf = aBuf; uint16_t hcCtl; @@ -664,7 +664,7 @@ int Lowpan::DecompressBaseHeader(Ip6::Header & aIp6Header, const uint8_t * aBuf, uint16_t aBufLength) { - NetworkData::Leader &networkData = GetNetif().GetNetworkDataLeader(); + NetworkData::Leader &networkData = Get(); otError error = OT_ERROR_PARSE; const uint8_t * cur = aBuf; uint16_t remaining = aBufLength; diff --git a/src/core/thread/mesh_forwarder.cpp b/src/core/thread/mesh_forwarder.cpp index 8e704a393..a439da9de 100644 --- a/src/core/thread/mesh_forwarder.cpp +++ b/src/core/thread/mesh_forwarder.cpp @@ -39,9 +39,9 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "net/ip6.hpp" #include "net/ip6_filter.hpp" @@ -102,15 +102,14 @@ void MeshForwarder::Start(void) { if (mEnabled == false) { - GetNetif().GetMac().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); mEnabled = true; } } void MeshForwarder::Stop(void) { - ThreadNetif &netif = GetNetif(); - Message * message; + Message *message; VerifyOrExit(mEnabled == true); @@ -140,7 +139,7 @@ void MeshForwarder::Stop(void) mEnabled = false; mSendMessage = NULL; - netif.GetMac().SetRxOnWhenIdle(false); + Get().SetRxOnWhenIdle(false); exit: return; @@ -192,7 +191,7 @@ void MeshForwarder::ScheduleTransmissionTask(void) mSendMessageMaxCsmaBackoffs = Mac::kMaxCsmaBackoffsDirect; mSendMessageMaxFrameRetries = Mac::kMaxFrameRetriesDirect; - GetNetif().GetMac().SendFrameRequest(); + Get().SendFrameRequest(); ExitNow(); } @@ -202,15 +201,14 @@ exit: otError MeshForwarder::PrepareDiscoverRequest(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(!mScanning); mScanChannel = Mac::ChannelMask::kChannelIteratorFirst; - mRestorePanId = netif.GetMac().GetPanId(); + mRestorePanId = Get().GetPanId(); - SuccessOrExit(error = netif.GetMac().AcquireRadioChannel(&mMacRadioAcquisitionId)); + SuccessOrExit(error = Get().AcquireRadioChannel(&mMacRadioAcquisitionId)); mScanning = true; @@ -301,18 +299,17 @@ exit: otError MeshForwarder::PrepareDataPoll(void) { - otError error = OT_ERROR_NONE; - ThreadNetif &netif = GetNetif(); - Neighbor * parent = netif.GetMle().GetParentCandidate(); - uint16_t shortAddress; + otError error = OT_ERROR_NONE; + Neighbor *parent = Get().GetParentCandidate(); + uint16_t shortAddress; VerifyOrExit((parent != NULL) && parent->IsStateValidOrRestoring(), error = OT_ERROR_DROP); - shortAddress = netif.GetMac().GetShortAddress(); + shortAddress = Get().GetShortAddress(); - if ((shortAddress == Mac::kShortAddrInvalid) || (parent != netif.GetMle().GetParent())) + if ((shortAddress == Mac::kShortAddrInvalid) || (parent != Get().GetParent())) { - mMacSource.SetExtended(netif.GetMac().GetExtAddress()); + mMacSource.SetExtended(Get().GetExtAddress()); mMacDest.SetExtended(parent->GetExtAddress()); } else @@ -327,9 +324,9 @@ exit: otError MeshForwarder::UpdateIp6Route(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Ip6::Header ip6Header; + Mle::MleRouter &mle = Get(); + otError error = OT_ERROR_NONE; + Ip6::Header ip6Header; mAddMeshHeader = false; @@ -341,7 +338,7 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) GetMacSourceAddress(ip6Header.GetSource(), mMacSource); // 2. Choose correct MAC Destination Address. - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_DISABLED || netif.GetMle().GetRole() == OT_DEVICE_ROLE_DETACHED) + if (mle.GetRole() == OT_DEVICE_ROLE_DISABLED || mle.GetRole() == OT_DEVICE_ROLE_DETACHED) { // Allow only for link-local unicasts and multicasts. if (ip6Header.GetDestination().IsLinkLocal() || ip6Header.GetDestination().IsLinkLocalMulticast()) @@ -360,9 +357,9 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) { // With the exception of MLE multicasts, a Thread End Device transmits multicasts, // as IEEE 802.15.4 unicasts to its parent. - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD && !aMessage.IsSubTypeMle()) + if (mle.GetRole() == OT_DEVICE_ROLE_CHILD && !aMessage.IsSubTypeMle()) { - mMacDest.SetShort(netif.GetMle().GetNextHop(Mac::kShortAddrBroadcast)); + mMacDest.SetShort(mle.GetNextHop(Mac::kShortAddrBroadcast)); } else { @@ -373,9 +370,9 @@ otError MeshForwarder::UpdateIp6Route(Message &aMessage) { GetMacDestinationAddress(ip6Header.GetDestination(), mMacDest); } - else if (netif.GetMle().IsMinimalEndDevice()) + else if (mle.IsMinimalEndDevice()) { - mMacDest.SetShort(netif.GetMle().GetNextHop(Mac::kShortAddrBroadcast)); + mMacDest.SetShort(mle.GetNextHop(Mac::kShortAddrBroadcast)); } else { @@ -392,36 +389,32 @@ exit: bool MeshForwarder::GetRxOnWhenIdle(void) { - return GetNetif().GetMac().GetRxOnWhenIdle(); + return Get().GetRxOnWhenIdle(); } void MeshForwarder::SetRxOnWhenIdle(bool aRxOnWhenIdle) { - ThreadNetif &netif = GetNetif(); - - netif.GetMac().SetRxOnWhenIdle(aRxOnWhenIdle); + Get().SetRxOnWhenIdle(aRxOnWhenIdle); if (aRxOnWhenIdle) { mDataPollManager.StopPolling(); - netif.GetSupervisionListener().Stop(); + Get().Stop(); } else { mDataPollManager.StartPolling(); - netif.GetSupervisionListener().Start(); + Get().Start(); } } void MeshForwarder::GetMacSourceAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr) { - ThreadNetif &netif = GetNetif(); - aIp6Addr.ToExtAddress(aMacAddr); - if (aMacAddr.GetExtended() != netif.GetMac().GetExtAddress()) + if (aMacAddr.GetExtended() != Get().GetExtAddress()) { - aMacAddr.SetShort(netif.GetMac().GetShortAddress()); + aMacAddr.SetShort(Get().GetShortAddress()); } } @@ -438,7 +431,7 @@ void MeshForwarder::GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Mac:: { aMacAddr.SetShort(HostSwap16(aIp6Addr.mFields.m16[7])); } - else if (GetNetif().GetMle().IsRoutingLocator(aIp6Addr)) + else if (Get().IsRoutingLocator(aIp6Addr)) { aMacAddr.SetShort(HostSwap16(aIp6Addr.mFields.m16[7])); } @@ -498,9 +491,8 @@ otError MeshForwarder::DecompressIp6Header(const uint8_t * aFrame, uint8_t & aHeaderLength, bool & aNextHeaderCompressed) { - Lowpan::Lowpan & lowpan = GetNetif().GetLowpan(); - otError error = OT_ERROR_NONE; - const uint8_t * start = aFrame; + otError error = OT_ERROR_NONE; + const uint8_t * start = aFrame; Lowpan::FragmentHeader fragmentHeader; int headerLength; @@ -515,8 +507,8 @@ otError MeshForwarder::DecompressIp6Header(const uint8_t * aFrame, } VerifyOrExit(aFrameLength >= 1 && Lowpan::Lowpan::IsLowpanHc(aFrame), error = OT_ERROR_NOT_FOUND); - headerLength = - lowpan.DecompressBaseHeader(aIp6Header, aNextHeaderCompressed, aMacSource, aMacDest, aFrame, aFrameLength); + headerLength = Get().DecompressBaseHeader(aIp6Header, aNextHeaderCompressed, aMacSource, aMacDest, + aFrame, aFrameLength); VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE); aHeaderLength = static_cast(aFrame - start) + static_cast(headerLength); @@ -527,8 +519,7 @@ exit: otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mEnabled, error = OT_ERROR_ABORT); @@ -548,7 +539,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) case Message::kTypeIp6: if (mSendMessage->GetSubType() == Message::kSubTypeMleDiscoverRequest) { - SuccessOrExit(error = netif.GetMac().SetRadioChannel(mMacRadioAcquisitionId, mScanChannel)); + SuccessOrExit(error = Get().SetRadioChannel(mMacRadioAcquisitionId, mScanChannel)); aFrame.SetChannel(mScanChannel); @@ -556,7 +547,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // Request messages MUST have the Destination PAN ID in the IEEE 802.15.4 MAC header set // to be the Broadcast PAN ID (0xFFFF) and the Source PAN ID set to a randomly generated // value. - if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && netif.GetMac().GetPanId() == Mac::kPanIdBroadcast) + if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && Get().GetPanId() == Mac::kPanIdBroadcast) { uint16_t panid; @@ -565,7 +556,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) panid = Random::GetUint16(); } while (panid == Mac::kPanIdBroadcast); - netif.GetMac().SetPanId(panid); + Get().SetPanId(panid); } } @@ -635,7 +626,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame) // The case where the current message requires fragmentation is // already checked and handled in `SendFragment()` method. - child = netif.GetMle().GetChildTable().FindChild(macDest, ChildTable::kInStateValidOrRestoring); + child = Get().FindChild(macDest, ChildTable::kInStateValidOrRestoring); if ((child != NULL) && !child->IsRxOnWhenIdle() && (child->GetIndirectMessageCount() > 1)) { @@ -651,8 +642,7 @@ exit: void MeshForwarder::SendPoll(Message &aMessage, Mac::Frame &aFrame) { - ThreadNetif &netif = GetNetif(); - uint16_t fcf; + uint16_t fcf; // initialize MAC header fcf = Mac::Frame::kFcfFrameMacCmd | Mac::Frame::kFcfPanidCompression | Mac::Frame::kFcfFrameVersion2006; @@ -669,7 +659,7 @@ void 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(netif.GetMac().GetPanId()); + aFrame.SetDstPanId(Get().GetPanId()); aFrame.SetSrcAddr(mMacSource); aFrame.SetDstAddr(mMacDest); aFrame.SetCommandId(Mac::Frame::kMacCmdDataRequest); @@ -679,7 +669,6 @@ void MeshForwarder::SendPoll(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; @@ -751,7 +740,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) secCtl |= Mac::Frame::kSecEncMic32; } - dstpan = netif.GetMac().GetPanId(); + dstpan = Get().GetPanId(); switch (aMessage.GetSubType()) { @@ -769,7 +758,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) break; } - if (dstpan == netif.GetMac().GetPanId()) + if (dstpan == Get().GetPanId()) { #if OPENTHREAD_CONFIG_HEADER_IE_SUPPORT // Handle a special case in IEEE 802.15.4-2015, when Pan ID Compression is 0, but Src Pan ID is not present: @@ -790,7 +779,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) aFrame.InitMacHeader(fcf, secCtl); aFrame.SetDstPanId(dstpan); - aFrame.SetSrcPanId(netif.GetMac().GetPanId()); + aFrame.SetSrcPanId(Get().GetPanId()); aFrame.SetDstAddr(mMacDest); aFrame.SetSrcAddr(mMacSource); @@ -825,10 +814,11 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) // initialize Mesh header if (mAddMeshHeader) { + Mle::MleRouter & mle = Get(); Lowpan::MeshHeader meshHeader; uint8_t hopsLeft; - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) + if (mle.GetRole() == OT_DEVICE_ROLE_CHILD) { // REED sets hopsLeft to max (16) + 1. It does not know the route cost. hopsLeft = Mle::kMaxRouteCost + 1; @@ -836,16 +826,16 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) else { // Calculate the number of predicted hops. - hopsLeft = netif.GetMle().GetRouteCost(mMeshDest); + hopsLeft = mle.GetRouteCost(mMeshDest); if (hopsLeft != Mle::kMaxRouteCost) { - hopsLeft += netif.GetMle().GetLinkCost(Mle::Mle::GetRouterId(netif.GetMle().GetNextHop(mMeshDest))); + hopsLeft += mle.GetLinkCost(Mle::Mle::GetRouterId(mle.GetNextHop(mMeshDest))); } else { // In case there is no route to the destination router (only link). - hopsLeft = netif.GetMle().GetLinkCost(Mle::Mle::GetRouterId(mMeshDest)); + hopsLeft = mle.GetLinkCost(Mle::Mle::GetRouterId(mMeshDest)); } } @@ -874,7 +864,7 @@ otError MeshForwarder::SendFragment(Message &aMessage, Mac::Frame &aFrame) Lowpan::FragmentHeader::kInitialHeaderSize); uint8_t hcLength; - error = netif.GetLowpan().Compress(aMessage, meshSource, meshDest, buffer); + error = Get().Compress(aMessage, meshSource, meshDest, buffer); assert(error == OT_ERROR_NONE); hcLength = static_cast(buffer.GetWritePointer() - payload); @@ -967,16 +957,15 @@ exit: void MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) { - ThreadNetif &netif = GetNetif(); uint16_t fcf; uint8_t secCtl; Mac::Address macSource; - macSource.SetShort(netif.GetMac().GetShortAddress()); + macSource.SetShort(Get().GetShortAddress()); if (macSource.IsShortAddrInvalid()) { - macSource.SetExtended(netif.GetMac().GetExtAddress()); + macSource.SetExtended(Get().GetExtAddress()); } fcf = Mac::Frame::kFcfFrameData | Mac::Frame::kFcfFrameVersion2006; @@ -996,8 +985,8 @@ void MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) aFrame.InitMacHeader(fcf, secCtl); - aFrame.SetDstPanId(netif.GetMac().GetPanId()); - aFrame.SetSrcPanId(netif.GetMac().GetPanId()); + aFrame.SetDstPanId(Get().GetPanId()); + aFrame.SetSrcPanId(Get().GetPanId()); aFrame.SetDstAddr(mMacDest); aFrame.SetSrcAddr(macSource); aFrame.SetPayloadLength(0); @@ -1006,9 +995,9 @@ void MeshForwarder::SendEmptyFrame(Mac::Frame &aFrame, bool aAckRequest) void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) { - ThreadNetif &netif = GetNetif(); - Mac::Address macDest; - Neighbor * neighbor; + Mle::MleRouter &mle = Get(); + Mac::Address macDest; + Neighbor * neighbor; mSendBusy = false; @@ -1016,7 +1005,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) aFrame.GetDstAddr(macDest); - if ((neighbor = netif.GetMle().GetNeighbor(macDest)) != NULL) + if ((neighbor = mle.GetNeighbor(macDest)) != NULL) { switch (aError) { @@ -1039,7 +1028,7 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) { if (neighbor->GetLinkFailures() >= Mle::kFailedRouterTransmissions) { - netif.GetMle().RemoveNeighbor(*neighbor); + mle.RemoveNeighbor(*neighbor); } } @@ -1132,12 +1121,12 @@ void MeshForwarder::HandleSentFrame(Mac::Frame &aFrame, otError aError) if (mSendMessage->GetType() == Message::kTypeMacDataPoll) { - neighbor = netif.GetMle().GetParentCandidate(); + neighbor = mle.GetParentCandidate(); if (neighbor->GetState() == Neighbor::kStateInvalid) { mDataPollManager.StopPolling(); - netif.GetMle().BecomeDetached(); + mle.BecomeDetached(); } else { @@ -1195,25 +1184,22 @@ exit: void MeshForwarder::HandleDiscoverComplete(void) { - ThreadNetif &netif = GetNetif(); - assert(mScanning); if (mMacRadioAcquisitionId) { - netif.GetMac().ReleaseRadioChannel(); + Get().ReleaseRadioChannel(); mMacRadioAcquisitionId = 0; } - netif.GetMac().SetPanId(mRestorePanId); + Get().SetPanId(mRestorePanId); mScanning = false; - netif.GetMle().HandleDiscoverComplete(); + Get().HandleDiscoverComplete(); mDiscoverTimer.Stop(); } void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) { - ThreadNetif & netif = GetNetif(); otThreadLinkInfo linkInfo; Mac::Address macDest; Mac::Address macSource; @@ -1242,7 +1228,7 @@ void MeshForwarder::HandleReceivedFrame(Mac::Frame &aFrame) payload = aFrame.GetPayload(); payloadLength = aFrame.GetPayloadLength(); - netif.GetSupervisionListener().UpdateOnReceive(macSource, linkInfo.mLinkSecurity); + Get().UpdateOnReceive(macSource, linkInfo.mLinkSecurity); switch (aFrame.GetType()) { @@ -1316,7 +1302,6 @@ void MeshForwarder::HandleFragment(uint8_t * aFrame, const Mac::Address & aMacDest, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Lowpan::FragmentHeader fragmentHeader; Message * message = NULL; @@ -1332,7 +1317,7 @@ void MeshForwarder::HandleFragment(uint8_t * aFrame, uint8_t priority; SuccessOrExit(error = GetFramePriority(aFrame, aFrameLength, aMacSource, aMacDest, priority)); - VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kTypeIp6, 0, priority)) != NULL, + VerifyOrExit((message = Get().New(Message::kTypeIp6, 0, priority)) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(aLinkInfo.mLinkSecurity); message->SetPanId(aLinkInfo.mPanId); @@ -1341,8 +1326,8 @@ void MeshForwarder::HandleFragment(uint8_t * aFrame, message->SetTimeSyncSeq(aLinkInfo.mTimeSyncSeq); message->SetNetworkTimeOffset(aLinkInfo.mNetworkTimeOffset); #endif - headerLength = netif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, - fragmentHeader.GetDatagramSize()); + headerLength = Get().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, + fragmentHeader.GetDatagramSize()); VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE); aFrame += headerLength; @@ -1360,7 +1345,7 @@ void MeshForwarder::HandleFragment(uint8_t * aFrame, message->MoveOffset(aFrameLength); // Security Check - VerifyOrExit(netif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); + VerifyOrExit(Get().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 @@ -1512,19 +1497,17 @@ void MeshForwarder::HandleLowpanHC(uint8_t * aFrame, const Mac::Address & aMacDest, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Message * message = NULL; - int headerLength; - uint8_t priority; + otError error = OT_ERROR_NONE; + Message *message = NULL; + int headerLength; + uint8_t priority; #if OPENTHREAD_FTD UpdateRoutes(aFrame, aFrameLength, aMacSource, aMacDest); #endif SuccessOrExit(error = GetFramePriority(aFrame, aFrameLength, aMacSource, aMacDest, priority)); - VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kTypeIp6, 0, priority)) != NULL, - error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().New(Message::kTypeIp6, 0, priority)) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(aLinkInfo.mLinkSecurity); message->SetPanId(aLinkInfo.mPanId); message->AddRss(aLinkInfo.mRss); @@ -1533,7 +1516,7 @@ void MeshForwarder::HandleLowpanHC(uint8_t * aFrame, message->SetNetworkTimeOffset(aLinkInfo.mNetworkTimeOffset); #endif - headerLength = netif.GetLowpan().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, 0); + headerLength = Get().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, 0); VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE); aFrame += headerLength; @@ -1543,7 +1526,7 @@ void MeshForwarder::HandleLowpanHC(uint8_t * aFrame, message->Write(message->GetOffset(), aFrameLength, aFrame); // Security Check - VerifyOrExit(netif.GetIp6Filter().Accept(*message), error = OT_ERROR_DROP); + VerifyOrExit(Get().Accept(*message), error = OT_ERROR_DROP); exit: @@ -1566,7 +1549,7 @@ otError MeshForwarder::HandleDatagram(Message & aMessage, const otThreadLinkInfo &aLinkInfo, const Mac::Address & aMacSource) { - ThreadNetif &netif = GetNetif(); + ThreadNetif &netif = Get(); LogMessage(kMessageReceive, aMessage, &aMacSource, OT_ERROR_NONE); @@ -1575,7 +1558,7 @@ otError MeshForwarder::HandleDatagram(Message & aMessage, mIpCounters.mRxSuccess++; } - return netif.GetIp6().HandleDatagram(aMessage, &netif, netif.GetInterfaceId(), &aLinkInfo, false); + return Get().HandleDatagram(aMessage, &netif, netif.GetInterfaceId(), &aLinkInfo, false); } otError MeshForwarder::GetFramePriority(const uint8_t * aFrame, @@ -1600,7 +1583,7 @@ otError MeshForwarder::GetFramePriority(const uint8_t * aFrame, if (nextHeaderCompressed) { - VerifyOrExit(GetNetif().GetLowpan().DecompressUdpHeader(udpHeader, aFrame, aFrameLength) >= 0); + VerifyOrExit(Get().DecompressUdpHeader(udpHeader, aFrame, aFrameLength) >= 0); } else { diff --git a/src/core/thread/mesh_forwarder.hpp b/src/core/thread/mesh_forwarder.hpp index 96a667ef0..b4ef6706d 100644 --- a/src/core/thread/mesh_forwarder.hpp +++ b/src/core/thread/mesh_forwarder.hpp @@ -168,6 +168,7 @@ private: class MeshForwarder : public InstanceLocator { friend class Mac::Mac; + friend class Instance; public: /** @@ -294,14 +295,6 @@ public: */ const MessageQueue &GetReassemblyQueue(void) const { return mReassemblyList; } - /** - * This method returns a reference to the data poll manager. - * - * @returns A reference to the data poll manager. - * - */ - DataPollManager &GetDataPollManager(void) { return mDataPollManager; } - /** * This method returns a reference to the IP level counters. * @@ -318,14 +311,6 @@ public: * */ const MessageQueue &GetResolvingQueue(void) const { return mResolvingQueue; } - - /** - * This method returns a reference to the source match controller. - * - * @returns A reference to the source match controller. - * - */ - SourceMatchController &GetSourceMatchController(void) { return mSourceMatchController; } #endif private: diff --git a/src/core/thread/mesh_forwarder_ftd.cpp b/src/core/thread/mesh_forwarder_ftd.cpp index a9a4936f6..5ae12d323 100644 --- a/src/core/thread/mesh_forwarder_ftd.cpp +++ b/src/core/thread/mesh_forwarder_ftd.cpp @@ -37,8 +37,8 @@ #include "mesh_forwarder.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "net/ip6.hpp" #include "net/tcp.hpp" @@ -48,10 +48,10 @@ namespace ot { otError MeshForwarder::SendMessage(Message &aMessage) { - ThreadNetif &netif = GetNetif(); - ChildTable & childTable = netif.GetMle().GetChildTable(); - otError error = OT_ERROR_NONE; - Neighbor * neighbor; + Mle::MleRouter &mle = Get(); + ChildTable & childTable = Get(); + otError error = OT_ERROR_NONE; + Neighbor * neighbor; switch (aMessage.GetType()) { @@ -75,8 +75,8 @@ otError MeshForwarder::SendMessage(Message &aMessage) if (aMessage.GetSubType() != Message::kSubTypeMplRetransmission) { - if (ip6Header.GetDestination() == netif.GetMle().GetLinkLocalAllThreadNodesAddress() || - ip6Header.GetDestination() == netif.GetMle().GetRealmLocalAllThreadNodesAddress()) + if (ip6Header.GetDestination() == mle.GetLinkLocalAllThreadNodesAddress() || + ip6Header.GetDestination() == mle.GetRealmLocalAllThreadNodesAddress()) { // destined for all sleepy children for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateValidOrRestoring); !iter.IsDone(); @@ -99,7 +99,7 @@ otError MeshForwarder::SendMessage(Message &aMessage) { Child &child = *iter.GetChild(); - if (netif.GetMle().IsSleepyChildSubscribed(ip6Header.GetDestination(), child)) + if (mle.IsSleepyChildSubscribed(ip6Header.GetDestination(), child)) { aMessage.SetChildMask(childTable.GetChildIndex(child)); mSourceMatchController.IncrementMessageCount(child); @@ -108,8 +108,8 @@ otError MeshForwarder::SendMessage(Message &aMessage) } } } - else if ((neighbor = netif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL && - !neighbor->IsRxOnWhenIdle() && !aMessage.GetDirectTransmission()) + else if ((neighbor = mle.GetNeighbor(ip6Header.GetDestination())) != NULL && !neighbor->IsRxOnWhenIdle() && + !aMessage.GetDirectTransmission()) { // destined for a sleepy child Child &child = *static_cast(neighbor); @@ -127,7 +127,7 @@ otError MeshForwarder::SendMessage(Message &aMessage) case Message::kTypeSupervision: { - Child *child = netif.GetChildSupervisor().GetDestination(aMessage); + Child *child = Get().GetDestination(aMessage); VerifyOrExit(child != NULL, error = OT_ERROR_DROP); VerifyOrExit(!child->IsRxOnWhenIdle(), error = OT_ERROR_DROP); @@ -200,7 +200,7 @@ void MeshForwarder::ClearChildIndirectMessages(Child &aChild) { nextMessage = message->GetNext(); - message->ClearChildMask(GetNetif().GetMle().GetChildTable().GetChildIndex(aChild)); + message->ClearChildMask(Get().GetChildIndex(aChild)); if (!message->IsChildPending() && !message->GetDirectTransmission()) { @@ -273,7 +273,7 @@ exit: otError MeshForwarder::RemoveMessageFromSleepyChild(Message &aMessage, Child &aChild) { otError error = OT_ERROR_NONE; - uint8_t childIndex = GetNetif().GetMle().GetChildTable().GetChildIndex(aChild); + uint8_t childIndex = Get().GetChildIndex(aChild); VerifyOrExit(aMessage.GetChildMask(childIndex) == true, error = OT_ERROR_NOT_FOUND); @@ -291,8 +291,8 @@ exit: void MeshForwarder::RemoveMessages(Child &aChild, uint8_t aSubType) { - ThreadNetif &netif = GetNetif(); - Message * nextMessage; + Mle::MleRouter &mle = Get(); + Message * nextMessage; for (Message *message = mSendQueue.GetHead(); message; message = nextMessage) { @@ -313,7 +313,7 @@ void MeshForwarder::RemoveMessages(Child &aChild, uint8_t aSubType) IgnoreReturnValue(message->Read(0, sizeof(ip6header), &ip6header)); - if (&aChild == static_cast(netif.GetMle().GetNeighbor(ip6header.GetDestination()))) + if (&aChild == static_cast(mle.GetNeighbor(ip6header.GetDestination()))) { message->ClearDirectTransmission(); } @@ -327,7 +327,7 @@ void MeshForwarder::RemoveMessages(Child &aChild, uint8_t aSubType) IgnoreReturnValue(meshHeader.Init(*message)); - if (&aChild == static_cast(netif.GetMle().GetNeighbor(meshHeader.GetDestination()))) + if (&aChild == static_cast(mle.GetNeighbor(meshHeader.GetDestination()))) { message->ClearDirectTransmission(); } @@ -387,8 +387,7 @@ void MeshForwarder::RemoveDataResponseMessages(void) otError MeshForwarder::GetIndirectTransmission(void) { - otError error = OT_ERROR_NOT_FOUND; - ThreadNetif &netif = GetNetif(); + otError error = OT_ERROR_NOT_FOUND; UpdateIndirectMessages(); @@ -421,11 +420,11 @@ otError MeshForwarder::GetIndirectTransmission(void) if (child.IsIndirectSourceMatchShort()) { - mMacSource.SetShort(netif.GetMac().GetShortAddress()); + mMacSource.SetShort(Get().GetShortAddress()); } else { - mMacSource.SetExtended(netif.GetMac().GetExtAddress()); + mMacSource.SetExtended(Get().GetExtAddress()); } child.GetMacAddress(mMacDest); @@ -435,7 +434,7 @@ otError MeshForwarder::GetIndirectTransmission(void) mIndirectStartingChild = &child; - netif.GetMac().SendFrameRequest(); + Get().SendFrameRequest(); ExitNow(error = OT_ERROR_NONE); } @@ -447,7 +446,7 @@ Message *MeshForwarder::GetIndirectTransmission(Child &aChild) { Message *message = NULL; Message *next; - uint8_t childIndex = GetNetif().GetMle().GetChildTable().GetChildIndex(aChild); + uint8_t childIndex = Get().GetChildIndex(aChild); for (message = mSendQueue.GetHead(); message; message = next) { @@ -532,8 +531,7 @@ void MeshForwarder::PrepareIndirectTransmission(Message &aMessage, const Child & void MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) { - ThreadNetif &netif = GetNetif(); - uint16_t fcf; + uint16_t fcf; // initialize MAC header fcf = Mac::Frame::kFcfFrameData | Mac::Frame::kFcfPanidCompression | Mac::Frame::kFcfFrameVersion2006 | @@ -541,7 +539,7 @@ void MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) Mac::Frame::kFcfSecurityEnabled; aFrame.InitMacHeader(fcf, Mac::Frame::kKeyIdMode1 | Mac::Frame::kSecEncMic32); - aFrame.SetDstPanId(netif.GetMac().GetPanId()); + aFrame.SetDstPanId(Get().GetPanId()); aFrame.SetDstAddr(mMacDest.GetShort()); aFrame.SetSrcAddr(mMacSource.GetShort()); @@ -555,16 +553,15 @@ void MeshForwarder::SendMesh(Message &aMessage, Mac::Frame &aFrame) void MeshForwarder::HandleDataRequest(const Mac::Address &aMacSource, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif &netif = GetNetif(); - Child * child; - uint16_t indirectMsgCount; + Child * child; + uint16_t indirectMsgCount; // Security Check: only process secure Data Poll frames. VerifyOrExit(aLinkInfo.mLinkSecurity); - VerifyOrExit(netif.GetMle().GetRole() != OT_DEVICE_ROLE_DETACHED); + VerifyOrExit(Get().GetRole() != OT_DEVICE_ROLE_DETACHED); - child = netif.GetMle().GetChildTable().FindChild(aMacSource, ChildTable::kInStateValidOrRestoring); + child = Get().FindChild(aMacSource, ChildTable::kInStateValidOrRestoring); VerifyOrExit(child != NULL); child->SetLastHeard(TimerMilli::GetNow()); @@ -586,10 +583,9 @@ exit: void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aError, const Mac::Address &aMacDest) { - ThreadNetif &netif = GetNetif(); - Child * child; + Child *child; - child = netif.GetMle().GetChildTable().FindChild(aMacDest, ChildTable::kInStateValidOrRestoring); + child = Get().FindChild(aMacDest, ChildTable::kInStateValidOrRestoring); VerifyOrExit(child != NULL); child->SetDataRequestPending(false); @@ -714,7 +710,7 @@ void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aEr #endif } - childIndex = netif.GetMle().GetChildTable().GetChildIndex(*child); + childIndex = Get().GetChildIndex(*child); if (mSendMessage->GetChildMask(childIndex)) { @@ -742,7 +738,7 @@ void MeshForwarder::HandleSentFrameToChild(const Mac::Frame &aFrame, otError aEr if (aError == OT_ERROR_NONE) { - netif.GetChildSupervisor().UpdateOnSend(*child); + Get().UpdateOnSend(*child); } exit: @@ -751,7 +747,6 @@ exit: otError MeshForwarder::UpdateMeshRoute(Message &aMessage) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Lowpan::MeshHeader meshHeader; Neighbor * neighbor; @@ -759,15 +754,15 @@ otError MeshForwarder::UpdateMeshRoute(Message &aMessage) IgnoreReturnValue(meshHeader.Init(aMessage)); - nextHop = netif.GetMle().GetNextHop(meshHeader.GetDestination()); + nextHop = Get().GetNextHop(meshHeader.GetDestination()); if (nextHop != Mac::kShortAddrInvalid) { - neighbor = netif.GetMle().GetNeighbor(nextHop); + neighbor = Get().GetNeighbor(nextHop); } else { - neighbor = netif.GetMle().GetNeighbor(meshHeader.GetDestination()); + neighbor = Get().GetNeighbor(meshHeader.GetDestination()); } if (neighbor == NULL) @@ -776,7 +771,7 @@ otError MeshForwarder::UpdateMeshRoute(Message &aMessage) } mMacDest.SetShort(neighbor->GetRloc16()); - mMacSource.SetShort(netif.GetMac().GetShortAddress()); + mMacSource.SetShort(Get().GetShortAddress()); mAddMeshHeader = true; mMeshDest = meshHeader.GetDestination(); @@ -788,27 +783,27 @@ exit: otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) { - otError error = OT_ERROR_NONE; - ThreadNetif &netif = GetNetif(); - Neighbor * neighbor; + Mle::MleRouter &mle = Get(); + otError error = OT_ERROR_NONE; + Neighbor * neighbor; - if (netif.GetMle().IsRoutingLocator(ip6Header.GetDestination())) + if (mle.IsRoutingLocator(ip6Header.GetDestination())) { uint16_t rloc16 = HostSwap16(ip6Header.GetDestination().mFields.m16[7]); - VerifyOrExit(netif.GetMle().IsRouterIdValid(netif.GetMle().GetRouterId(rloc16)), error = OT_ERROR_DROP); + VerifyOrExit(mle.IsRouterIdValid(mle.GetRouterId(rloc16)), error = OT_ERROR_DROP); mMeshDest = rloc16; } - else if (netif.GetMle().IsAnycastLocator(ip6Header.GetDestination())) + else if (mle.IsAnycastLocator(ip6Header.GetDestination())) { uint16_t aloc16 = HostSwap16(ip6Header.GetDestination().mFields.m16[7]); if (aloc16 == Mle::kAloc16Leader) { - mMeshDest = Mle::Mle::GetRloc16(netif.GetMle().GetLeaderId()); + mMeshDest = Mle::Mle::GetRloc16(mle.GetLeaderId()); } else if ((aloc16 >= Mle::kAloc16CommissionerStart) && (aloc16 <= Mle::kAloc16CommissionerEnd)) { - SuccessOrExit(error = MeshCoP::GetBorderAgentRloc(netif, mMeshDest)); + SuccessOrExit(error = MeshCoP::GetBorderAgentRloc(Get(), mMeshDest)); } #if OPENTHREAD_ENABLE_DHCP6_SERVER || OPENTHREAD_ENABLE_DHCP6_CLIENT @@ -816,15 +811,14 @@ otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) { uint16_t agentRloc16; uint8_t routerId; - VerifyOrExit((netif.GetNetworkDataLeader().GetRlocByContextId( + VerifyOrExit((Get().GetRlocByContextId( static_cast(aloc16 & Mle::kAloc16DhcpAgentMask), agentRloc16) == OT_ERROR_NONE), error = OT_ERROR_DROP); routerId = Mle::Mle::GetRouterId(agentRloc16); // if agent is active router or the child of the device - if ((Mle::Mle::IsActiveRouter(agentRloc16)) || - (Mle::Mle::GetRloc16(routerId) == netif.GetMle().GetRloc16())) + if ((Mle::Mle::IsActiveRouter(agentRloc16)) || (Mle::Mle::GetRloc16(routerId) == mle.GetRloc16())) { mMeshDest = agentRloc16; } @@ -849,25 +843,25 @@ otError MeshForwarder::UpdateIp6RouteFtd(Ip6::Header &ip6Header) ExitNow(error = OT_ERROR_DROP); } } - else if ((neighbor = netif.GetMle().GetNeighbor(ip6Header.GetDestination())) != NULL) + else if ((neighbor = mle.GetNeighbor(ip6Header.GetDestination())) != NULL) { mMeshDest = neighbor->GetRloc16(); } - else if (netif.GetNetworkDataLeader().IsOnMesh(ip6Header.GetDestination())) + else if (Get().IsOnMesh(ip6Header.GetDestination())) { - SuccessOrExit(error = netif.GetAddressResolver().Resolve(ip6Header.GetDestination(), mMeshDest)); + SuccessOrExit(error = Get().Resolve(ip6Header.GetDestination(), mMeshDest)); } else { - netif.GetNetworkDataLeader().RouteLookup(ip6Header.GetSource(), ip6Header.GetDestination(), NULL, &mMeshDest); + Get().RouteLookup(ip6Header.GetSource(), ip6Header.GetDestination(), NULL, &mMeshDest); } VerifyOrExit(mMeshDest != Mac::kShortAddrInvalid, error = OT_ERROR_DROP); - mMeshSource = netif.GetMac().GetShortAddress(); + mMeshSource = Get().GetShortAddress(); - SuccessOrExit(error = netif.GetMle().CheckReachability(mMeshSource, mMeshDest, ip6Header)); - mMacDest.SetShort(netif.GetMle().GetNextHop(mMeshDest)); + SuccessOrExit(error = mle.CheckReachability(mMeshSource, mMeshDest, ip6Header)); + mMacDest.SetShort(mle.GetNextHop(mMeshDest)); if (mMacDest.GetShort() != mMeshDest) { @@ -898,12 +892,11 @@ otError MeshForwarder::CheckReachability(uint8_t * aFrame, const Mac::Address &aMeshSource, const Mac::Address &aMeshDest) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Ip6::Header ip6Header; + otError error = OT_ERROR_NONE; + Ip6::Header ip6Header; SuccessOrExit(error = GetIp6Header(aFrame, aFrameLength, aMeshSource, aMeshDest, ip6Header)); - error = netif.GetMle().CheckReachability(aMeshSource.GetShort(), aMeshDest.GetShort(), ip6Header); + error = Get().CheckReachability(aMeshSource.GetShort(), aMeshDest.GetShort(), ip6Header); exit: // the message may not contain an IPv6 header @@ -924,7 +917,6 @@ void MeshForwarder::HandleMesh(uint8_t * aFrame, const Mac::Address & aMacSource, const otThreadLinkInfo &aLinkInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Message * message = NULL; Mac::Address meshDest; @@ -942,7 +934,8 @@ void MeshForwarder::HandleMesh(uint8_t * aFrame, UpdateRoutes(aFrame, aFrameLength, meshSource, meshDest); - if (meshDest.GetShort() == netif.GetMac().GetShortAddress() || netif.GetMle().IsMinimalChild(meshDest.GetShort())) + if (meshDest.GetShort() == Get().GetShortAddress() || + Get().IsMinimalChild(meshDest.GetShort())) { aFrame += meshHeader.GetHeaderLength(); aFrameLength -= meshHeader.GetHeaderLength(); @@ -964,7 +957,7 @@ void MeshForwarder::HandleMesh(uint8_t * aFrame, { uint8_t priority = kDefaultMsgPriority; - netif.GetMle().ResolveRoutingLoops(aMacSource.GetShort(), meshDest.GetShort()); + Get().ResolveRoutingLoops(aMacSource.GetShort(), meshDest.GetShort()); SuccessOrExit(error = CheckReachability(aFrame, aFrameLength, meshSource, meshDest)); @@ -972,7 +965,7 @@ void MeshForwarder::HandleMesh(uint8_t * aFrame, meshHeader.AppendTo(aFrame); GetForwardFramePriority(aFrame, aFrameLength, meshDest, meshSource, priority); - VerifyOrExit((message = GetInstance().GetMessagePool().New(Message::kType6lowpan, priority)) != NULL, + VerifyOrExit((message = Get().New(Message::kType6lowpan, priority)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(aFrameLength)); message->Write(0, aFrameLength, aFrame); @@ -1004,21 +997,20 @@ void MeshForwarder::UpdateRoutes(uint8_t * aFrame, const Mac::Address &aMeshSource, const Mac::Address &aMeshDest) { - ThreadNetif &netif = GetNetif(); - Ip6::Header ip6Header; - Neighbor * neighbor; + Ip6::Header ip6Header; + Neighbor * neighbor; VerifyOrExit(!aMeshDest.IsBroadcast() && aMeshSource.IsShort()); SuccessOrExit(GetIp6Header(aFrame, aFrameLength, aMeshSource, aMeshDest, ip6Header)); - netif.GetAddressResolver().UpdateCacheEntry(ip6Header.GetSource(), aMeshSource.GetShort()); + Get().UpdateCacheEntry(ip6Header.GetSource(), aMeshSource.GetShort()); - neighbor = netif.GetMle().GetNeighbor(ip6Header.GetSource()); + neighbor = Get().GetNeighbor(ip6Header.GetSource()); VerifyOrExit(neighbor != NULL && !neighbor->IsFullThreadDevice()); - if (Mle::Mle::GetRouterId(aMeshSource.GetShort()) != Mle::Mle::GetRouterId(GetNetif().GetMac().GetShortAddress())) + if (Mle::Mle::GetRouterId(aMeshSource.GetShort()) != Mle::Mle::GetRouterId(Get().GetShortAddress())) { - netif.GetMle().RemoveNeighbor(*neighbor); + Get().RemoveNeighbor(*neighbor); } exit: @@ -1178,9 +1170,8 @@ exit: otError MeshForwarder::GetDestinationRlocByServiceAloc(uint16_t aServiceAloc, uint16_t &aMeshDest) { otError error = OT_ERROR_NONE; - ThreadNetif & netif = GetNetif(); uint8_t serviceId = Mle::Mle::GetServiceIdFromAloc(aServiceAloc); - NetworkData::ServiceTlv *serviceTlv = netif.GetNetworkDataLeader().FindServiceById(serviceId); + NetworkData::ServiceTlv *serviceTlv = Get().FindServiceById(serviceId); if (serviceTlv != NULL) { @@ -1197,7 +1188,7 @@ otError MeshForwarder::GetDestinationRlocByServiceAloc(uint16_t aServiceAloc, ui { case NetworkData::NetworkDataTlv::kTypeServer: server = static_cast(cur); - curCost = netif.GetMle().GetCost(server->GetServer16()); + curCost = Get().GetCost(server->GetServer16()); if ((bestDest == Mac::kShortAddrInvalid) || (curCost < bestCost)) { @@ -1301,12 +1292,11 @@ otError MeshForwarder::DecompressIp6UdpTcpHeader(const Message & aMessage, uint16_t & aSourcePort, uint16_t & aDestPort) { - otError error = OT_ERROR_PARSE; - Lowpan::Lowpan &lowpan = GetNetif().GetLowpan(); - int headerLength; - bool nextHeaderCompressed; - uint8_t frameBuffer[sizeof(Ip6::Header)]; - uint16_t frameLength; + otError error = OT_ERROR_PARSE; + int headerLength; + bool nextHeaderCompressed; + uint8_t frameBuffer[sizeof(Ip6::Header)]; + uint16_t frameLength; union { Ip6::UdpHeader udp; @@ -1321,8 +1311,8 @@ otError MeshForwarder::DecompressIp6UdpTcpHeader(const Message & aMessage, frameLength = aMessage.Read(aOffset, sizeof(frameBuffer), frameBuffer); - headerLength = - lowpan.DecompressBaseHeader(aIp6Header, nextHeaderCompressed, aMeshSource, aMeshDest, frameBuffer, frameLength); + headerLength = Get().DecompressBaseHeader(aIp6Header, nextHeaderCompressed, aMeshSource, aMeshDest, + frameBuffer, frameLength); VerifyOrExit(headerLength >= 0); aOffset += headerLength; @@ -1335,7 +1325,7 @@ otError MeshForwarder::DecompressIp6UdpTcpHeader(const Message & aMessage, if (nextHeaderCompressed) { frameLength = aMessage.Read(aOffset, sizeof(Ip6::UdpHeader), frameBuffer); - headerLength = lowpan.DecompressUdpHeader(header.udp, frameBuffer, frameLength); + headerLength = Get().DecompressUdpHeader(header.udp, frameBuffer, frameLength); VerifyOrExit(headerLength >= 0); } else diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index 6e192daed..64d5eaa96 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -42,8 +42,8 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "crypto/aes_ccm.hpp" @@ -88,7 +88,7 @@ Mle::Mle(Instance &aInstance) , mParentLinkMargin(0) , mParentIsSingleton(false) , mReceivedResponseFromParent(false) - , mSocket(aInstance.GetThreadNetif().GetIp6().GetUdp()) + , mSocket(aInstance.Get()) , mTimeout(kMleEndDeviceTimeout) , mDiscoverHandler(NULL) , mDiscoverContext(NULL) @@ -129,7 +129,7 @@ Mle::Mle(Instance &aInstance) // link-local 64 mLinkLocal64.GetAddress().mFields.m16[0] = HostSwap16(0xfe80); - mLinkLocal64.GetAddress().SetIid(GetNetif().GetMac().GetExtAddress()); + mLinkLocal64.GetAddress().SetIid(Get().GetExtAddress()); mLinkLocal64.mPrefixLength = 64; mLinkLocal64.mPreferred = true; mLinkLocal64.mValid = true; @@ -160,7 +160,7 @@ Mle::Mle(Instance &aInstance) // initialize Mesh Local Prefix meshLocalPrefix.m8[0] = 0xfd; - memcpy(&meshLocalPrefix.m8[1], GetNetif().GetMac().GetExtendedPanId().m8, 5); + memcpy(&meshLocalPrefix.m8[1], Get().GetExtendedPanId().m8, 5); meshLocalPrefix.m8[6] = 0x00; meshLocalPrefix.m8[7] = 0x00; @@ -186,7 +186,7 @@ Mle::Mle(Instance &aInstance) mMeshLocal16.mRloc = true; // Store RLOC address reference in MPL module. - GetNetif().GetIp6().GetMpl().SetMatchingAddress(mMeshLocal16.GetAddress()); + Get().SetMatchingAddress(mMeshLocal16.GetAddress()); // link-local all thread nodes mLinkLocalAllThreadNodes.GetAddress().mFields.m16[0] = HostSwap16(0xff32); @@ -228,7 +228,7 @@ otError Mle::Disable(void) Stop(false); SuccessOrExit(error = mSocket.Close()); - SuccessOrExit(error = GetNetif().RemoveUnicastAddress(mLinkLocal64)); + SuccessOrExit(error = Get().RemoveUnicastAddress(mLinkLocal64)); exit: return error; @@ -236,12 +236,11 @@ exit: otError Mle::Start(bool aAnnounceAttach) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; // cannot bring up the interface if IEEE 802.15.4 promiscuous mode is enabled VerifyOrExit(otPlatRadioGetPromiscuous(&GetInstance()) == false, error = OT_ERROR_INVALID_STATE); - VerifyOrExit(netif.IsUp(), error = OT_ERROR_INVALID_STATE); + VerifyOrExit(Get().IsUp(), error = OT_ERROR_INVALID_STATE); SetStateDetached(); @@ -250,7 +249,7 @@ otError Mle::Start(bool aAnnounceAttach) mAttachCounter = 0; - netif.GetKeyManager().Start(); + Get().Start(); if (!aAnnounceAttach) { @@ -263,7 +262,7 @@ otError Mle::Start(bool aAnnounceAttach) } else if (IsActiveRouter(GetRloc16())) { - if (netif.GetMle().BecomeRouter(ThreadStatusTlv::kTooFewRouters) != OT_ERROR_NONE) + if (Get().BecomeRouter(ThreadStatusTlv::kTooFewRouters) != OT_ERROR_NONE) { BecomeChild(kAttachAny); } @@ -280,22 +279,20 @@ exit: void Mle::Stop(bool aClearNetworkDatasets) { - ThreadNetif &netif = GetNetif(); - if (aClearNetworkDatasets) { - netif.GetActiveDataset().HandleDetach(); - netif.GetPendingDataset().HandleDetach(); + Get().HandleDetach(); + Get().HandleDetach(); } VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED); - netif.GetKeyManager().Stop(); + Get().Stop(); SetStateDetached(); - GetNetif().UnsubscribeMulticast(mRealmLocalAllThreadNodes); - GetNetif().UnsubscribeMulticast(mLinkLocalAllThreadNodes); - netif.RemoveUnicastAddress(mMeshLocal16); - netif.RemoveUnicastAddress(mMeshLocal64); + Get().UnsubscribeMulticast(mRealmLocalAllThreadNodes); + Get().UnsubscribeMulticast(mLinkLocalAllThreadNodes); + Get().RemoveUnicastAddress(mMeshLocal16); + Get().RemoveUnicastAddress(mMeshLocal64); SetRole(OT_DEVICE_ROLE_DISABLED); @@ -305,12 +302,12 @@ exit: void Mle::SetRole(otDeviceRole aRole) { - VerifyOrExit(aRole != mRole, GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_ROLE)); + VerifyOrExit(aRole != mRole, Get().SignalIfFirst(OT_CHANGED_THREAD_ROLE)); otLogNoteMle("Role %s -> %s", RoleToString(mRole), RoleToString(aRole)); mRole = aRole; - GetNotifier().Signal(OT_CHANGED_THREAD_ROLE); + Get().Signal(OT_CHANGED_THREAD_ROLE); switch (mRole) { @@ -334,11 +331,11 @@ void Mle::SetRole(otDeviceRole aRole) #if OPENTHREAD_ENABLE_BORDER_AGENT if (IsAttached()) { - SuccessOrExit(GetInstance().Get().Start()); + SuccessOrExit(Get().Start()); } else { - SuccessOrExit(GetInstance().Get().Stop()); + SuccessOrExit(Get().Stop()); } #endif @@ -358,22 +355,18 @@ exit: otError Mle::Restore(void) { - ThreadNetif & netif = GetNetif(); - KeyManager & keyManager = netif.GetKeyManager(); - Mac::Mac & mac = netif.GetMac(); - Settings & settings = GetInstance().GetSettings(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; Settings::ParentInfo parentInfo; - netif.GetActiveDataset().Restore(); - netif.GetPendingDataset().Restore(); + Get().Restore(); + Get().Restore(); - SuccessOrExit(error = settings.ReadNetworkInfo(networkInfo)); + SuccessOrExit(error = Get().ReadNetworkInfo(networkInfo)); - keyManager.SetCurrentKeySequence(networkInfo.mKeySequence); - keyManager.SetMleFrameCounter(networkInfo.mMleFrameCounter); - keyManager.SetMacFrameCounter(networkInfo.mMacFrameCounter); + Get().SetCurrentKeySequence(networkInfo.mKeySequence); + Get().SetMleFrameCounter(networkInfo.mMleFrameCounter); + Get().SetMacFrameCounter(networkInfo.mMacFrameCounter); switch (networkInfo.mRole) { @@ -387,8 +380,8 @@ otError Mle::Restore(void) } mDeviceMode = networkInfo.mDeviceMode; - mac.SetShortAddress(networkInfo.mRloc16); - mac.SetExtAddress(networkInfo.mExtAddress); + Get().SetShortAddress(networkInfo.mRloc16); + Get().SetExtAddress(networkInfo.mExtAddress); memcpy(&mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], networkInfo.mMlIid, OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); @@ -400,7 +393,7 @@ otError Mle::Restore(void) if (!IsActiveRouter(networkInfo.mRloc16)) { - error = settings.ReadParentInfo(parentInfo); + error = Get().ReadParentInfo(parentInfo); if (error != OT_ERROR_NONE) { @@ -428,11 +421,9 @@ otError Mle::Restore(void) } else { - MleRouter &mle = netif.GetMle(); - - mle.SetRouterId(GetRouterId(GetRloc16())); - mle.SetPreviousPartitionId(networkInfo.mPreviousPartitionId); - mle.RestoreChildren(); + Get().SetRouterId(GetRouterId(GetRloc16())); + Get().SetPreviousPartitionId(networkInfo.mPreviousPartitionId); + Get().RestoreChildren(); } exit: @@ -441,10 +432,7 @@ exit: otError Mle::Store(void) { - ThreadNetif & netif = GetNetif(); - KeyManager & keyManager = netif.GetKeyManager(); - Settings & settings = GetInstance().GetSettings(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Settings::NetworkInfo networkInfo; memset(&networkInfo, 0, sizeof(networkInfo)); @@ -457,7 +445,7 @@ otError Mle::Store(void) networkInfo.mRole = mRole; networkInfo.mRloc16 = GetRloc16(); networkInfo.mPreviousPartitionId = mLeaderData.GetPartitionId(); - networkInfo.mExtAddress = netif.GetMac().GetExtAddress(); + networkInfo.mExtAddress = Get().GetExtAddress(); memcpy(networkInfo.mMlIid, &mMeshLocal64.GetAddress().mFields.m8[OT_IP6_PREFIX_SIZE], OT_IP6_IID_SIZE); if (mRole == OT_DEVICE_ROLE_CHILD) @@ -467,24 +455,24 @@ otError Mle::Store(void) memset(&parentInfo, 0, sizeof(parentInfo)); parentInfo.mExtAddress = mParent.GetExtAddress(); - SuccessOrExit(error = settings.SaveParentInfo(parentInfo)); + SuccessOrExit(error = Get().SaveParentInfo(parentInfo)); } } else { // when not attached, read out any existing values so that we do not change them - IgnoreReturnValue(settings.ReadNetworkInfo(networkInfo)); + IgnoreReturnValue(Get().ReadNetworkInfo(networkInfo)); } // update MAC and MLE Frame Counters even when we are not attached MLE messages are sent before a device attached - networkInfo.mKeySequence = keyManager.GetCurrentKeySequence(); - networkInfo.mMleFrameCounter = keyManager.GetMleFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; - networkInfo.mMacFrameCounter = keyManager.GetMacFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; + networkInfo.mKeySequence = Get().GetCurrentKeySequence(); + networkInfo.mMleFrameCounter = Get().GetMleFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; + networkInfo.mMacFrameCounter = Get().GetMacFrameCounter() + OPENTHREAD_CONFIG_STORE_FRAME_COUNTER_AHEAD; - SuccessOrExit(error = settings.SaveNetworkInfo(networkInfo)); + SuccessOrExit(error = Get().SaveNetworkInfo(networkInfo)); - keyManager.SetStoredMleFrameCounter(networkInfo.mMleFrameCounter); - keyManager.SetStoredMacFrameCounter(networkInfo.mMacFrameCounter); + Get().SetStoredMleFrameCounter(networkInfo.mMleFrameCounter); + Get().SetStoredMacFrameCounter(networkInfo.mMacFrameCounter); otLogDebgMle("Store Network Information"); @@ -512,7 +500,7 @@ otError Mle::Discover(const Mac::ChannelMask &aScanChannels, mDiscoverHandler = aCallback; mDiscoverContext = aContext; - GetNetif().GetMeshForwarder().SetDiscoverParameters(aScanChannels); + Get().SetDiscoverParameters(aScanChannels); VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetSubType(Message::kSubTypeMleDiscoverRequest); @@ -562,8 +550,7 @@ void Mle::HandleDiscoverComplete(void) otError Mle::BecomeDetached(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); @@ -576,7 +563,7 @@ otError Mle::BecomeDetached(void) // not in reattach stage after reset if (mReattachState == kReattachStop) { - netif.GetPendingDataset().HandleDetach(); + Get().HandleDetach(); } #if OPENTHREAD_CONFIG_ENABLE_PERIODIC_PARENT_SEARCH @@ -594,15 +581,14 @@ exit: otError Mle::BecomeChild(AttachMode aMode) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mAttachState == kAttachStateIdle, error = OT_ERROR_BUSY); if (mReattachState == kReattachStart) { - if (netif.GetActiveDataset().Restore() == OT_ERROR_NONE) + if (Get().Restore() == OT_ERROR_NONE) { mReattachState = kReattachActive; } @@ -620,7 +606,7 @@ otError Mle::BecomeChild(AttachMode aMode) { if (IsFullThreadDevice()) { - netif.GetMle().StopAdvertiseTimer(); + Get().StopAdvertiseTimer(); } } else @@ -643,7 +629,7 @@ otError Mle::BecomeChild(AttachMode aMode) if (!IsRxOnWhenIdle()) { - netif.GetMac().SetRxOnWhenIdle(false); + Get().SetRxOnWhenIdle(false); } } @@ -702,11 +688,9 @@ bool Mle::IsAttached(void) const void Mle::SetStateDetached(void) { - ThreadNetif &netif = GetNetif(); - if (mRole == OT_DEVICE_ROLE_LEADER) { - netif.RemoveUnicastAddress(mLeaderAloc); + Get().RemoveUnicastAddress(mLeaderAloc); } SetRole(OT_DEVICE_ROLE_DETACHED); @@ -717,20 +701,18 @@ void Mle::SetStateDetached(void) mChildUpdateAttempts = 0; mDataRequestState = kDataRequestNone; mDataRequestAttempts = 0; - netif.GetMeshForwarder().SetRxOnWhenIdle(true); - netif.GetMac().SetBeaconEnabled(false); - netif.GetMle().HandleDetachStart(); - netif.GetIp6().SetForwardingEnabled(false); - netif.GetIp6().GetMpl().SetTimerExpirations(0); + Get().SetRxOnWhenIdle(true); + Get().SetBeaconEnabled(false); + Get().HandleDetachStart(); + Get().SetForwardingEnabled(false); + Get().SetTimerExpirations(0); } void Mle::SetStateChild(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - if (mRole == OT_DEVICE_ROLE_LEADER) { - netif.RemoveUnicastAddress(mLeaderAloc); + Get().RemoveUnicastAddress(mLeaderAloc); } SetRloc16(aRloc16); @@ -741,19 +723,19 @@ void Mle::SetStateChild(uint16_t aRloc16) mReattachState = kReattachStop; mChildUpdateAttempts = 0; mDataRequestAttempts = 0; - netif.GetMac().SetBeaconEnabled(false); + Get().SetBeaconEnabled(false); ScheduleMessageTransmissionTimer(); if (IsFullThreadDevice()) { - netif.GetMle().HandleChildStart(mParentRequestMode); + Get().HandleChildStart(mParentRequestMode); } #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - netif.GetNetworkDataLocal().ClearResubmitDelayTimer(); + Get().ClearResubmitDelayTimer(); #endif - netif.GetIp6().SetForwardingEnabled(false); - netif.GetIp6().GetMpl().SetTimerExpirations(kMplChildDataMessageTimerExpirations); + Get().SetForwardingEnabled(false); + Get().SetTimerExpirations(kMplChildDataMessageTimerExpirations); // send announce after attached if needed InformPreviousChannel(); @@ -774,10 +756,10 @@ void Mle::InformPreviousChannel(void) VerifyOrExit(mRole == OT_DEVICE_ROLE_CHILD || mRole == OT_DEVICE_ROLE_ROUTER); if (!IsFullThreadDevice() || mRole == OT_DEVICE_ROLE_ROUTER || - GetNetif().GetMle().GetRouterSelectionJitterTimeout() == 0) + Get().GetRouterSelectionJitterTimeout() == 0) { mAlternatePanId = Mac::kPanIdBroadcast; - GetNetif().GetAnnounceBeginServer().SendAnnounce(1 << mAlternateChannel); + Get().SendAnnounce(1 << mAlternateChannel); } exit: @@ -795,7 +777,7 @@ void Mle::SetTimeout(uint32_t aTimeout) mTimeout = aTimeout; - GetNetif().GetMeshForwarder().GetDataPollManager().RecalculatePollPeriod(); + Get().RecalculatePollPeriod(); if (mRole == OT_DEVICE_ROLE_CHILD) { @@ -855,33 +837,29 @@ exit: void Mle::UpdateLinkLocalAddress(void) { - ThreadNetif &netif = GetNetif(); + Get().RemoveUnicastAddress(mLinkLocal64); + mLinkLocal64.GetAddress().SetIid(Get().GetExtAddress()); + Get().AddUnicastAddress(mLinkLocal64); - netif.RemoveUnicastAddress(mLinkLocal64); - mLinkLocal64.GetAddress().SetIid(netif.GetMac().GetExtAddress()); - netif.AddUnicastAddress(mLinkLocal64); - - GetNotifier().Signal(OT_CHANGED_THREAD_LL_ADDR); + Get().Signal(OT_CHANGED_THREAD_LL_ADDR); } void Mle::SetMeshLocalPrefix(const otMeshLocalPrefix &aMeshLocalPrefix) { - ThreadNetif &netif = GetNetif(); - if (memcmp(mMeshLocal64.GetAddress().mFields.m8, aMeshLocalPrefix.m8, sizeof(aMeshLocalPrefix)) == 0) { - GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_ML_ADDR); + Get().SignalIfFirst(OT_CHANGED_THREAD_ML_ADDR); ExitNow(); } - if (netif.IsUp()) + if (Get().IsUp()) { - netif.RemoveUnicastAddress(mLeaderAloc); + Get().RemoveUnicastAddress(mLeaderAloc); // We must remove the old addresses before adding the new ones. - netif.RemoveUnicastAddress(mMeshLocal64); - netif.RemoveUnicastAddress(mMeshLocal16); - netif.UnsubscribeMulticast(mLinkLocalAllThreadNodes); - netif.UnsubscribeMulticast(mRealmLocalAllThreadNodes); + Get().RemoveUnicastAddress(mMeshLocal64); + Get().RemoveUnicastAddress(mMeshLocal16); + Get().UnsubscribeMulticast(mLinkLocalAllThreadNodes); + Get().UnsubscribeMulticast(mRealmLocalAllThreadNodes); } memcpy(mMeshLocal64.GetAddress().mFields.m8, aMeshLocalPrefix.m8, sizeof(aMeshLocalPrefix)); @@ -889,7 +867,7 @@ void Mle::SetMeshLocalPrefix(const otMeshLocalPrefix &aMeshLocalPrefix) memcpy(mLeaderAloc.GetAddress().mFields.m8, aMeshLocalPrefix.m8, sizeof(aMeshLocalPrefix)); // Just keep mesh local prefix if network interface is down - VerifyOrExit(netif.IsUp()); + VerifyOrExit(Get().IsUp()); ApplyMeshLocalPrefix(); @@ -899,17 +877,15 @@ exit: void Mle::ApplyMeshLocalPrefix(void) { - ThreadNetif &netif = GetNetif(); - #if OPENTHREAD_ENABLE_SERVICE for (uint8_t i = 0; i < OT_ARRAY_LENGTH(mServiceAlocs); i++) { if (HostSwap16(mServiceAlocs[i].GetAddress().mFields.m16[7]) != Mac::kShortAddrInvalid) { - netif.RemoveUnicastAddress(mServiceAlocs[i]); + Get().RemoveUnicastAddress(mServiceAlocs[i]); memcpy(mServiceAlocs[i].GetAddress().mFields.m8, mMeshLocal64.GetAddress().mFields.m8, 8); - netif.AddUnicastAddress(mServiceAlocs[i]); + Get().AddUnicastAddress(mServiceAlocs[i]); } } @@ -924,59 +900,57 @@ void Mle::ApplyMeshLocalPrefix(void) VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED); // Add the addresses back into the table. - netif.AddUnicastAddress(mMeshLocal64); - netif.SubscribeMulticast(mLinkLocalAllThreadNodes); - netif.SubscribeMulticast(mRealmLocalAllThreadNodes); + Get().AddUnicastAddress(mMeshLocal64); + Get().SubscribeMulticast(mLinkLocalAllThreadNodes); + Get().SubscribeMulticast(mRealmLocalAllThreadNodes); if (IsAttached()) { - netif.AddUnicastAddress(mMeshLocal16); + Get().AddUnicastAddress(mMeshLocal16); } // update Leader ALOC if (mRole == OT_DEVICE_ROLE_LEADER) { - netif.AddUnicastAddress(mLeaderAloc); + Get().AddUnicastAddress(mLeaderAloc); } exit: // Changing the prefix also causes the mesh local address to be different. - GetNotifier().Signal(OT_CHANGED_THREAD_ML_ADDR); + Get().Signal(OT_CHANGED_THREAD_ML_ADDR); } uint16_t Mle::GetRloc16(void) const { - return GetNetif().GetMac().GetShortAddress(); + return Get().GetShortAddress(); } void Mle::SetRloc16(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - - netif.RemoveUnicastAddress(mMeshLocal16); + Get().RemoveUnicastAddress(mMeshLocal16); if (aRloc16 != Mac::kShortAddrInvalid) { // mesh-local 16 mMeshLocal16.GetAddress().mFields.m16[7] = HostSwap16(aRloc16); - netif.AddUnicastAddress(mMeshLocal16); + Get().AddUnicastAddress(mMeshLocal16); } - netif.GetMac().SetShortAddress(aRloc16); - netif.GetIp6().GetMpl().SetSeedId(aRloc16); + Get().SetShortAddress(aRloc16); + Get().SetSeedId(aRloc16); } void Mle::SetLeaderData(uint32_t aPartitionId, uint8_t aWeighting, uint8_t aLeaderRouterId) { if (mLeaderData.GetPartitionId() != aPartitionId) { - GetNetif().GetMle().HandlePartitionChange(); - GetNotifier().Signal(OT_CHANGED_THREAD_PARTITION_ID); + Get().HandlePartitionChange(); + Get().Signal(OT_CHANGED_THREAD_PARTITION_ID); mCounters.mPartitionIdChanges++; } else { - GetNotifier().SignalIfFirst(OT_CHANGED_THREAD_PARTITION_ID); + Get().SignalIfFirst(OT_CHANGED_THREAD_PARTITION_ID); } mLeaderData.SetPartitionId(aPartitionId); @@ -1039,7 +1013,7 @@ otError Mle::AddLeaderAloc(void) SuccessOrExit(error = GetLeaderAloc(mLeaderAloc.GetAddress())); - error = GetNetif().AddUnicastAddress(mLeaderAloc); + error = Get().AddUnicastAddress(mLeaderAloc); exit: return error; @@ -1047,10 +1021,9 @@ exit: const LeaderDataTlv &Mle::GetLeaderDataTlv(void) { - NetworkData::Leader &leaderData = GetNetif().GetNetworkDataLeader(); + mLeaderData.SetDataVersion(Get().GetVersion()); + mLeaderData.SetStableDataVersion(Get().GetStableVersion()); - mLeaderData.SetDataVersion(leaderData.GetVersion()); - mLeaderData.SetStableDataVersion(leaderData.GetStableVersion()); return mLeaderData; } @@ -1203,7 +1176,7 @@ otError Mle::AppendLinkFrameCounter(Message &aMessage) LinkFrameCounterTlv tlv; tlv.Init(); - tlv.SetFrameCounter(GetNetif().GetKeyManager().GetMacFrameCounter()); + tlv.SetFrameCounter(Get().GetMacFrameCounter()); return aMessage.Append(&tlv, sizeof(tlv)); } @@ -1213,7 +1186,7 @@ otError Mle::AppendMleFrameCounter(Message &aMessage) MleFrameCounterTlv tlv; tlv.Init(); - tlv.SetFrameCounter(GetNetif().GetKeyManager().GetMleFrameCounter()); + tlv.SetFrameCounter(Get().GetMleFrameCounter()); return aMessage.Append(&tlv, sizeof(tlv)); } @@ -1231,8 +1204,8 @@ otError Mle::AppendAddress16(Message &aMessage, uint16_t aRloc16) otError Mle::AppendLeaderData(Message &aMessage) { mLeaderData.Init(); - mLeaderData.SetDataVersion(GetNetif().GetNetworkDataLeader().GetVersion()); - mLeaderData.SetStableDataVersion(GetNetif().GetNetworkDataLeader().GetStableVersion()); + mLeaderData.SetDataVersion(Get().GetVersion()); + mLeaderData.SetStableDataVersion(Get().GetStableVersion()); return aMessage.Append(&mLeaderData, sizeof(mLeaderData)); } @@ -1242,7 +1215,7 @@ void Mle::FillNetworkDataTlv(NetworkDataTlv &aTlv, bool aStableOnly) uint8_t length = sizeof(NetworkDataTlv) - sizeof(Tlv); // sizeof( NetworkDataTlv::mNetworkData ) // Ignore result code, provided buffer must be enough - GetNetif().GetNetworkDataLeader().GetNetworkData(aStableOnly, aTlv.GetNetworkData(), length); + Get().GetNetworkData(aStableOnly, aTlv.GetNetworkData(), length); aTlv.SetLength(length); } @@ -1309,7 +1282,6 @@ otError Mle::AppendVersion(Message &aMessage) otError Mle::AppendAddressRegistration(Message &aMessage) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Tlv tlv; AddressRegistrationEntry entry; @@ -1322,7 +1294,7 @@ otError Mle::AppendAddressRegistration(Message &aMessage) SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); // write entries to message - for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = Get().GetUnicastAddresses(); addr; addr = addr->GetNext()) { if (addr->GetAddress().IsLinkLocal() || IsRoutingLocator(addr->GetAddress()) || IsAnycastLocator(addr->GetAddress())) @@ -1330,7 +1302,7 @@ otError Mle::AppendAddressRegistration(Message &aMessage) continue; } - if (netif.GetNetworkDataLeader().GetContext(addr->GetAddress(), context) == OT_ERROR_NONE) + if (Get().GetContext(addr->GetAddress(), context) == OT_ERROR_NONE) { // compressed entry entry.SetContextId(context.mContextId); @@ -1357,7 +1329,7 @@ otError Mle::AppendAddressRegistration(Message &aMessage) Ip6::Address address; // append external multicast address - while (netif.GetNextExternalMulticast(iterator, address) == OT_ERROR_NONE) + while (Get().GetNextExternalMulticast(iterator, address) == OT_ERROR_NONE) { entry.SetUncompressed(); entry.SetIp6Address(address); @@ -1396,8 +1368,8 @@ otError Mle::AppendTimeParameter(Message &aMessage) TimeParameterTlv tlv; tlv.Init(); - tlv.SetTimeSyncPeriod(GetNetif().GetTimeSync().GetTimeSyncPeriod()); - tlv.SetXtalThreshold(GetNetif().GetTimeSync().GetXtalThreshold()); + tlv.SetTimeSyncPeriod(Get().GetTimeSyncPeriod()); + tlv.SetXtalThreshold(Get().GetXtalThreshold()); return aMessage.Append(&tlv, sizeof(tlv)); } @@ -1415,12 +1387,11 @@ otError Mle::AppendXtalAccuracy(Message &aMessage) otError Mle::AppendActiveTimestamp(Message &aMessage) { - ThreadNetif & netif = GetNetif(); otError error; ActiveTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; - timestamp = netif.GetActiveDataset().GetTimestamp(); + timestamp = Get().GetTimestamp(); VerifyOrExit(timestamp, error = OT_ERROR_NONE); timestampTlv.Init(); @@ -1437,7 +1408,7 @@ otError Mle::AppendPendingTimestamp(Message &aMessage) PendingTimestampTlv timestampTlv; const MeshCoP::Timestamp *timestamp; - timestamp = GetNetif().GetPendingDataset().GetTimestamp(); + timestamp = Get().GetTimestamp(); VerifyOrExit(timestamp && timestamp->GetSeconds() != 0, error = OT_ERROR_NONE); timestampTlv.Init(); @@ -1455,20 +1426,18 @@ void Mle::HandleStateChanged(Notifier::Callback &aCallback, otChangedFlags aFlag void Mle::HandleStateChanged(otChangedFlags aFlags) { - ThreadNetif &netif = GetNetif(); - VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED); if ((aFlags & (OT_CHANGED_IP6_ADDRESS_ADDED | OT_CHANGED_IP6_ADDRESS_REMOVED)) != 0) { - if (!netif.IsUnicastAddress(mMeshLocal64.GetAddress())) + if (!Get().IsUnicastAddress(mMeshLocal64.GetAddress())) { // Mesh Local EID was removed, choose a new one and add it back Random::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE, OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE); - netif.AddUnicastAddress(mMeshLocal64); - GetNotifier().Signal(OT_CHANGED_THREAD_ML_ADDR); + Get().AddUnicastAddress(mMeshLocal64); + Get().Signal(OT_CHANGED_THREAD_ML_ADDR); } if (mRole == OT_DEVICE_ROLE_CHILD && !IsFullThreadDevice()) @@ -1491,7 +1460,7 @@ void Mle::HandleStateChanged(otChangedFlags aFlags) { if (IsFullThreadDevice()) { - netif.GetMle().HandleNetworkDataUpdateRouter(); + Get().HandleNetworkDataUpdateRouter(); } else if ((aFlags & OT_CHANGED_THREAD_ROLE) == 0) { @@ -1500,18 +1469,18 @@ void Mle::HandleStateChanged(otChangedFlags aFlags) } #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - netif.GetNetworkDataLocal().SendServerDataNotification(); + Get().SendServerDataNotification(); #if OPENTHREAD_ENABLE_SERVICE this->UpdateServiceAlocs(); #endif #endif #if OPENTHREAD_ENABLE_DHCP6_SERVER - GetNetif().GetDhcp6Server().UpdateService(); + Get().UpdateService(); #endif // OPENTHREAD_ENABLE_DHCP6_SERVER #if OPENTHREAD_ENABLE_DHCP6_CLIENT - GetNetif().GetDhcp6Client().UpdateAddresses(); + Get().UpdateAddresses(); #endif // OPENTHREAD_ENABLE_DHCP6_CLIENT } @@ -1528,8 +1497,8 @@ void Mle::HandleStateChanged(otChangedFlags aFlags) if (aFlags & OT_CHANGED_SECURITY_POLICY) { - GetNetif().GetIp6Filter().AllowNativeCommissioner( - (GetNetif().GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) != 0); + Get().AllowNativeCommissioner( + (Get().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) != 0); } exit: @@ -1539,12 +1508,10 @@ exit: #if OPENTHREAD_ENABLE_SERVICE void Mle::UpdateServiceAlocs(void) { - ThreadNetif & netif = GetNetif(); uint16_t rloc = GetRloc16(); uint16_t serviceAloc = 0; uint8_t serviceId = 0; int i = 0; - NetworkData::Leader & leaderData = netif.GetNetworkDataLeader(); otNetworkDataIterator serviceIterator = OT_NETWORK_DATA_ITERATOR_INIT; int serviceAlocsLength = OT_ARRAY_LENGTH(mServiceAlocs); @@ -1556,15 +1523,15 @@ void Mle::UpdateServiceAlocs(void) serviceAloc = HostSwap16(mServiceAlocs[i].GetAddress().mFields.m16[7]); if ((serviceAloc != Mac::kShortAddrInvalid) && - (!leaderData.ContainsService(Mle::GetServiceIdFromAloc(serviceAloc), rloc))) + (!Get().ContainsService(Mle::GetServiceIdFromAloc(serviceAloc), rloc))) { - netif.RemoveUnicastAddress(mServiceAlocs[i]); + Get().RemoveUnicastAddress(mServiceAlocs[i]); mServiceAlocs[i].GetAddress().mFields.m16[7] = HostSwap16(Mac::kShortAddrInvalid); } } // Now add any missing service alocs which should be there, if there is enough space in mServiceAlocs - while (leaderData.GetNextServiceId(&serviceIterator, rloc, &serviceId) == OT_ERROR_NONE) + while (Get().GetNextServiceId(&serviceIterator, rloc, &serviceId) == OT_ERROR_NONE) { for (i = 0; i < serviceAlocsLength; i++) { @@ -1586,7 +1553,7 @@ void Mle::UpdateServiceAlocs(void) if (serviceAloc == Mac::kShortAddrInvalid) { SuccessOrExit(GetServiceAloc(serviceId, mServiceAlocs[i].GetAddress())); - netif.AddUnicastAddress(mServiceAlocs[i]); + Get().AddUnicastAddress(mServiceAlocs[i]); break; } } @@ -1653,7 +1620,7 @@ void Mle::HandleAttachTimer(void) SetAttachState(kAttachStateParentRequestRouter); mParentCandidate.SetState(Neighbor::kStateInvalid); mReceivedResponseFromParent = false; - GetNetif().GetMeshForwarder().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); // initial MLE Parent Request has both E and R flags set in Scan Mask TLV // during reattach when losing connectivity. @@ -1726,7 +1693,7 @@ bool Mle::PrepareAnnounceState(void) VerifyOrExit((mRole != OT_DEVICE_ROLE_CHILD) && !IsFullThreadDevice() && (mReattachState == kReattachStop)); - SuccessOrExit(GetNetif().GetActiveDataset().GetChannelMask(channelMask)); + SuccessOrExit(Get().GetChannelMask(channelMask)); mAnnounceDelay = kAnnounceTimeout / (channelMask.GetNumberOfChannels() + 1); @@ -1743,14 +1710,13 @@ exit: uint32_t Mle::Reattach(void) { - ThreadNetif &netif = GetNetif(); - uint32_t delay = 0; + uint32_t delay = 0; if (mReattachState == kReattachActive) { - if (netif.GetPendingDataset().Restore() == OT_ERROR_NONE) + if (Get().Restore() == OT_ERROR_NONE) { - netif.GetPendingDataset().ApplyConfiguration(); + Get().ApplyConfiguration(); mReattachState = kReattachPending; SetAttachState(kAttachStateStart); delay = 1 + Random::GetUint32InRange(0, kAttachStartJitter); @@ -1763,7 +1729,7 @@ uint32_t Mle::Reattach(void) else if (mReattachState == kReattachPending) { mReattachState = kReattachStop; - netif.GetActiveDataset().Restore(); + Get().Restore(); } VerifyOrExit(mReattachState == kReattachStop); @@ -1775,8 +1741,8 @@ uint32_t Mle::Reattach(void) { if (mAlternatePanId != Mac::kPanIdBroadcast) { - netif.GetMac().SetPanChannel(mAlternateChannel); - netif.GetMac().SetPanId(mAlternatePanId); + Get().SetPanChannel(mAlternateChannel); + Get().SetPanId(mAlternatePanId); mAlternatePanId = Mac::kPanIdBroadcast; BecomeDetached(); } @@ -1784,7 +1750,7 @@ uint32_t Mle::Reattach(void) { BecomeDetached(); } - else if (netif.GetMle().BecomeLeader() != OT_ERROR_NONE) + else if (Get().BecomeLeader() != OT_ERROR_NONE) { BecomeDetached(); } @@ -1792,8 +1758,8 @@ uint32_t Mle::Reattach(void) else if (!IsRxOnWhenIdle()) { // return to sleepy operation - netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); - netif.GetMeshForwarder().SetRxOnWhenIdle(false); + Get().SetAttachMode(false); + Get().SetRxOnWhenIdle(false); } break; @@ -2005,8 +1971,8 @@ otError Mle::SendChildIdRequest(void) if (!IsRxOnWhenIdle()) { - GetNetif().GetMeshForwarder().GetDataPollManager().SetAttachMode(true); - GetNetif().GetMeshForwarder().SetRxOnWhenIdle(false); + Get().SetAttachMode(true); + Get().SetRxOnWhenIdle(false); } exit: @@ -2045,7 +2011,7 @@ otError Mle::SendDataRequest(const Ip6::Address &aDestination, if (!IsRxOnWhenIdle()) { - GetNetif().GetMeshForwarder().GetDataPollManager().SendFastPolls(DataPollManager::kDefaultFastPolls); + Get().SendFastPolls(DataPollManager::kDefaultFastPolls); } } @@ -2152,7 +2118,7 @@ void Mle::HandleMessageTransmissionTimer(void) break; case kChildUpdateRequestPending: - if (GetNotifier().IsPending()) + if (Get().IsPending()) { // Here intentionally delay another kChildUpdateRequestPendingDelay // cycle to ensure we only send a Child Update Request after we @@ -2181,7 +2147,6 @@ exit: otError Mle::SendChildUpdateRequest(void) { - ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Address destination; Message * message = NULL; @@ -2235,12 +2200,12 @@ otError Mle::SendChildUpdateRequest(void) if (!IsRxOnWhenIdle()) { - netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(true); - netif.GetMeshForwarder().SetRxOnWhenIdle(false); + Get().SetAttachMode(true); + Get().SetRxOnWhenIdle(false); } else { - netif.GetMeshForwarder().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); } exit: @@ -2324,14 +2289,13 @@ otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce) otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce, const Ip6::Address &aDestination) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ChannelTlv channel; PanIdTlv panid; ActiveTimestampTlv activeTimestamp; Message * message = NULL; - VerifyOrExit(netif.GetMac().GetSupportedChannelMask().ContainsChannel(aChannel), error = OT_ERROR_INVALID_ARGS); + VerifyOrExit(Get().GetSupportedChannelMask().ContainsChannel(aChannel), error = OT_ERROR_INVALID_ARGS); VerifyOrExit((message = NewMleMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetLinkSecurityEnabled(true); message->SetSubType(Message::kSubTypeMleAnnounce); @@ -2339,7 +2303,7 @@ otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce, const Ip6::Add SuccessOrExit(error = AppendHeader(*message, Header::kCommandAnnounce)); channel.Init(); - channel.SetChannel(netif.GetMac().GetPanChannel()); + channel.SetChannel(Get().GetPanChannel()); SuccessOrExit(error = message->Append(&channel, sizeof(channel))); if (aOrphanAnnounce) @@ -2357,7 +2321,7 @@ otError Mle::SendAnnounce(uint8_t aChannel, bool aOrphanAnnounce, const Ip6::Add } panid.Init(); - panid.SetPanId(netif.GetMac().GetPanId()); + panid.SetPanId(Get().GetPanId()); SuccessOrExit(error = message->Append(&panid, sizeof(panid))); SuccessOrExit(error = SendMessage(*message, aDestination)); @@ -2378,7 +2342,7 @@ otError Mle::SendOrphanAnnounce(void) otError error; Mac::ChannelMask channelMask; - SuccessOrExit(error = GetNetif().GetActiveDataset().GetChannelMask(channelMask)); + SuccessOrExit(error = Get().GetChannelMask(channelMask)); SuccessOrExit(error = channelMask.GetNextChannel(mAnnounceChannel)); SendAnnounce(mAnnounceChannel, true); @@ -2389,9 +2353,7 @@ exit: otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) { - ThreadNetif & netif = GetNetif(); - KeyManager & keyManager = netif.GetKeyManager(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; Header header; uint32_t keySequence; uint8_t nonce[13]; @@ -2406,16 +2368,17 @@ otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) if (header.GetSecuritySuite() == Header::k154Security) { - header.SetFrameCounter(keyManager.GetMleFrameCounter()); + header.SetFrameCounter(Get().GetMleFrameCounter()); - keySequence = keyManager.GetCurrentKeySequence(); + keySequence = Get().GetCurrentKeySequence(); header.SetKeyId(keySequence); aMessage.Write(0, header.GetLength(), &header); - GenerateNonce(netif.GetMac().GetExtAddress(), keyManager.GetMleFrameCounter(), Mac::Frame::kSecEncMic32, nonce); + GenerateNonce(Get().GetExtAddress(), Get().GetMleFrameCounter(), Mac::Frame::kSecEncMic32, + nonce); - aesCcm.SetKey(keyManager.GetCurrentMleKey(), 16); + aesCcm.SetKey(Get().GetCurrentMleKey(), 16); error = aesCcm.Init(16 + 16 + header.GetHeaderLength(), aMessage.GetLength() - (header.GetLength() - 1), sizeof(tag), nonce, sizeof(nonce)); assert(error == OT_ERROR_NONE); @@ -2438,13 +2401,13 @@ otError Mle::SendMessage(Message &aMessage, const Ip6::Address &aDestination) aesCcm.Finalize(tag, &tagLength); SuccessOrExit(error = aMessage.Append(tag, tagLength)); - keyManager.IncrementMleFrameCounter(); + Get().IncrementMleFrameCounter(); } messageInfo.SetPeerAddr(aDestination); messageInfo.SetSockAddr(mLinkLocal64.GetAddress()); messageInfo.SetPeerPort(kUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); messageInfo.SetHopLimit(kMleHopLimit); SuccessOrExit(error = mSocket.SendTo(aMessage, messageInfo)); @@ -2492,9 +2455,6 @@ void Mle::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageI void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); - KeyManager & keyManager = netif.GetKeyManager(); - MleRouter & mle = netif.GetMle(); Header header; uint32_t keySequence; const uint8_t * mleKey; @@ -2524,7 +2484,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn switch (header.GetCommand()) { case Header::kCommandDiscoveryRequest: - mle.HandleDiscoveryRequest(aMessage, aMessageInfo); + Get().HandleDiscoveryRequest(aMessage, aMessageInfo); break; case Header::kCommandDiscoveryResponse: @@ -2542,13 +2502,13 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn keySequence = header.GetKeyId(); - if (keySequence == keyManager.GetCurrentKeySequence()) + if (keySequence == Get().GetCurrentKeySequence()) { - mleKey = keyManager.GetCurrentMleKey(); + mleKey = Get().GetCurrentMleKey(); } else { - mleKey = keyManager.GetTemporaryMleKey(keySequence); + mleKey = Get().GetTemporaryMleKey(keySequence); } VerifyOrExit(aMessage.GetOffset() + header.GetLength() + sizeof(messageTag) <= aMessage.GetLength()); @@ -2588,9 +2548,9 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn VerifyOrExit(memcmp(messageTag, tag, sizeof(tag)) == 0); #endif - if (keySequence > keyManager.GetCurrentKeySequence()) + if (keySequence > Get().GetCurrentKeySequence()) { - keyManager.SetCurrentKeySequence(keySequence); + Get().SetCurrentKeySequence(keySequence); } aMessage.SetOffset(mleOffset); @@ -2613,7 +2573,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn } else { - neighbor = mle.GetNeighbor(macAddr); + neighbor = Get().GetNeighbor(macAddr); } break; @@ -2663,15 +2623,15 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn switch (command) { case Header::kCommandLinkRequest: - mle.HandleLinkRequest(aMessage, aMessageInfo); + Get().HandleLinkRequest(aMessage, aMessageInfo); break; case Header::kCommandLinkAccept: - mle.HandleLinkAccept(aMessage, aMessageInfo, keySequence); + Get().HandleLinkAccept(aMessage, aMessageInfo, keySequence); break; case Header::kCommandLinkAcceptAndRequest: - mle.HandleLinkAcceptAndRequest(aMessage, aMessageInfo, keySequence); + Get().HandleLinkAcceptAndRequest(aMessage, aMessageInfo, keySequence); break; case Header::kCommandAdvertisement: @@ -2679,7 +2639,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandDataRequest: - mle.HandleDataRequest(aMessage, aMessageInfo); + Get().HandleDataRequest(aMessage, aMessageInfo); break; case Header::kCommandDataResponse: @@ -2687,7 +2647,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandParentRequest: - mle.HandleParentRequest(aMessage, aMessageInfo); + Get().HandleParentRequest(aMessage, aMessageInfo); break; case Header::kCommandParentResponse: @@ -2695,7 +2655,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn break; case Header::kCommandChildIdRequest: - mle.HandleChildIdRequest(aMessage, aMessageInfo, keySequence); + Get().HandleChildIdRequest(aMessage, aMessageInfo, keySequence); break; case Header::kCommandChildIdResponse: @@ -2705,7 +2665,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn case Header::kCommandChildUpdateRequest: if (mRole == OT_DEVICE_ROLE_LEADER || mRole == OT_DEVICE_ROLE_ROUTER) { - mle.HandleChildUpdateRequest(aMessage, aMessageInfo, keySequence); + Get().HandleChildUpdateRequest(aMessage, aMessageInfo, keySequence); } else { @@ -2717,7 +2677,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn case Header::kCommandChildUpdateResponse: if (mRole == OT_DEVICE_ROLE_LEADER || mRole == OT_DEVICE_ROLE_ROUTER) { - mle.HandleChildUpdateResponse(aMessage, aMessageInfo, keySequence); + Get().HandleChildUpdateResponse(aMessage, aMessageInfo, keySequence); } else { @@ -2732,7 +2692,7 @@ void Mle::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageIn #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC case Header::kCommandTimeSync: - mle.HandleTimeSync(aMessage, aMessageInfo); + Get().HandleTimeSync(aMessage, aMessageInfo); break; #endif } @@ -2743,7 +2703,6 @@ exit: otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Mac::ExtAddress macAddr; bool isNeighbor; @@ -2770,7 +2729,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo { if (IsFullThreadDevice()) { - SuccessOrExit(error = netif.GetMle().HandleAdvertisement(aMessage, aMessageInfo)); + SuccessOrExit(error = Get().HandleAdvertisement(aMessage, aMessageInfo)); } else { @@ -2807,7 +2766,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo route.IsValid()) { // Overwrite Route Data - netif.GetMle().ProcessRouteTlv(route); + Get().ProcessRouteTlv(route); } mRetrieveNewNetworkData = true; @@ -2819,7 +2778,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - if ((neighbor = netif.GetMle().GetNeighbor(macAddr)) != NULL && neighbor->GetState() == Neighbor::kStateValid) + if ((neighbor = Get().GetNeighbor(macAddr)) != NULL && neighbor->GetState() == Neighbor::kStateValid) { isNeighbor = true; } @@ -2830,7 +2789,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo if (isNeighbor) { if (mRetrieveNewNetworkData || - (static_cast(leaderData.GetDataVersion() - netif.GetNetworkDataLeader().GetVersion()) > 0)) + (static_cast(leaderData.GetDataVersion() - Get().GetVersion()) > 0)) { delay = Random::GetUint16InRange(0, kMleMaxResponseDelay); SendDataRequest(aMessageInfo.GetPeerAddr(), tlvs, sizeof(tlvs), delay); @@ -2859,7 +2818,6 @@ 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; ActiveTimestampTlv activeTimestamp; @@ -2893,12 +2851,12 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (IsFullNetworkData()) { - diff = static_cast(leaderData.GetDataVersion() - netif.GetNetworkDataLeader().GetVersion()); + diff = static_cast(leaderData.GetDataVersion() - Get().GetVersion()); } else { - diff = static_cast(leaderData.GetStableDataVersion() - - netif.GetNetworkDataLeader().GetStableVersion()); + diff = + static_cast(leaderData.GetStableDataVersion() - Get().GetStableVersion()); } VerifyOrExit(diff > 0); @@ -2910,7 +2868,7 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a const MeshCoP::Timestamp *timestamp; VerifyOrExit(activeTimestamp.IsValid(), error = OT_ERROR_PARSE); - timestamp = netif.GetActiveDataset().GetTimestamp(); + timestamp = Get().GetTimestamp(); // if received timestamp does not match the local value and message does not contain the dataset, // send MLE Data Request @@ -2931,7 +2889,7 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a const MeshCoP::Timestamp *timestamp; VerifyOrExit(pendingTimestamp.IsValid(), error = OT_ERROR_PARSE); - timestamp = netif.GetPendingDataset().GetTimestamp(); + timestamp = Get().GetTimestamp(); // if received timestamp does not match the local value and message does not contain the dataset, // send MLE Data Request @@ -2949,8 +2907,8 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (Tlv::GetOffset(aMessage, Tlv::kNetworkData, networkDataOffset) == OT_ERROR_NONE) { error = - netif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), - !IsFullNetworkData(), aMessage, networkDataOffset); + Get().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), + !IsFullNetworkData(), aMessage, networkDataOffset); SuccessOrExit(error); } else @@ -2964,8 +2922,8 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (activeDatasetOffset > 0) { aMessage.Read(activeDatasetOffset, sizeof(tlv), &tlv); - netif.GetActiveDataset().Save(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), - tlv.GetLength()); + Get().Save(activeTimestamp, aMessage, activeDatasetOffset + sizeof(tlv), + tlv.GetLength()); } } @@ -2975,8 +2933,8 @@ otError Mle::HandleLeaderData(const Message &aMessage, const Ip6::MessageInfo &a if (pendingDatasetOffset > 0) { aMessage.Read(pendingDatasetOffset, sizeof(tlv), &tlv); - netif.GetPendingDataset().Save(pendingTimestamp, aMessage, pendingDatasetOffset + sizeof(tlv), - tlv.GetLength()); + Get().Save(pendingTimestamp, aMessage, pendingDatasetOffset + sizeof(tlv), + tlv.GetLength()); } } @@ -3072,7 +3030,6 @@ 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 otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); ResponseTlv response; @@ -3117,7 +3074,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(netif.GetMac().GetNoiseFloor(), linkInfo->mRss); + linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(Get().GetNoiseFloor(), linkInfo->mRss); if (linkMargin > linkMarginTlv.GetLinkMargin()) { @@ -3152,8 +3109,7 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf #if OPENTHREAD_FTD if (IsFullThreadDevice() && (mRole != OT_DEVICE_ROLE_DETACHED)) { - int8_t diff = - static_cast(connectivity.GetIdSequence() - netif.GetMle().GetRouterTable().GetRouterIdSequence()); + int8_t diff = static_cast(connectivity.GetIdSequence() - Get().GetRouterIdSequence()); switch (mParentRequestMode) { @@ -3174,8 +3130,9 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf case kAttachBetter: VerifyOrExit(leaderData.GetPartitionId() != mLeaderData.GetPartitionId()); + VerifyOrExit(MleRouter::ComparePartitions(connectivity.GetActiveRouters() <= 1, leaderData, - netif.GetMle().IsSingleton(), mLeaderData) > 0); + Get().IsSingleton(), mLeaderData) > 0); break; } } @@ -3220,8 +3177,8 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf { VerifyOrExit(timeParameter.IsValid()); - GetNetif().GetTimeSync().SetTimeSyncPeriod(timeParameter.GetTimeSyncPeriod()); - GetNetif().GetTimeSync().SetXtalThreshold(timeParameter.GetXtalThreshold()); + Get().SetTimeSyncPeriod(timeParameter.GetTimeSyncPeriod()); + Get().SetXtalThreshold(timeParameter.GetXtalThreshold()); } #if OPENTHREAD_CONFIG_TIME_SYNC_REQUIRED @@ -3247,7 +3204,7 @@ otError Mle::HandleParentResponse(const Message &aMessage, const Ip6::MessageInf mParentCandidate.SetDeviceMode(ModeTlv::kModeFullThreadDevice | ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeFullNetworkData | ModeTlv::kModeSecureDataRequest); mParentCandidate.GetLinkInfo().Clear(); - mParentCandidate.GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), linkInfo->mRss); + mParentCandidate.GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); mParentCandidate.ResetLinkFailures(); mParentCandidate.SetLinkQualityOut(LinkQualityInfo::ConvertLinkMarginToLinkQuality(linkMarginTlv.GetLinkMargin())); mParentCandidate.SetState(Neighbor::kStateParentResponse); @@ -3276,7 +3233,6 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn { OT_UNUSED_VARIABLE(aMessageInfo); - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; LeaderDataTlv leaderData; SourceAddressTlv sourceAddress; @@ -3317,14 +3273,14 @@ 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); - netif.GetActiveDataset().Save(activeTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); + Get().Save(activeTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); } } // clear Pending Dataset if device succeed to reattach using stored Pending Dataset if (mReattachState == kReattachPending) { - netif.GetPendingDataset().Clear(); + Get().Clear(); } // Pending Timestamp @@ -3336,19 +3292,19 @@ 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); - netif.GetPendingDataset().Save(pendingTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); + Get().Save(pendingTimestamp, aMessage, offset + sizeof(tlv), tlv.GetLength()); } } else { - netif.GetPendingDataset().ClearNetwork(); + Get().ClearNetwork(); } #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC // Sync to Thread network time if (aMessage.GetTimeSyncSeq() != OT_TIME_SYNC_INVALID_SEQ) { - GetNetif().GetTimeSync().HandleTimeSyncMessage(aMessage); + Get().HandleTimeSyncMessage(aMessage); } #endif @@ -3360,18 +3316,18 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn if (!IsRxOnWhenIdle()) { - netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); - netif.GetMeshForwarder().SetRxOnWhenIdle(false); + Get().SetAttachMode(false); + Get().SetRxOnWhenIdle(false); } else { - netif.GetMeshForwarder().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); } // Route if ((Tlv::GetTlv(aMessage, Tlv::kRoute, sizeof(route), route) == OT_ERROR_NONE) && IsFullThreadDevice()) { - SuccessOrExit(error = netif.GetMle().ProcessRouteTlv(route)); + SuccessOrExit(error = Get().ProcessRouteTlv(route)); } mParent = mParentCandidate; @@ -3379,10 +3335,10 @@ otError Mle::HandleChildIdResponse(const Message &aMessage, const Ip6::MessageIn mParent.SetRloc16(sourceAddress.GetRloc16()); - netif.GetNetworkDataLeader().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), - !IsFullNetworkData(), aMessage, networkDataOffset); + Get().SetNetworkData(leaderData.GetDataVersion(), leaderData.GetStableDataVersion(), + !IsFullNetworkData(), aMessage, networkDataOffset); - netif.GetActiveDataset().ApplyConfiguration(); + Get().ApplyConfiguration(); SetStateChild(shortAddress.GetRloc16()); @@ -3461,7 +3417,6 @@ exit: otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; StatusTlv status; ModeTlv mode; @@ -3547,12 +3502,12 @@ otError Mle::HandleChildUpdateResponse(const Message &aMessage, const Ip6::Messa if (!IsRxOnWhenIdle()) { - netif.GetMeshForwarder().GetDataPollManager().SetAttachMode(false); - netif.GetMeshForwarder().SetRxOnWhenIdle(false); + Get().SetAttachMode(false); + Get().SetRxOnWhenIdle(false); } else { - netif.GetMeshForwarder().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); } break; @@ -3598,18 +3553,16 @@ otError Mle::HandleAnnounce(const Message &aMessage, const Ip6::MessageInfo &aMe VerifyOrExit(panIdTlv.IsValid(), error = OT_ERROR_PARSE); panId = panIdTlv.GetPanId(); - localTimestamp = GetNetif().GetActiveDataset().GetTimestamp(); + localTimestamp = Get().GetTimestamp(); if (localTimestamp == NULL || localTimestamp->Compare(timestamp) > 0) { - Mac::Mac &mac = GetNetif().GetMac(); - // No action is required if device is detached, and current // channel and pan-id match the values from the received MLE // Announce message. - VerifyOrExit((mRole != OT_DEVICE_ROLE_DETACHED) || (mac.GetPanChannel() != channel) || - (mac.GetPanId() != panId)); + VerifyOrExit((mRole != OT_DEVICE_ROLE_DETACHED) || (Get().GetPanChannel() != channel) || + (Get().GetPanId() != panId)); if (mAttachState == kAttachStateProcessAnnounce) { @@ -3646,9 +3599,8 @@ exit: void Mle::ProcessAnnounce(void) { - Mac::Mac &mac = GetNetif().GetMac(); - uint8_t newChannel = mAlternateChannel; - uint16_t newPanId = mAlternatePanId; + uint8_t newChannel = mAlternateChannel; + uint16_t newPanId = mAlternatePanId; assert(mAttachState == kAttachStateProcessAnnounce); @@ -3657,12 +3609,12 @@ void Mle::ProcessAnnounce(void) Stop(/* aClearNetworkDatasets */ false); // Save the current/previous channel and pan-id - mAlternateChannel = mac.GetPanChannel(); - mAlternatePanId = mac.GetPanId(); + mAlternateChannel = Get().GetPanChannel(); + mAlternatePanId = Get().GetPanId(); mAlternateTimestamp = 0; - mac.SetPanChannel(newChannel); - mac.SetPanId(newPanId); + Get().SetPanChannel(newChannel); + Get().SetPanId(newPanId); Start(/* aAnnounceAttach */ true); } @@ -3890,7 +3842,6 @@ Router *Mle::GetParentCandidate(void) otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_DROP; Ip6::MessageInfo messageInfo; @@ -3899,17 +3850,17 @@ otError Mle::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::He ExitNow(error = OT_ERROR_NONE); } - if (netif.IsUnicastAddress(aIp6Header.GetDestination())) + if (Get().IsUnicastAddress(aIp6Header.GetDestination())) { ExitNow(error = OT_ERROR_NONE); } messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, - messageInfo, aIp6Header); + Get().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, messageInfo, + aIp6Header); exit: return error; @@ -3918,7 +3869,6 @@ exit: #if OPENTHREAD_CONFIG_INFORM_PREVIOUS_PARENT_ON_REATTACH otError Mle::InformPreviousParent(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Message * message = NULL; Ip6::MessageInfo messageInfo; @@ -3927,15 +3877,15 @@ otError Mle::InformPreviousParent(void) mCounters.mParentChanges++; - VerifyOrExit((message = netif.GetIp6().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage(0)) != NULL, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = message->SetLength(0)); messageInfo.SetSockAddr(GetMeshLocal64()); messageInfo.SetPeerAddr(GetMeshLocal16()); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(mPreviousParentRloc); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetIp6().SendDatagram(*message, messageInfo, Ip6::kProtoNone)); + SuccessOrExit(error = Get().SendDatagram(*message, messageInfo, Ip6::kProtoNone)); otLogNoteMle("Sending message to inform previous parent 0x%04x", mPreviousParentRloc); diff --git a/src/core/thread/mle_router.cpp b/src/core/thread/mle_router.cpp index f016141da..dec3d7173 100644 --- a/src/core/thread/mle_router.cpp +++ b/src/core/thread/mle_router.cpp @@ -40,8 +40,8 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "mac/mac_frame.hpp" @@ -90,14 +90,12 @@ MleRouter::MleRouter(Instance &aInstance) void MleRouter::HandlePartitionChange(void) { - ThreadNetif &netif = GetNetif(); - mPreviousPartitionId = mLeaderData.GetPartitionId(); mPreviousPartitionRouterIdSequence = mRouterTable.GetRouterIdSequence(); - mPreviousPartitionIdTimeout = netif.GetMle().GetNetworkIdTimeout(); + mPreviousPartitionIdTimeout = GetNetworkIdTimeout(); - netif.GetAddressResolver().Clear(); - netif.GetCoap().AbortTransaction(&MleRouter::HandleAddressSolicitResponse, this); + Get().Clear(); + Get().AbortTransaction(&MleRouter::HandleAddressSolicitResponse, this); mRouterTable.Clear(); } @@ -117,7 +115,7 @@ void MleRouter::SetRouterRoleEnabled(bool aEnabled) break; case OT_DEVICE_ROLE_CHILD: - GetNetif().GetMac().SetBeaconEnabled(mRouterRoleEnabled); + Get().SetBeaconEnabled(mRouterRoleEnabled); break; case OT_DEVICE_ROLE_ROUTER: @@ -133,8 +131,7 @@ void MleRouter::SetRouterRoleEnabled(bool aEnabled) otError MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mRole != OT_DEVICE_ROLE_ROUTER, error = OT_ERROR_NONE); @@ -142,7 +139,7 @@ otError MleRouter::BecomeRouter(ThreadStatusTlv::Status aStatus) otLogInfoMle("Attempt to become router"); - netif.GetMeshForwarder().SetRxOnWhenIdle(true); + Get().SetRxOnWhenIdle(true); mRouterSelectionJitterTimeout = 0; switch (mRole) @@ -167,11 +164,10 @@ exit: otError MleRouter::BecomeLeader(void) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - Router * router; - uint32_t partitionId; - uint8_t leaderId; + otError error = OT_ERROR_NONE; + Router * router; + uint32_t partitionId; + uint8_t leaderId; VerifyOrExit(mRole != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(mRole != OT_DEVICE_ROLE_LEADER, error = OT_ERROR_NONE); @@ -189,10 +185,10 @@ otError MleRouter::BecomeLeader(void) assert(router != NULL); SetRouterId(leaderId); - router->SetExtAddress(netif.GetMac().GetExtAddress()); + router->SetExtAddress(Get().GetExtAddress()); - netif.GetNetworkDataLeader().Reset(); - netif.GetLeader().SetEmptyCommissionerData(); + Get().Reset(); + Get().SetEmptyCommissionerData(); SetStateLeader(GetRloc16(leaderId)); @@ -202,15 +198,13 @@ exit: void MleRouter::StopLeader(void) { - ThreadNetif &netif = GetNetif(); - - netif.GetCoap().RemoveResource(mAddressSolicit); - netif.GetCoap().RemoveResource(mAddressRelease); - netif.GetActiveDataset().StopLeader(); - netif.GetPendingDataset().StopLeader(); + Get().RemoveResource(mAddressSolicit); + Get().RemoveResource(mAddressRelease); + Get().StopLeader(); + Get().StopLeader(); mAdvertiseTimer.Stop(); - netif.GetNetworkDataLeader().Stop(); - netif.UnsubscribeAllRoutersMulticast(); + Get().Stop(); + Get().UnsubscribeAllRoutersMulticast(); } void MleRouter::HandleDetachStart(void) @@ -222,8 +216,7 @@ void MleRouter::HandleDetachStart(void) otError MleRouter::HandleChildStart(AttachMode aMode) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; + otError error = OT_ERROR_NONE; mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter); @@ -232,10 +225,10 @@ otError MleRouter::HandleChildStart(AttachMode aMode) if (mRouterRoleEnabled) { - netif.GetMac().SetBeaconEnabled(true); + Get().SetBeaconEnabled(true); } - netif.SubscribeAllRoutersMulticast(); + Get().SubscribeAllRoutersMulticast(); VerifyOrExit(IsRouterIdValid(mPreviousRouterId), error = OT_ERROR_INVALID_STATE); @@ -301,8 +294,6 @@ exit: void MleRouter::SetStateRouter(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - SetRloc16(aRloc16); SetRole(OT_DEVICE_ROLE_ROUTER); @@ -313,12 +304,12 @@ void MleRouter::SetStateRouter(uint16_t aRloc16) mAdvertiseTimer.Stop(); ResetAdvertiseInterval(); - netif.SubscribeAllRoutersMulticast(); + Get().SubscribeAllRoutersMulticast(); mPreviousPartitionIdRouter = mLeaderData.GetPartitionId(); - netif.GetNetworkDataLeader().Stop(); - netif.GetIp6().SetForwardingEnabled(true); - netif.GetIp6().GetMpl().SetTimerExpirations(kMplRouterDataMessageTimerExpirations); - netif.GetMac().SetBeaconEnabled(true); + Get().Stop(); + Get().SetForwardingEnabled(true); + Get().SetTimerExpirations(kMplRouterDataMessageTimerExpirations); + Get().SetBeaconEnabled(true); // remove children that do not have matching RLOC16 for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateValidOrRestoring); !iter.IsDone(); iter++) @@ -332,8 +323,6 @@ void MleRouter::SetStateRouter(uint16_t aRloc16) void MleRouter::SetStateLeader(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - SetRloc16(aRloc16); SetRole(OT_DEVICE_ROLE_LEADER); @@ -345,19 +334,19 @@ void MleRouter::SetStateLeader(uint16_t aRloc16) ResetAdvertiseInterval(); AddLeaderAloc(); - netif.SubscribeAllRoutersMulticast(); + Get().SubscribeAllRoutersMulticast(); mPreviousPartitionIdRouter = mLeaderData.GetPartitionId(); mStateUpdateTimer.Start(kStateUpdatePeriod); - netif.GetNetworkDataLeader().Start(); - netif.GetActiveDataset().StartLeader(); - netif.GetPendingDataset().StartLeader(); - netif.GetCoap().AddResource(mAddressSolicit); - netif.GetCoap().AddResource(mAddressRelease); - netif.GetIp6().SetForwardingEnabled(true); - netif.GetIp6().GetMpl().SetTimerExpirations(kMplRouterDataMessageTimerExpirations); - netif.GetMac().SetBeaconEnabled(true); - netif.GetAddressResolver().Clear(); + Get().Start(); + Get().StartLeader(); + Get().StartLeader(); + Get().AddResource(mAddressSolicit); + Get().AddResource(mAddressRelease); + Get().SetForwardingEnabled(true); + Get().SetTimerExpirations(kMplRouterDataMessageTimerExpirations); + Get().SetBeaconEnabled(true); + Get().Clear(); // remove children that do not have matching RLOC16 for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateValidOrRestoring); !iter.IsDone(); iter++) @@ -628,7 +617,7 @@ otError MleRouter::HandleLinkRequest(const Message &aMessage, const Ip6::Message neighbor->SetExtAddress(macAddr); neighbor->GetLinkInfo().Clear(); - neighbor->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + neighbor->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); neighbor->ResetLinkFailures(); neighbor->SetLastHeard(TimerMilli::GetNow()); neighbor->SetState(Neighbor::kStateLinkRequest); @@ -707,7 +696,7 @@ otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo, SuccessOrExit(error = AppendMleFrameCounter(*message)); // always append a link margin, regardless of whether or not it was requested - linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(Get().GetNoiseFloor(), linkInfo->mRss); SuccessOrExit(error = AppendLinkMargin(*message, linkMargin)); @@ -939,7 +928,7 @@ otError MleRouter::HandleLinkAccept(const Message & aMessage, SendDataRequest(aMessageInfo.GetPeerAddr(), dataRequestTlvs, sizeof(dataRequestTlvs), 0); #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC - GetNetif().GetTimeSync().HandleTimeSyncMessage(aMessage); + Get().HandleTimeSyncMessage(aMessage); #endif break; @@ -957,7 +946,7 @@ otError MleRouter::HandleLinkAccept(const Message & aMessage, VerifyOrExit(leaderData.GetPartitionId() == mLeaderData.GetPartitionId()); if (mRetrieveNewNetworkData || - (static_cast(leaderData.GetDataVersion() - GetNetif().GetNetworkDataLeader().GetVersion()) > 0)) + (static_cast(leaderData.GetDataVersion() - Get().GetVersion()) > 0)) { SendDataRequest(aMessageInfo.GetPeerAddr(), dataRequestTlvs, sizeof(dataRequestTlvs), 0); } @@ -987,7 +976,7 @@ otError MleRouter::HandleLinkAccept(const Message & aMessage, router->SetLastHeard(TimerMilli::GetNow()); router->SetDeviceMode(ModeTlv::kModeFullThreadDevice | ModeTlv::kModeRxOnWhenIdle | ModeTlv::kModeFullNetworkData); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + router->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); router->SetLinkQualityOut(LinkQualityInfo::ConvertLinkMarginToLinkQuality(linkMargin.GetLinkMargin())); router->ResetLinkFailures(); router->SetState(Neighbor::kStateValid); @@ -1154,10 +1143,9 @@ exit: otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); - uint8_t linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + uint8_t linkMargin = LinkQualityInfo::ConvertRssToLinkMargin(Get().GetNoiseFloor(), linkInfo->mRss); Mac::ExtAddress macAddr; SourceAddressTlv sourceAddress; LeaderDataTlv leaderData; @@ -1244,7 +1232,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa routerId = GetRouterId(sourceAddress.GetRloc16()); #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC - GetNetif().GetTimeSync().HandleTimeSyncMessage(aMessage); + Get().HandleTimeSyncMessage(aMessage); #endif if (IsFullThreadDevice() && @@ -1354,7 +1342,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa { router->SetExtAddress(macAddr); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), linkInfo->mRss); + router->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); router->ResetLinkFailures(); router->SetLastHeard(TimerMilli::GetNow()); router->SetState(Neighbor::kStateLinkRequest); @@ -1400,7 +1388,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa { router->SetExtAddress(macAddr); router->GetLinkInfo().Clear(); - router->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), linkInfo->mRss); + router->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); router->ResetLinkFailures(); router->SetLastHeard(TimerMilli::GetNow()); router->SetState(Neighbor::kStateLinkRequest); @@ -1416,7 +1404,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa UpdateRoutes(route, routerId); #if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - netif.GetNetworkDataLocal().SendServerDataNotification(); + Get().SendServerDataNotification(); #endif exit: @@ -1425,15 +1413,14 @@ exit: void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) { - MleRouter &mle = GetNetif().GetMle(); - Router * neighbor; - uint8_t curCost; - uint8_t newCost; - uint8_t oldNextHop; - uint8_t cost; - uint8_t linkQuality; - bool update; - bool changed = false; + Router *neighbor; + uint8_t curCost; + uint8_t newCost; + uint8_t oldNextHop; + uint8_t cost; + uint8_t linkQuality; + bool update; + bool changed = false; neighbor = mRouterTable.GetRouter(aRouterId); VerifyOrExit(neighbor != NULL); @@ -1461,7 +1448,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) continue; } - if (router->GetRloc16() == mle.GetRloc16()) + if (router->GetRloc16() == GetRloc16()) { linkQuality = aRoute.GetLinkQualityIn(routeCount); @@ -1500,7 +1487,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) { if (nextHop == NULL && mRouterTable.GetLinkCost(*router) >= kMaxRouteCost) { - mle.ResetAdvertiseInterval(); + ResetAdvertiseInterval(); } router->SetNextHop(aRouterId); @@ -1511,7 +1498,7 @@ void MleRouter::UpdateRoutes(const RouteTlv &aRoute, uint8_t aRouterId) { if (mRouterTable.GetLinkCost(*router) >= kMaxRouteCost) { - mle.ResetAdvertiseInterval(); + ResetAdvertiseInterval(); } router->SetNextHop(kInvalidRouterId); @@ -1635,18 +1622,18 @@ otError MleRouter::HandleParentRequest(const Message &aMessage, const Ip6::Messa SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kChallenge, sizeof(challenge), challenge)); VerifyOrExit(challenge.IsValid(), error = OT_ERROR_PARSE); - child = GetChildTable().FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); + child = mChildTable.FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); if (child == NULL) { - VerifyOrExit((child = GetChildTable().GetNewChild()) != NULL); + VerifyOrExit((child = mChildTable.GetNewChild()) != NULL); memset(child, 0, sizeof(*child)); // MAC Address child->SetExtAddress(macAddr); child->GetLinkInfo().Clear(); - child->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + child->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); child->ResetLinkFailures(); child->SetState(Neighbor::kStateParentRequest); child->SetDataRequestPending(false); @@ -1886,7 +1873,7 @@ void MleRouter::HandleStateUpdateTimer(void) #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC if (mRole == OT_DEVICE_ROLE_LEADER || mRole == OT_DEVICE_ROLE_ROUTER) { - GetNetif().GetTimeSync().ProcessTimeSync(); + Get().ProcessTimeSync(); } #endif @@ -1920,7 +1907,7 @@ void MleRouter::SendParentResponse(Child *aChild, const ChallengeTlv &aChallenge aChild->GenerateChallenge(); SuccessOrExit(error = AppendChallenge(*message, aChild->GetChallenge(), aChild->GetChallengeSize())); - error = AppendLinkMargin(*message, aChild->GetLinkInfo().GetLinkMargin(GetNetif().GetMac().GetNoiseFloor())); + error = AppendLinkMargin(*message, aChild->GetLinkInfo().GetLinkMargin(Get().GetNoiseFloor())); SuccessOrExit(error); SuccessOrExit(error = AppendConnectivity(*message)); @@ -1986,7 +1973,7 @@ otError MleRouter::UpdateChildAddresses(const Message &aMessage, uint16_t aOffse if (entry.IsCompressed()) { - if (GetNetif().GetNetworkDataLeader().GetContext(entry.GetContextId(), context) != OT_ERROR_NONE) + if (Get().GetContext(entry.GetContextId(), context) != OT_ERROR_NONE) { otLogWarnMle("Failed to get context %d for compressed address from child 0x%04x", entry.GetContextId(), aChild.GetRloc16()); @@ -2064,7 +2051,6 @@ otError MleRouter::HandleChildIdRequest(const Message & aMessage, const Ip6::MessageInfo &aMessageInfo, uint32_t aKeySequence) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; const otThreadLinkInfo *linkInfo = static_cast(aMessageInfo.GetLinkInfo()); Mac::ExtAddress macAddr; @@ -2091,7 +2077,7 @@ otError MleRouter::HandleChildIdRequest(const Message & aMessage, // Find Child aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); - child = GetChildTable().FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); + child = mChildTable.FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); VerifyOrExit(child != NULL, error = OT_ERROR_ALREADY); // Response @@ -2101,9 +2087,9 @@ otError MleRouter::HandleChildIdRequest(const Message & aMessage, error = OT_ERROR_SECURITY); // Remove existing MLE messages - netif.GetMeshForwarder().RemoveMessages(*child, Message::kSubTypeMleGeneral); - netif.GetMeshForwarder().RemoveMessages(*child, Message::kSubTypeMleChildUpdateRequest); - netif.GetMeshForwarder().RemoveMessages(*child, Message::kSubTypeMleDataResponse); + Get().RemoveMessages(*child, Message::kSubTypeMleGeneral); + Get().RemoveMessages(*child, Message::kSubTypeMleChildUpdateRequest); + Get().RemoveMessages(*child, Message::kSubTypeMleDataResponse); // Link-Layer Frame Counter SuccessOrExit(error = Tlv::GetTlv(aMessage, Tlv::kLinkFrameCounter, sizeof(linkFrameCounter), linkFrameCounter)); @@ -2174,7 +2160,7 @@ otError MleRouter::HandleChildIdRequest(const Message & aMessage, child->SetMleFrameCounter(mleFrameCounter.GetFrameCounter()); child->SetKeySequence(aKeySequence); child->SetDeviceMode(mode.GetMode()); - child->GetLinkInfo().AddRss(netif.GetMac().GetNoiseFloor(), linkInfo->mRss); + child->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); child->SetTimeout(timeout.GetTimeout()); if (mode.GetMode() & ModeTlv::kModeFullNetworkData) @@ -2193,12 +2179,12 @@ otError MleRouter::HandleChildIdRequest(const Message & aMessage, child->SetRequestTlv(numTlvs, tlvRequest.GetTlvs()[numTlvs]); } - if (activeTimestamp.GetLength() == 0 || netif.GetActiveDataset().Compare(activeTimestamp) != 0) + if (activeTimestamp.GetLength() == 0 || Get().Compare(activeTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kActiveDataset); } - if (pendingTimestamp.GetLength() == 0 || netif.GetPendingDataset().Compare(pendingTimestamp) != 0) + if (pendingTimestamp.GetLength() == 0 || Get().Compare(pendingTimestamp) != 0) { child->SetRequestTlv(numTlvs++, Tlv::kPendingDataset); } @@ -2252,7 +2238,7 @@ otError MleRouter::HandleChildUpdateRequest(const Message & aMessage, // Find Child aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); - child = GetChildTable().FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); + child = mChildTable.FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); tlvs[tlvslength++] = Tlv::kSourceAddress; @@ -2284,7 +2270,7 @@ otError MleRouter::HandleChildUpdateRequest(const Message & aMessage, if (!(mode.GetMode() & ModeTlv::kModeRxOnWhenIdle) && (child->GetState() == Neighbor::kStateValid)) { - GetNetif().GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*child, true); + Get().SetSrcMatchAsShort(*child, true); } } @@ -2389,7 +2375,7 @@ otError MleRouter::HandleChildUpdateResponse(const Message & aMessage, // Find Child aMessageInfo.GetPeerAddr().ToExtAddress(macAddr); - child = GetChildTable().FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); + child = mChildTable.FindChild(macAddr, ChildTable::kInStateAnyExceptInvalid); if (child == NULL) { @@ -2477,7 +2463,7 @@ otError MleRouter::HandleChildUpdateResponse(const Message & aMessage, SetChildStateToValid(*child); child->SetLastHeard(TimerMilli::GetNow()); child->SetKeySequence(aKeySequence); - child->GetLinkInfo().AddRss(GetNetif().GetMac().GetNoiseFloor(), linkInfo->mRss); + child->GetLinkInfo().AddRss(Get().GetNoiseFloor(), linkInfo->mRss); exit: return error; @@ -2485,7 +2471,6 @@ exit: otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; TlvRequestTlv tlvRequest; ActiveTimestampTlv activeTimestamp; @@ -2519,12 +2504,12 @@ otError MleRouter::HandleDataRequest(const Message &aMessage, const Ip6::Message memcpy(tlvs, tlvRequest.GetTlvs(), tlvRequest.GetLength()); numTlvs = tlvRequest.GetLength(); - if (activeTimestamp.GetLength() == 0 || netif.GetActiveDataset().Compare(activeTimestamp)) + if (activeTimestamp.GetLength() == 0 || Get().Compare(activeTimestamp)) { tlvs[numTlvs++] = Tlv::kActiveDataset; } - if (pendingTimestamp.GetLength() == 0 || netif.GetPendingDataset().Compare(pendingTimestamp)) + if (pendingTimestamp.GetLength() == 0 || Get().Compare(pendingTimestamp)) { tlvs[numTlvs++] = Tlv::kPendingDataset; } @@ -2558,8 +2543,6 @@ exit: void MleRouter::SynchronizeChildNetworkData(void) { - ThreadNetif &netif = GetNetif(); - VerifyOrExit(mRole == OT_DEVICE_ROLE_ROUTER || mRole == OT_DEVICE_ROLE_LEADER); for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateValid); !iter.IsDone(); iter++) @@ -2574,11 +2557,11 @@ void MleRouter::SynchronizeChildNetworkData(void) if (child.IsFullNetworkData()) { - version = netif.GetNetworkDataLeader().GetVersion(); + version = Get().GetVersion(); } else { - version = netif.GetNetworkDataLeader().GetStableVersion(); + version = Get().GetStableVersion(); } if (child.GetNetworkDataVersion() == version) @@ -2632,7 +2615,6 @@ otError MleRouter::SetSteeringData(const Mac::ExtAddress *aExtAddress) otError MleRouter::HandleDiscoveryRequest(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Tlv tlv; MeshCoP::Tlv meshcopTlv; @@ -2674,7 +2656,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(netif.GetNetworkDataLeader().IsJoiningEnabled()); + VerifyOrExit(Get().IsJoiningEnabled()); } } @@ -2683,7 +2665,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(&netif.GetMac().GetExtendedPanId(), &extPanId.GetExtendedPanId(), OT_EXT_PAN_ID_SIZE)); + VerifyOrExit(memcmp(&Get().GetExtendedPanId(), &extPanId.GetExtendedPanId(), OT_EXT_PAN_ID_SIZE)); break; @@ -2708,7 +2690,6 @@ exit: otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint16_t aPanId) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Message * message; uint16_t startOffset; @@ -2735,7 +2716,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 discoveryResponse.Init(); discoveryResponse.SetVersion(kThreadVersion); - if (netif.GetKeyManager().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) + if (Get().GetSecurityPolicyFlags() & OT_SECURITY_POLICY_NATIVE_COMMISSIONING) { MeshCoP::CommissionerUdpPortTlv commissionerUdpPort; @@ -2754,12 +2735,12 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 // Extended PAN ID TLV extPanId.Init(); - extPanId.SetExtendedPanId(netif.GetMac().GetExtendedPanId()); + extPanId.SetExtendedPanId(Get().GetExtendedPanId()); SuccessOrExit(error = message->Append(&extPanId, sizeof(extPanId))); // Network Name TLV networkName.Init(); - networkName.SetNetworkName(netif.GetMac().GetNetworkName()); + networkName.SetNetworkName(Get().GetNetworkName()); SuccessOrExit(error = message->Append(&networkName, sizeof(tlv) + networkName.GetLength())); #if OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB @@ -2774,7 +2755,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 #endif // OPENTHREAD_CONFIG_ENABLE_STEERING_DATA_SET_OOB { // Steering Data TLV - steeringData = netif.GetNetworkDataLeader().GetCommissioningDataSubTlv(MeshCoP::Tlv::kSteeringData); + steeringData = Get().GetCommissioningDataSubTlv(MeshCoP::Tlv::kSteeringData); if (steeringData != NULL) { @@ -2784,7 +2765,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1 // Joiner UDP Port TLV joinerUdpPort.Init(); - joinerUdpPort.SetUdpPort(netif.GetJoinerRouter().GetJoinerUdpPort()); + joinerUdpPort.SetUdpPort(Get().GetJoinerUdpPort()); SuccessOrExit(error = message->Append(&joinerUdpPort, sizeof(tlv) + joinerUdpPort.GetLength())); tlv.SetLength(static_cast(message->GetLength() - startOffset)); @@ -2808,7 +2789,6 @@ exit: otError MleRouter::SendChildIdResponse(Child &aChild) { - ThreadNetif &netif = GetNetif(); otError error = OT_ERROR_NONE; Ip6::Address destination; Message * message; @@ -2834,9 +2814,9 @@ otError MleRouter::SendChildIdResponse(Child &aChild) mNextChildId = kMinChildId; } - rloc16 = netif.GetMac().GetShortAddress() | mNextChildId; + rloc16 = Get().GetShortAddress() | mNextChildId; - } while (GetChildTable().FindChild(rloc16, ChildTable::kInStateAnyExceptInvalid) != NULL); + } while (mChildTable.FindChild(rloc16, ChildTable::kInStateAnyExceptInvalid) != NULL); // allocate Child ID aChild.SetRloc16(rloc16); @@ -2878,7 +2858,7 @@ otError MleRouter::SendChildIdResponse(Child &aChild) if (!aChild.IsRxOnWhenIdle()) { - netif.GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(aChild, false); + Get().SetSrcMatchAsShort(aChild, false); } #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC @@ -2908,16 +2888,15 @@ 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 = netif.GetMle().GetChildTable().GetChildIndex(aChild); + uint8_t childIndex = Get().GetChildIndex(aChild); - for (message = netif.GetMeshForwarder().GetSendQueue().GetHead(); message; message = message->GetNext()) + for (message = Get().GetSendQueue().GetHead(); message; message = message->GetNext()) { if (message->GetChildMask(childIndex) && message->GetSubType() == Message::kSubTypeMleChildUpdateRequest) { @@ -2929,7 +2908,7 @@ otError MleRouter::SendChildUpdateRequest(Child &aChild) } // Remove queued outdated "Child Update Request" when there is newer Network Data is to send. - netif.GetMeshForwarder().RemoveMessages(aChild, Message::kSubTypeMleChildUpdateRequest); + Get().RemoveMessages(aChild, Message::kSubTypeMleChildUpdateRequest); break; } } @@ -3100,7 +3079,7 @@ otError MleRouter::SendDataResponse(const Ip6::Address &aDestination, if (aDelay) { // Remove MLE Data Responses from Send Message Queue. - GetNetif().GetMeshForwarder().RemoveDataResponseMessages(); + Get().RemoveDataResponseMessages(); // Remove multicast MLE Data Response from Delayed Message Queue. RemoveDelayedDataResponseMessage(); @@ -3126,14 +3105,13 @@ exit: bool MleRouter::IsMinimalChild(uint16_t aRloc16) { - ThreadNetif &netif = GetNetif(); - bool rval = false; + bool rval = false; - if (GetRouterId(aRloc16) == GetRouterId(netif.GetMac().GetShortAddress())) + if (GetRouterId(aRloc16) == GetRouterId(Get().GetShortAddress())) { Neighbor *neighbor; - neighbor = netif.GetMle().GetNeighbor(aRloc16); + neighbor = GetNeighbor(aRloc16); rval = (neighbor != NULL) && (!neighbor->IsFullThreadDevice()); } @@ -3155,8 +3133,6 @@ exit: void MleRouter::RemoveNeighbor(Neighbor &aNeighbor) { - ThreadNetif &netif = GetNetif(); - switch (mRole) { case OT_DEVICE_ROLE_DISABLED: @@ -3182,13 +3158,13 @@ void MleRouter::RemoveNeighbor(Neighbor &aNeighbor) aNeighbor.SetState(Neighbor::kStateInvalid); - netif.GetMeshForwarder().ClearChildIndirectMessages(static_cast(aNeighbor)); - netif.GetNetworkDataLeader().SendServerDataNotification(aNeighbor.GetRloc16()); + Get().ClearChildIndirectMessages(static_cast(aNeighbor)); + Get().SendServerDataNotification(aNeighbor.GetRloc16()); if (aNeighbor.GetDeviceMode() & ModeTlv::kModeFullThreadDevice) { // Clear all EID-to-RLOC entries associated with the child. - netif.GetAddressResolver().Remove(aNeighbor.GetRloc16()); + Get().Remove(aNeighbor.GetRloc16()); } RemoveStoredChild(aNeighbor.GetRloc16()); @@ -3226,7 +3202,7 @@ Neighbor *MleRouter::GetNeighbor(uint16_t aAddress) case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - rval = GetChildTable().FindChild(aAddress, ChildTable::kInStateValidOrRestoring); + rval = mChildTable.FindChild(aAddress, ChildTable::kInStateValidOrRestoring); VerifyOrExit(rval == NULL); rval = mRouterTable.GetNeighbor(aAddress); @@ -3253,7 +3229,7 @@ Neighbor *MleRouter::GetNeighbor(const Mac::ExtAddress &aAddress) case OT_DEVICE_ROLE_ROUTER: case OT_DEVICE_ROLE_LEADER: - rval = GetChildTable().FindChild(aAddress, ChildTable::kInStateValidOrRestoring); + rval = mChildTable.FindChild(aAddress, ChildTable::kInStateValidOrRestoring); VerifyOrExit(rval == NULL); rval = mRouterTable.GetNeighbor(aAddress); @@ -3318,7 +3294,7 @@ Neighbor *MleRouter::GetNeighbor(const Ip6::Address &aAddress) ExitNow(rval = GetNeighbor(macAddr)); } - if (GetNetif().GetNetworkDataLeader().GetContext(aAddress, context) != OT_ERROR_NONE) + if (Get().GetContext(aAddress, context) != OT_ERROR_NONE) { context.mContextId = 0xff; } @@ -3482,8 +3458,8 @@ otError MleRouter::GetChildInfoById(uint16_t aChildId, otChildInfo &aChildInfo) aChildId = GetChildId(aChildId); } - rloc16 = GetNetif().GetMac().GetShortAddress() | aChildId; - child = GetChildTable().FindChild(rloc16, ChildTable::kInStateAnyExceptInvalid); + rloc16 = Get().GetShortAddress() | aChildId; + child = mChildTable.FindChild(rloc16, ChildTable::kInStateAnyExceptInvalid); VerifyOrExit(child != NULL, error = OT_ERROR_NOT_FOUND); error = GetChildInfo(*child, aChildInfo); @@ -3497,7 +3473,7 @@ otError MleRouter::GetChildInfoByIndex(uint8_t aChildIndex, otChildInfo &aChildI otError error = OT_ERROR_NONE; Child * child = NULL; - child = GetChildTable().GetChildAtIndex(aChildIndex); + child = mChildTable.GetChildAtIndex(aChildIndex); VerifyOrExit(child != NULL, error = OT_ERROR_NOT_FOUND); error = GetChildInfo(*child, aChildInfo); @@ -3513,7 +3489,7 @@ otError MleRouter::GetChildNextIp6Address(uint8_t aChildIndex otError error = OT_ERROR_NONE; Child * child = NULL; - child = GetChildTable().GetChildAtIndex(aChildIndex); + child = mChildTable.GetChildAtIndex(aChildIndex); VerifyOrExit(child != NULL, error = OT_ERROR_INVALID_ARGS); VerifyOrExit(child->IsStateValidOrRestoring(), error = OT_ERROR_INVALID_ARGS); @@ -3534,12 +3510,12 @@ void MleRouter::RestoreChildren(void) Child * child; const Settings::ChildInfo &childInfo = iter.GetChildInfo(); - child = GetChildTable().FindChild(*static_cast(&childInfo.mExtAddress), - ChildTable::kInStateAnyExceptInvalid); + child = mChildTable.FindChild(*static_cast(&childInfo.mExtAddress), + ChildTable::kInStateAnyExceptInvalid); if (child == NULL) { - VerifyOrExit((child = GetChildTable().GetNewChild()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((child = mChildTable.GetNewChild()) != NULL, error = OT_ERROR_NO_BUFS); } else { @@ -3555,13 +3531,13 @@ void MleRouter::RestoreChildren(void) child->SetDeviceMode(childInfo.mMode); child->SetState(Neighbor::kStateRestored); child->SetLastHeard(TimerMilli::GetNow()); - GetNetif().GetMeshForwarder().GetSourceMatchController().SetSrcMatchAsShort(*child, true); + Get().SetSrcMatchAsShort(*child, true); numChildren++; } exit: - if (foundDuplicate || (numChildren > GetChildTable().GetMaxChildren()) || (error != OT_ERROR_NONE)) + if (foundDuplicate || (numChildren > mChildTable.GetMaxChildren()) || (error != OT_ERROR_NONE)) { // If there is any error, e.g., there are more saved children // in non-volatile settings than could be restored or there are @@ -3602,14 +3578,14 @@ otError MleRouter::StoreChild(const Child &aChild) childInfo.mRloc16 = aChild.GetRloc16(); childInfo.mMode = aChild.GetDeviceMode(); - return GetInstance().GetSettings().AddChildInfo(childInfo); + return Get().AddChildInfo(childInfo); } otError MleRouter::RefreshStoredChildren(void) { otError error = OT_ERROR_NONE; - SuccessOrExit(error = GetInstance().GetSettings().DeleteChildInfo()); + SuccessOrExit(error = Get().DeleteChildInfo()); for (ChildTable::Iterator iter(GetInstance(), ChildTable::kInStateAnyExceptInvalid); !iter.IsDone(); iter++) { @@ -3666,7 +3642,7 @@ otError MleRouter::GetNextNeighborInfo(otNeighborInfoIterator &aIterator, otNeig { for (index = aIterator;; index++) { - Child *child = GetChildTable().GetChildAtIndex(static_cast(index)); + Child *child = mChildTable.GetChildAtIndex(static_cast(index)); if (child == NULL) { @@ -3753,7 +3729,6 @@ exit: otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, Ip6::Header &aIp6Header) { - ThreadNetif & netif = GetNetif(); Ip6::MessageInfo messageInfo; otError error = OT_ERROR_NONE; @@ -3763,10 +3738,10 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I ExitNow(); } - if (aMeshDest == netif.GetMac().GetShortAddress()) + if (aMeshDest == Get().GetShortAddress()) { // mesh destination is this device - if (netif.IsUnicastAddress(aIp6Header.GetDestination())) + if (Get().IsUnicastAddress(aIp6Header.GetDestination())) { // IPv6 destination is this device ExitNow(); @@ -3780,7 +3755,7 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I else if (GetRouterId(aMeshDest) == mRouterId) { // mesh destination is a child of this device - if (GetChildTable().FindChild(aMeshDest, ChildTable::kInStateValidOrRestoring)) + if (mChildTable.FindChild(aMeshDest, ChildTable::kInStateValidOrRestoring)) { ExitNow(); } @@ -3793,10 +3768,10 @@ otError MleRouter::CheckReachability(uint16_t aMeshSource, uint16_t aMeshDest, I messageInfo.GetPeerAddr() = GetMeshLocal16(); messageInfo.GetPeerAddr().mFields.m16[7] = HostSwap16(aMeshSource); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - netif.GetIp6().GetIcmp().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, - messageInfo, aIp6Header); + Get().SendError(Ip6::IcmpHeader::kTypeDstUnreach, Ip6::IcmpHeader::kCodeDstUnreachNoRoute, messageInfo, + aIp6Header); error = OT_ERROR_DROP; @@ -3806,7 +3781,6 @@ exit: otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ThreadExtMacAddressTlv macAddr64Tlv; ThreadRloc16Tlv rlocTlv; @@ -3816,7 +3790,7 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) VerifyOrExit(mAddressSolicitPending == false); - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -3824,7 +3798,7 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) message->SetPayloadMarker(); macAddr64Tlv.Init(); - macAddr64Tlv.SetMacAddr(netif.GetMac().GetExtAddress()); + macAddr64Tlv.SetMacAddr(Get().GetExtAddress()); SuccessOrExit(error = message->Append(&macAddr64Tlv, sizeof(macAddr64Tlv))); if (IsRouterIdValid(mPreviousRouterId)) @@ -3847,7 +3821,7 @@ otError MleRouter::SendAddressSolicit(ThreadStatusTlv::Status aStatus) messageInfo.SetPeerPort(kCoapUdpPort); SuccessOrExit( - error = netif.GetCoap().SendMessage(*message, messageInfo, &MleRouter::HandleAddressSolicitResponse, this)); + error = Get().SendMessage(*message, messageInfo, &MleRouter::HandleAddressSolicitResponse, this)); mAddressSolicitPending = true; LogMleMessage("Send Address Solicit", messageInfo.GetPeerAddr()); @@ -3864,14 +3838,13 @@ exit: otError MleRouter::SendAddressRelease(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ThreadRloc16Tlv rlocTlv; ThreadExtMacAddressTlv macAddr64Tlv; Ip6::MessageInfo messageInfo; Coap::Message * message; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -3883,13 +3856,13 @@ otError MleRouter::SendAddressRelease(void) SuccessOrExit(error = message->Append(&rlocTlv, sizeof(rlocTlv))); macAddr64Tlv.Init(); - macAddr64Tlv.SetMacAddr(netif.GetMac().GetExtAddress()); + macAddr64Tlv.SetMacAddr(Get().GetExtAddress()); SuccessOrExit(error = message->Append(&macAddr64Tlv, sizeof(macAddr64Tlv))); messageInfo.SetSockAddr(GetMeshLocal16()); SuccessOrExit(error = GetLeaderAddress(messageInfo.GetPeerAddr())); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); LogMleMessage("Send Address Release", messageInfo.GetPeerAddr()); @@ -3978,7 +3951,7 @@ void MleRouter::HandleAddressSolicitResponse(Coap::Message * aMessage, router = mRouterTable.GetRouter(routerId); VerifyOrExit(router != NULL); - router->SetExtAddress(GetNetif().GetMac().GetExtAddress()); + router->SetExtAddress(Get().GetExtAddress()); router->SetCost(0); router = mRouterTable.GetRouter(mParent.GetRouterId()); @@ -4045,7 +4018,7 @@ void MleRouter::HandleAddressSolicit(Coap::Message &aMessage, const Ip6::Message #if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC // In a time sync enabled network, all routers' xtal accuracy must be less than the threshold. if (Tlv::GetTlv(aMessage, Tlv::kXtalAccuracy, sizeof(xtalAccuracyTlv), xtalAccuracyTlv) != OT_ERROR_NONE || - xtalAccuracyTlv.GetXtalAccuracy() > GetNetif().GetTimeSync().GetXtalThreshold()) + xtalAccuracyTlv.GetXtalAccuracy() > Get().GetXtalThreshold()) { ExitNow(router = NULL); } @@ -4112,14 +4085,13 @@ void MleRouter::SendAddressSolicitResponse(const Coap::Message & aRequest, const Router * aRouter, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; ThreadStatusTlv statusTlv; ThreadRouterMaskTlv routerMaskTlv; ThreadRloc16Tlv rlocTlv; Coap::Message * message; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -4149,7 +4121,7 @@ void MleRouter::SendAddressSolicitResponse(const Coap::Message & aRequest, SuccessOrExit(error = message->Append(&routerMaskTlv, sizeof(routerMaskTlv))); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); LogMleMessage("Send Address Reply", aMessageInfo.GetPeerAddr()); @@ -4191,7 +4163,7 @@ void MleRouter::HandleAddressRelease(Coap::Message &aMessage, const Ip6::Message mRouterTable.Release(routerId); - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); LogMleMessage("Send Address Release Reply", aMessageInfo.GetPeerAddr()); @@ -4211,8 +4183,8 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) } else { - uint8_t numChildren = GetChildTable().GetNumChildren(ChildTable::kInStateValid); - uint8_t maxAllowed = GetChildTable().GetMaxChildrenAllowed(); + uint8_t numChildren = mChildTable.GetNumChildren(ChildTable::kInStateValid); + uint8_t maxAllowed = mChildTable.GetMaxChildrenAllowed(); if ((maxAllowed - numChildren) < (maxAllowed / 3)) { @@ -4285,7 +4257,7 @@ void MleRouter::FillConnectivityTlv(ConnectivityTlv &aTlv) Router &router = *iter.GetRouter(); uint8_t linkQuality; - if (router.GetRloc16() == GetNetif().GetMle().GetRloc16()) + if (router.GetRloc16() == GetRloc16()) { // skip self continue; @@ -4341,7 +4313,6 @@ exit: otError MleRouter::AppendChildAddresses(Message &aMessage, Child &aChild) { - ThreadNetif & netif = GetNetif(); otError error; Ip6::Address address; Child::Ip6AddressIterator iterator; @@ -4356,7 +4327,7 @@ otError MleRouter::AppendChildAddresses(Message &aMessage, Child &aChild) while (aChild.GetNextIp6Address(GetInstance(), iterator, address) == OT_ERROR_NONE) { - if (address.IsMulticast() || netif.GetNetworkDataLeader().GetContext(address, context) != OT_ERROR_NONE) + if (address.IsMulticast() || Get().GetContext(address, context) != OT_ERROR_NONE) { // uncompressed entry entry.SetUncompressed(); @@ -4405,7 +4376,7 @@ void MleRouter::FillRouteTlv(RouteTlv &aTlv) aTlv.SetRouterId(router.GetRouterId()); - if (router.GetRloc16() == GetNetif().GetMle().GetRloc16()) + if (router.GetRloc16() == GetRloc16()) { aTlv.SetLinkQualityIn(routerCount, 0); aTlv.SetLinkQualityOut(routerCount, 0); @@ -4463,12 +4434,12 @@ exit: otError MleRouter::AppendActiveDataset(Message &aMessage) { - return GetNetif().GetActiveDataset().AppendMleDatasetTlv(aMessage); + return Get().AppendMleDatasetTlv(aMessage); } otError MleRouter::AppendPendingDataset(Message &aMessage) { - return GetNetif().GetPendingDataset().AppendMleDatasetTlv(aMessage); + return Get().AppendMleDatasetTlv(aMessage); } bool MleRouter::HasMinDowngradeNeighborRouters(void) @@ -4586,7 +4557,7 @@ exit: bool MleRouter::HasChildren(void) { - return GetChildTable().HasChildren(ChildTable::kInStateValidOrAttaching); + return mChildTable.HasChildren(ChildTable::kInStateValidOrAttaching); } void MleRouter::RemoveChildren(void) @@ -4604,7 +4575,7 @@ bool MleRouter::HasSmallNumberOfChildren(void) VerifyOrExit(routerCount > mRouterDowngradeThreshold); - numChildren = GetChildTable().GetNumChildren(ChildTable::kInStateValid); + numChildren = mChildTable.GetNumChildren(ChildTable::kInStateValid); return numChildren < (routerCount - mRouterDowngradeThreshold) * 3; @@ -4668,11 +4639,11 @@ void MleRouter::SignalChildUpdated(otThreadChildTableEvent aEvent, Child &aChild switch (aEvent) { case OT_THREAD_CHILD_TABLE_EVENT_CHILD_ADDED: - GetNotifier().Signal(OT_CHANGED_THREAD_CHILD_ADDED); + Get().Signal(OT_CHANGED_THREAD_CHILD_ADDED); break; case OT_THREAD_CHILD_TABLE_EVENT_CHILD_REMOVED: - GetNotifier().Signal(OT_CHANGED_THREAD_CHILD_REMOVED); + Get().Signal(OT_CHANGED_THREAD_CHILD_REMOVED); break; } } @@ -4711,7 +4682,7 @@ void MleRouter::HandleTimeSync(const Message &aMessage, const Ip6::MessageInfo & { LogMleMessage("Receive Time Sync", aMessageInfo.GetPeerAddr()); - GetNetif().GetTimeSync().HandleTimeSyncMessage(aMessage); + Get().HandleTimeSyncMessage(aMessage); } otError MleRouter::SendTimeSync(void) diff --git a/src/core/thread/mle_router_ftd.hpp b/src/core/thread/mle_router_ftd.hpp index 26a248717..5dfe611a3 100644 --- a/src/core/thread/mle_router_ftd.hpp +++ b/src/core/thread/mle_router_ftd.hpp @@ -74,6 +74,7 @@ namespace Mle { class MleRouter : public Mle { friend class Mle; + friend class ot::Instance; public: /** @@ -334,14 +335,6 @@ public: */ void RemoveNeighbor(Neighbor &aNeighbor); - /** - * This method gets the `ChildTable` object. - * - * @returns A reference to the `ChildTable`. - * - */ - ChildTable &GetChildTable(void) { return mChildTable; } - /** * This method restores children information from non-volatile memory. * @@ -651,12 +644,6 @@ public: */ void ResetAdvertiseInterval(void); - /** - * This method returns a reference to the router table object. - * - */ - RouterTable &GetRouterTable(void) { return mRouterTable; } - /** * This static method converts link quality to route cost. * diff --git a/src/core/thread/mle_router_mtd.hpp b/src/core/thread/mle_router_mtd.hpp index 450bb6ad6..2523eec98 100644 --- a/src/core/thread/mle_router_mtd.hpp +++ b/src/core/thread/mle_router_mtd.hpp @@ -50,6 +50,7 @@ namespace Mle { class MleRouter : public Mle { friend class Mle; + friend class ot::Instance; public: explicit MleRouter(Instance &aInstance) @@ -83,9 +84,6 @@ public: otError RemoveNeighbor(const Mac::Address &) { return BecomeDetached(); } otError RemoveNeighbor(Neighbor &) { return BecomeDetached(); } - ChildTable & GetChildTable(void) { return mChildTable; } - RouterTable &GetRouterTable(void) { return mRouterTable; } - bool IsMinimalChild(uint16_t) { return false; } void RestoreChildren(void) {} diff --git a/src/core/thread/network_data.cpp b/src/core/thread/network_data.cpp index cc43017fc..df4f525a5 100644 --- a/src/core/thread/network_data.cpp +++ b/src/core/thread/network_data.cpp @@ -41,6 +41,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "mac/mac_frame.hpp" #include "thread/thread_netif.hpp" @@ -219,7 +220,7 @@ otError NetworkData::GetNextExternalRoute(otNetworkDataIterator *aIterator, aConfig->mPreference = hasRouteEntry->GetPreference(); aConfig->mStable = hasRoute->IsStable(); aConfig->mRloc16 = hasRouteEntry->GetRloc(); - aConfig->mNextHopIsThisDevice = (hasRouteEntry->GetRloc() == GetNetif().GetMle().GetRloc16()); + aConfig->mNextHopIsThisDevice = (hasRouteEntry->GetRloc() == Get().GetRloc16()); iterator.SaveTlvOffset(cur, mTlvs); iterator.SaveSubTlvOffset(subCur, prefix->GetSubTlvs()); @@ -995,7 +996,6 @@ void NetworkData::Remove(uint8_t *aStart, uint8_t aLength) otError NetworkData::SendServerDataNotification(uint16_t aRloc16) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; @@ -1003,7 +1003,7 @@ otError NetworkData::SendServerDataNotification(uint16_t aRloc16) VerifyOrExit(!mLastAttemptWait || static_cast(TimerMilli::GetNow() - mLastAttempt) < kDataResubmitDelay, error = OT_ERROR_ALREADY); - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -1027,10 +1027,10 @@ otError NetworkData::SendServerDataNotification(uint16_t aRloc16) SuccessOrExit(error = message->Append(&rloc16Tlv, sizeof(rloc16Tlv))); } - netif.GetMle().GetLeaderAloc(messageInfo.GetPeerAddr()); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + Get().GetLeaderAloc(messageInfo.GetPeerAddr()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); if (mType == kTypeLocal) { diff --git a/src/core/thread/network_data_leader.cpp b/src/core/thread/network_data_leader.cpp index eb2833997..1765a1558 100644 --- a/src/core/thread/network_data_leader.cpp +++ b/src/core/thread/network_data_leader.cpp @@ -42,6 +42,7 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" #include "common/timer.hpp" @@ -66,20 +67,19 @@ void LeaderBase::Reset(void) mVersion = static_cast(otPlatRandomGet()); mStableVersion = static_cast(otPlatRandomGet()); mLength = 0; - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); } otError LeaderBase::GetContext(const Ip6::Address &aAddress, Lowpan::Context &aContext) { - ThreadNetif &netif = GetNetif(); - PrefixTlv * prefix; - ContextTlv * contextTlv; + PrefixTlv * prefix; + ContextTlv *contextTlv; aContext.mPrefixLength = 0; - if (PrefixMatch(netif.GetMle().GetMeshLocalPrefix().m8, aAddress.mFields.m8, 64) >= 0) + if (PrefixMatch(Get().GetMeshLocalPrefix().m8, aAddress.mFields.m8, 64) >= 0) { - aContext.mPrefix = netif.GetMle().GetMeshLocalPrefix().m8; + aContext.mPrefix = Get().GetMeshLocalPrefix().m8; aContext.mPrefixLength = 64; aContext.mContextId = Mle::kMeshLocalPrefixContextId; aContext.mCompressFlag = true; @@ -127,7 +127,7 @@ otError LeaderBase::GetContext(uint8_t aContextId, Lowpan::Context &aContext) if (aContextId == Mle::kMeshLocalPrefixContextId) { - aContext.mPrefix = GetNetif().GetMle().GetMeshLocalPrefix().m8; + aContext.mPrefix = Get().GetMeshLocalPrefix().m8; aContext.mPrefixLength = 64; aContext.mContextId = Mle::kMeshLocalPrefixContextId; aContext.mCompressFlag = true; @@ -198,7 +198,7 @@ bool LeaderBase::IsOnMesh(const Ip6::Address &aAddress) PrefixTlv *prefix; bool rval = false; - if (memcmp(aAddress.mFields.m8, GetNetif().GetMle().GetMeshLocalPrefix().m8, sizeof(otMeshLocalPrefix)) == 0) + if (memcmp(aAddress.mFields.m8, Get().GetMeshLocalPrefix().m8, sizeof(otMeshLocalPrefix)) == 0) { ExitNow(rval = true); } @@ -276,7 +276,6 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, uint8_t * aPrefixMatch, uint16_t * aRloc16) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NO_ROUTE; PrefixTlv * prefix; HasRouteTlv * hasRoute; @@ -322,9 +321,10 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, if (rvalRoute == NULL || entry->GetPreference() > rvalRoute->GetPreference() || (entry->GetPreference() == rvalRoute->GetPreference() && - (entry->GetRloc() == netif.GetMle().GetRloc16() || - (rvalRoute->GetRloc() != netif.GetMle().GetRloc16() && - netif.GetMle().GetCost(entry->GetRloc()) < netif.GetMle().GetCost(rvalRoute->GetRloc()))))) + (entry->GetRloc() == Get().GetRloc16() || + (rvalRoute->GetRloc() != Get().GetRloc16() && + Get().GetCost(entry->GetRloc()) < + Get().GetCost(rvalRoute->GetRloc()))))) { rvalRoute = entry; rval_plen = static_cast(plen); @@ -354,7 +354,6 @@ otError LeaderBase::ExternalRouteLookup(uint8_t aDomainId, otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NO_ROUTE; BorderRouterTlv * borderRouter; BorderRouterEntry *entry; @@ -380,9 +379,9 @@ otError LeaderBase::DefaultRouteLookup(PrefixTlv &aPrefix, uint16_t *aRloc16) if (route == NULL || entry->GetPreference() > route->GetPreference() || (entry->GetPreference() == route->GetPreference() && - (entry->GetRloc() == netif.GetMle().GetRloc16() || - (route->GetRloc() != netif.GetMle().GetRloc16() && - netif.GetMle().GetCost(entry->GetRloc()) < netif.GetMle().GetCost(route->GetRloc()))))) + (entry->GetRloc() == Get().GetRloc16() || + (route->GetRloc() != Get().GetRloc16() && + Get().GetCost(entry->GetRloc()) < Get().GetCost(route->GetRloc()))))) { route = entry; } @@ -429,15 +428,15 @@ otError LeaderBase::SetNetworkData(uint8_t aVersion, #if OPENTHREAD_FTD // Synchronize internal 6LoWPAN Context ID Set with recently obtained Network Data. - if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { - GetNetif().GetNetworkDataLeader().UpdateContextsAfterReset(); + Get().UpdateContextsAfterReset(); } #endif otDumpDebgNetData("set network data", mTlvs, mLength); - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); exit: return error; @@ -463,7 +462,7 @@ otError LeaderBase::SetCommissioningData(const uint8_t *aValue, uint8_t aValueLe } mVersion++; - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(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 9b9102d80..b8687e858 100644 --- a/src/core/thread/network_data_leader_ftd.cpp +++ b/src/core/thread/network_data_leader_ftd.cpp @@ -44,9 +44,9 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/message.hpp" -#include "common/owner-locator.hpp" #include "common/timer.hpp" #include "mac/mac_frame.hpp" #include "meshcop/meshcop.hpp" @@ -82,34 +82,30 @@ void Leader::Reset(void) void Leader::Start(void) { - Coap::Coap &coap = GetNetif().GetCoap(); - - coap.AddResource(mServerData); - coap.AddResource(mCommissioningDataGet); - coap.AddResource(mCommissioningDataSet); + Get().AddResource(mServerData); + Get().AddResource(mCommissioningDataGet); + Get().AddResource(mCommissioningDataSet); } void Leader::Stop(void) { - Coap::Coap &coap = GetNetif().GetCoap(); - - coap.RemoveResource(mServerData); - coap.RemoveResource(mCommissioningDataGet); - coap.RemoveResource(mCommissioningDataSet); + Get().RemoveResource(mServerData); + Get().RemoveResource(mCommissioningDataGet); + Get().RemoveResource(mCommissioningDataSet); } void Leader::IncrementVersion(void) { - if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { mVersion++; - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); } } void Leader::IncrementStableVersion(void) { - if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { mStableVersion++; } @@ -141,7 +137,7 @@ void Leader::RemoveBorderRouter(uint16_t aRloc16, MatchMode aMatchMode) mStableVersion++; } - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); exit: return; @@ -173,7 +169,7 @@ void Leader::HandleServerData(Coap::Message &aMessage, const Ip6::MessageInfo &a networkData.GetLength()); } - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoNetData("Sent network data registration acknowledgment"); @@ -201,7 +197,7 @@ void Leader::HandleCommissioningSet(Coap::Message &aMessage, const Ip6::MessageI MeshCoP::Tlv *end; VerifyOrExit(length <= sizeof(tlvs)); - VerifyOrExit(GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER); + VerifyOrExit(Get().GetRole() == OT_DEVICE_ROLE_LEADER); aMessage.Read(offset, length, tlvs); @@ -280,7 +276,7 @@ void Leader::HandleCommissioningSet(Coap::Message &aMessage, const Ip6::MessageI exit: - if (GetNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER) { SendCommissioningSetResponse(aMessage, aMessageInfo, state); } @@ -321,14 +317,13 @@ void Leader::SendCommissioningGetResponse(const Coap::Message & aRequest, const uint8_t * aTlvs, uint8_t aLength) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message *message; uint8_t index; uint8_t * data = NULL; uint8_t length = 0; - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -372,7 +367,7 @@ void Leader::SendCommissioningGetResponse(const Coap::Message & aRequest, message->SetLength(message->GetLength() - 1); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent commissioning dataset get response"); @@ -388,12 +383,11 @@ void Leader::SendCommissioningSetResponse(const Coap::Message & aRequest, const Ip6::MessageInfo & aMessageInfo, MeshCoP::StateTlv::State aState) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message; MeshCoP::StateTlv state; - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aRequest); message->SetPayloadMarker(); @@ -402,7 +396,7 @@ void Leader::SendCommissioningSetResponse(const Coap::Message & aRequest, state.SetState(aState); SuccessOrExit(error = message->Append(&state, sizeof(state))); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, aMessageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, aMessageInfo)); otLogInfoMeshCoP("sent commissioning dataset set response"); @@ -792,7 +786,7 @@ otError Leader::RegisterNetworkData(uint16_t aRloc16, uint8_t *aTlvs, uint8_t aT } } - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); exit: return error; @@ -1201,7 +1195,7 @@ void Leader::FreeContext(uint8_t aContextId) mContextUsed &= ~(1 << aContextId); mVersion++; mStableVersion++; - GetNotifier().Signal(OT_CHANGED_THREAD_NETDATA); + Get().Signal(OT_CHANGED_THREAD_NETDATA); } void Leader::StartContextReuseTimer(uint8_t aContextId) diff --git a/src/core/thread/network_data_local.cpp b/src/core/thread/network_data_local.cpp index 1eafa2801..dda16e48f 100644 --- a/src/core/thread/network_data_local.cpp +++ b/src/core/thread/network_data_local.cpp @@ -36,6 +36,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "mac/mac_frame.hpp" #include "thread/thread_netif.hpp" @@ -65,7 +66,7 @@ otError Local::AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, in (aPrf == OT_ROUTE_PREFERENCE_HIGH), error = OT_ERROR_INVALID_ARGS); - VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, GetNetif().GetMle().GetMeshLocalPrefix().m8, prefixLengthBytes) < + VerifyOrExit(Ip6::Address::PrefixMatch(aPrefix, Get().GetMeshLocalPrefix().m8, prefixLengthBytes) < Ip6::Address::kMeshLocalPrefixLength, error = OT_ERROR_INVALID_ARGS); @@ -214,7 +215,7 @@ otError Local::AddService(uint32_t aEnterpriseNumber, serverTlv->SetStable(); } - serverTlv->SetServer16(GetNetif().GetMle().GetRloc16()); + serverTlv->SetServer16(Get().GetRloc16()); serverTlv->SetServerData(aServerData, aServerDataLength); ClearResubmitDelayTimer(); @@ -292,13 +293,13 @@ void Local::UpdateRloc(PrefixTlv &aPrefix) void Local::UpdateRloc(HasRouteTlv &aHasRoute) { HasRouteEntry *entry = aHasRoute.GetEntry(0); - entry->SetRloc(GetNetif().GetMle().GetRloc16()); + entry->SetRloc(Get().GetRloc16()); } void Local::UpdateRloc(BorderRouterTlv &aBorderRouter) { BorderRouterEntry *entry = aBorderRouter.GetEntry(0); - entry->SetRloc(GetNetif().GetMle().GetRloc16()); + entry->SetRloc(Get().GetRloc16()); } #if OPENTHREAD_ENABLE_SERVICE @@ -321,48 +322,41 @@ void Local::UpdateRloc(ServiceTlv &aService) void Local::UpdateRloc(ServerTlv &aServer) { - aServer.SetServer16(GetNetif().GetMle().GetRloc16()); + aServer.SetServer16(Get().GetRloc16()); } #endif bool Local::IsOnMeshPrefixConsistent(void) { - ThreadNetif &netif = GetNetif(); - - return (netif.GetNetworkDataLeader().ContainsOnMeshPrefixes(*this, netif.GetMle().GetRloc16()) && - ContainsOnMeshPrefixes(netif.GetNetworkDataLeader(), netif.GetMle().GetRloc16())); + return (Get().ContainsOnMeshPrefixes(*this, Get().GetRloc16()) && + ContainsOnMeshPrefixes(Get(), Get().GetRloc16())); } bool Local::IsExternalRouteConsistent(void) { - ThreadNetif &netif = GetNetif(); - - return (netif.GetNetworkDataLeader().ContainsExternalRoutes(*this, netif.GetMle().GetRloc16()) && - ContainsExternalRoutes(netif.GetNetworkDataLeader(), netif.GetMle().GetRloc16())); + return (Get().ContainsExternalRoutes(*this, Get().GetRloc16()) && + ContainsExternalRoutes(Get(), Get().GetRloc16())); } #if OPENTHREAD_ENABLE_SERVICE bool Local::IsServiceConsistent(void) { - ThreadNetif &netif = GetNetif(); - - return (netif.GetNetworkDataLeader().ContainsServices(*this, netif.GetMle().GetRloc16()) && - ContainsServices(netif.GetNetworkDataLeader(), netif.GetMle().GetRloc16())); + return (Get().ContainsServices(*this, Get().GetRloc16()) && + ContainsServices(Get(), Get().GetRloc16())); } #endif otError Local::SendServerDataNotification(void) { - ThreadNetif & netif = GetNetif(); - Mle::MleRouter &mle = netif.GetMle(); - otError error = OT_ERROR_NONE; - uint16_t rloc = mle.GetRloc16(); + otError error = OT_ERROR_NONE; + uint16_t rloc = Get().GetRloc16(); #if OPENTHREAD_FTD // Don't send this Server Data Notification if the device is going to upgrade to Router - if (mle.IsFullThreadDevice() && mle.IsRouterRoleEnabled() && (mle.GetRole() < OT_DEVICE_ROLE_ROUTER) && - (mle.GetRouterTable().GetActiveRouterCount() < mle.GetRouterUpgradeThreshold())) + if (Get().IsFullThreadDevice() && Get().IsRouterRoleEnabled() && + (Get().GetRole() < OT_DEVICE_ROLE_ROUTER) && + (Get().GetActiveRouterCount() < Get().GetRouterUpgradeThreshold())) { ExitNow(error = OT_ERROR_INVALID_STATE); } diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index ca4754c0c..e4871f3a5 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -42,6 +42,7 @@ #include "common/debug.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "mac/mac.hpp" #include "mac/mac_frame.hpp" @@ -67,10 +68,10 @@ NetworkDiagnostic::NetworkDiagnostic(Instance &aInstance) , mReceiveDiagnosticGetCallback(NULL) , mReceiveDiagnosticGetCallbackContext(NULL) { - GetNetif().GetCoap().AddResource(mDiagnosticGetRequest); - GetNetif().GetCoap().AddResource(mDiagnosticGetQuery); - GetNetif().GetCoap().AddResource(mDiagnosticGetAnswer); - GetNetif().GetCoap().AddResource(mDiagnosticReset); + Get().AddResource(mDiagnosticGetRequest); + Get().AddResource(mDiagnosticGetQuery); + Get().AddResource(mDiagnosticGetAnswer); + Get().AddResource(mDiagnosticReset); } void NetworkDiagnostic::SetReceiveDiagnosticGetCallback(otReceiveDiagnosticGetCallback aCallback, @@ -84,13 +85,12 @@ otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; otCoapResponseHandler handler = NULL; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); if (aDestination.IsMulticast()) { @@ -121,12 +121,12 @@ otError NetworkDiagnostic::SendDiagnosticGet(const Ip6::Address &aDestination, SuccessOrExit(error = message->Append(aTlvTypes, aCount)); } - messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aDestination); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, handler, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, handler, this)); otLogInfoNetDiag("Sent diagnostic get"); @@ -186,7 +186,7 @@ void NetworkDiagnostic::HandleDiagnosticGetAnswer(Coap::Message &aMessage, const mReceiveDiagnosticGetCallback(&aMessage, &aMessageInfo, mReceiveDiagnosticGetCallbackContext); } - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoNetDiag("Sent diagnostic answer acknowledgment"); @@ -196,14 +196,13 @@ 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 = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = Get().GetUnicastAddresses(); addr; addr = addr->GetNext()) { count++; } @@ -211,7 +210,7 @@ otError NetworkDiagnostic::AppendIp6AddressList(Message &aMessage) tlv.SetLength(count * sizeof(Ip6::Address)); SuccessOrExit(error = aMessage.Append(&tlv, sizeof(tlv))); - for (const Ip6::NetifUnicastAddress *addr = netif.GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Ip6::NetifUnicastAddress *addr = Get().GetUnicastAddresses(); addr; addr = addr->GetNext()) { SuccessOrExit(error = aMessage.Append(&addr->GetAddress(), sizeof(Ip6::Address))); } @@ -223,7 +222,6 @@ exit: otError NetworkDiagnostic::AppendChildTable(Message &aMessage) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; uint8_t count = 0; uint8_t timeout = 0; @@ -232,7 +230,7 @@ otError NetworkDiagnostic::AppendChildTable(Message &aMessage) tlv.Init(); - count = netif.GetMle().GetChildTable().GetNumChildren(ChildTable::kInStateValid); + count = Get().GetNumChildren(ChildTable::kInStateValid); tlv.SetLength(count * sizeof(ChildTableEntry)); SuccessOrExit(error = aMessage.Append(&tlv, sizeof(ChildTableTlv))); @@ -250,6 +248,7 @@ otError NetworkDiagnostic::AppendChildTable(Message &aMessage) entry.SetReserved(0); entry.SetTimeout(timeout + 4); + entry.SetChildId(Mle::Mle::GetChildId(child.GetRloc16())); entry.SetMode(child.GetDeviceMode()); @@ -263,7 +262,7 @@ exit: void NetworkDiagnostic::FillMacCountersTlv(MacCountersTlv &aMacCountersTlv) { - const otMacCounters &macCounters = GetInstance().Get().GetCounters(); + const otMacCounters &macCounters = Get().GetCounters(); aMacCountersTlv.SetIfInUnknownProtos(macCounters.mRxOther); aMacCountersTlv.SetIfInErrors(macCounters.mRxErrNoFrame + macCounters.mRxErrUnknownNeighbor + @@ -283,10 +282,9 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, Message & aResponse, NetworkDiagnosticTlv &aNetworkDiagnosticTlv) { - ThreadNetif &netif = GetNetif(); - otError error = OT_ERROR_NONE; - uint16_t offset = 0; - uint8_t type; + otError error = OT_ERROR_NONE; + uint16_t offset = 0; + uint8_t type; offset = aRequest.GetOffset() + sizeof(NetworkDiagnosticTlv); @@ -302,7 +300,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { ExtMacAddressTlv tlv; tlv.Init(); - tlv.SetMacAddr(netif.GetMac().GetExtAddress()); + tlv.SetMacAddr(Get().GetExtAddress()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -311,7 +309,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { Address16Tlv tlv; tlv.Init(); - tlv.SetRloc16(netif.GetMle().GetRloc16()); + tlv.SetRloc16(Get().GetRloc16()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -320,19 +318,18 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { ModeTlv tlv; tlv.Init(); - tlv.SetMode(netif.GetMle().GetDeviceMode()); + tlv.SetMode(Get().GetDeviceMode()); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } case NetworkDiagnosticTlv::kTimeout: { - if (!netif.GetMle().IsRxOnWhenIdle()) + if (!Get().IsRxOnWhenIdle()) { TimeoutTlv tlv; tlv.Init(); - tlv.SetTimeout( - TimerMilli::MsecToSec(netif.GetMeshForwarder().GetDataPollManager().GetKeepAlivePollPeriod())); + tlv.SetTimeout(TimerMilli::MsecToSec(Get().GetKeepAlivePollPeriod())); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); } @@ -343,7 +340,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { ConnectivityTlv tlv; tlv.Init(); - netif.GetMle().FillConnectivityTlv(reinterpret_cast(tlv)); + Get().FillConnectivityTlv(reinterpret_cast(tlv)); SuccessOrExit(error = aResponse.Append(&tlv, sizeof(tlv))); break; } @@ -353,7 +350,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { RouteTlv tlv; tlv.Init(); - netif.GetMle().FillRouteTlv(reinterpret_cast(tlv)); + Get().FillRouteTlv(reinterpret_cast(tlv)); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; } @@ -361,7 +358,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, case NetworkDiagnosticTlv::kLeaderData: { - LeaderDataTlv tlv(reinterpret_cast(netif.GetMle().GetLeaderDataTlv())); + LeaderDataTlv tlv(reinterpret_cast(Get().GetLeaderDataTlv())); tlv.Init(); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; @@ -371,7 +368,8 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { NetworkDataTlv tlv; tlv.Init(); - netif.GetMle().FillNetworkDataTlv((reinterpret_cast(tlv)), false); + + Get().FillNetworkDataTlv((reinterpret_cast(tlv)), false); SuccessOrExit(error = aResponse.Append(&tlv, tlv.GetSize())); break; } @@ -412,7 +410,8 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, // Thread 1.1.1 Specification Section 10.11.2.2: // If a Thread device is unable to supply a specific Diagnostic TLV, that TLV is omitted. // Here only Leader or Router may have children. - if (netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER || netif.GetMle().GetRole() == OT_DEVICE_ROLE_ROUTER) + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER || + Get().GetRole() == OT_DEVICE_ROLE_ROUTER) { SuccessOrExit(error = AppendChildTable(aResponse)); } @@ -443,7 +442,7 @@ otError NetworkDiagnostic::FillRequestedTlvs(Message & aRequest, { uint32_t maxTimeout = 0; - if (netif.GetMle().GetMaxChildTimeout(maxTimeout) == OT_ERROR_NONE) + if (Get().GetMaxChildTimeout(maxTimeout) == OT_ERROR_NONE) { MaxChildTimeoutTlv tlv; tlv.Init(); @@ -473,7 +472,6 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(void *aContext, otMessage *aMes void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -494,13 +492,13 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const // DIAG_GET.qry may be sent as a confirmable message. if (aMessage.GetType() == OT_COAP_TYPE_CONFIRMABLE) { - if (netif.GetCoap().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) + if (Get().SendEmptyAck(aMessage, aMessageInfo) == OT_ERROR_NONE) { otLogInfoNetDiag("Sent diagnostic get query acknowledgment"); } } - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -511,10 +509,10 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const message->SetPayloadMarker(); } - messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aMessageInfo.GetPeerAddr()); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); SuccessOrExit(error = FillRequestedTlvs(aMessage, *message, networkDiagnosticTlv)); @@ -524,7 +522,7 @@ void NetworkDiagnostic::HandleDiagnosticGetQuery(Coap::Message &aMessage, const message->SetLength(message->GetLength() - 1); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo, NULL, this)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo, NULL, this)); otLogInfoNetDiag("Sent diagnostic get answer"); @@ -546,7 +544,6 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(void * aContext void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; Coap::Message * message = NULL; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -565,7 +562,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Message &aMessage, cons VerifyOrExit((static_cast(&networkDiagnosticTlv)->IsValid()), error = OT_ERROR_DROP); - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->SetDefaultResponseHeader(aMessage); message->SetPayloadMarker(); @@ -578,7 +575,7 @@ void NetworkDiagnostic::HandleDiagnosticGetRequest(Coap::Message &aMessage, cons message->SetLength(message->GetOffset() - 1); } - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoNetDiag("Sent diagnostic get response"); @@ -594,12 +591,11 @@ otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, const uint8_t aTlvTypes[], uint8_t aCount) { - ThreadNetif & netif = GetNetif(); otError error; Coap::Message * message = NULL; Ip6::MessageInfo messageInfo; - VerifyOrExit((message = netif.GetCoap().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = Get().NewMessage()) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -620,12 +616,12 @@ otError NetworkDiagnostic::SendDiagnosticReset(const Ip6::Address &aDestination, SuccessOrExit(error = message->Append(aTlvTypes, aCount)); } - messageInfo.SetSockAddr(GetNetif().GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(aDestination); messageInfo.SetPeerPort(kCoapUdpPort); - messageInfo.SetInterfaceId(netif.GetInterfaceId()); + messageInfo.SetInterfaceId(Get().GetInterfaceId()); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoNetDiag("Sent network diagnostic reset"); @@ -647,7 +643,6 @@ void NetworkDiagnostic::HandleDiagnosticReset(void *aContext, otMessage *aMessag void NetworkDiagnostic::HandleDiagnosticReset(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - ThreadNetif & netif = GetNetif(); uint16_t offset = 0; uint8_t type; NetworkDiagnosticTlv networkDiagnosticTlv; @@ -672,7 +667,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Message &aMessage, const Ip6 switch (type) { case NetworkDiagnosticTlv::kMacCounters: - netif.GetMac().ResetCounters(); + Get().ResetCounters(); otLogInfoNetDiag("Received diagnostic reset type kMacCounters(9)"); break; @@ -682,7 +677,7 @@ void NetworkDiagnostic::HandleDiagnosticReset(Coap::Message &aMessage, const Ip6 } } - SuccessOrExit(netif.GetCoap().SendEmptyAck(aMessage, aMessageInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, aMessageInfo)); otLogInfoNetDiag("Sent diagnostic reset acknowledgment"); diff --git a/src/core/thread/panid_query_server.cpp b/src/core/thread/panid_query_server.cpp index 9e2090388..b83d23a65 100644 --- a/src/core/thread/panid_query_server.cpp +++ b/src/core/thread/panid_query_server.cpp @@ -41,8 +41,8 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "meshcop/meshcop.hpp" #include "meshcop/meshcop_tlvs.hpp" #include "thread/thread_netif.hpp" @@ -57,7 +57,7 @@ PanIdQueryServer::PanIdQueryServer(Instance &aInstance) , mTimer(aInstance, &PanIdQueryServer::HandleTimer, this) , mPanIdQuery(OT_URI_PATH_PANID_QUERY, &PanIdQueryServer::HandleQuery, this) { - GetNetif().GetCoap().AddResource(mPanIdQuery); + Get().AddResource(mPanIdQuery); } void PanIdQueryServer::HandleQuery(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo) @@ -85,7 +85,7 @@ void PanIdQueryServer::HandleQuery(Coap::Message &aMessage, const Ip6::MessageIn if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast()) { - SuccessOrExit(GetNetif().GetCoap().SendEmptyAck(aMessage, responseInfo)); + SuccessOrExit(Get().SendEmptyAck(aMessage, responseInfo)); otLogInfoMeshCoP("sent panid query response"); } @@ -119,14 +119,13 @@ void PanIdQueryServer::HandleScanResult(Mac::Frame *aFrame) otError PanIdQueryServer::SendConflict(void) { - ThreadNetif & netif = GetNetif(); otError error = OT_ERROR_NONE; MeshCoP::ChannelMaskTlv channelMask; MeshCoP::PanIdTlv panId; Ip6::MessageInfo messageInfo; Coap::Message * message; - VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(netif.GetCoap())) != NULL, error = OT_ERROR_NO_BUFS); + VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get())) != NULL, error = OT_ERROR_NO_BUFS); message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST); message->SetToken(Coap::Message::kDefaultTokenLength); @@ -141,10 +140,10 @@ otError PanIdQueryServer::SendConflict(void) panId.SetPanId(mPanId); SuccessOrExit(error = message->Append(&panId, sizeof(panId))); - messageInfo.SetSockAddr(netif.GetMle().GetMeshLocal16()); + messageInfo.SetSockAddr(Get().GetMeshLocal16()); messageInfo.SetPeerAddr(mCommissioner); messageInfo.SetPeerPort(kCoapUdpPort); - SuccessOrExit(error = netif.GetCoap().SendMessage(*message, messageInfo)); + SuccessOrExit(error = Get().SendMessage(*message, messageInfo)); otLogInfoMeshCoP("sent panid conflict"); @@ -165,7 +164,7 @@ void PanIdQueryServer::HandleTimer(Timer &aTimer) void PanIdQueryServer::HandleTimer(void) { - GetNetif().GetMac().ActiveScan(mChannelMask, 0, HandleScanResult); + Get().ActiveScan(mChannelMask, 0, HandleScanResult); mChannelMask = 0; } diff --git a/src/core/thread/router_table.cpp b/src/core/thread/router_table.cpp index f4c018bd7..c76f95e0f 100644 --- a/src/core/thread/router_table.cpp +++ b/src/core/thread/router_table.cpp @@ -34,6 +34,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" #include "common/timer.hpp" #include "thread/mle.hpp" @@ -52,12 +53,12 @@ RouterTable::Iterator::Iterator(Instance &aInstance) void RouterTable::Iterator::Reset(void) { - mRouter = GetInstance().Get().GetFirstEntry(); + mRouter = Get().GetFirstEntry(); } void RouterTable::Iterator::Advance(void) { - mRouter = GetInstance().Get().GetNextEntry(mRouter); + mRouter = Get().GetNextEntry(mRouter); } RouterTable::RouterTable(Instance &aInstance) @@ -250,7 +251,7 @@ Router *RouterTable::Allocate(uint8_t aRouterId) mRouterIdSequence++; mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); - GetNetif().GetMle().ResetAdvertiseInterval(); + Get().ResetAdvertiseInterval(); otLogNoteMle("Allocate router id %d", aRouterId); @@ -260,13 +261,12 @@ exit: otError RouterTable::Release(uint8_t aRouterId) { - otError error = OT_ERROR_NONE; - ThreadNetif &netif = GetNetif(); - uint16_t rloc16 = Mle::Mle::GetRloc16(aRouterId); + otError error = OT_ERROR_NONE; + uint16_t rloc16 = Mle::Mle::GetRloc16(aRouterId); assert(aRouterId <= Mle::kMaxRouterId); - VerifyOrExit(netif.GetMle().GetRole() == OT_DEVICE_ROLE_LEADER, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(Get().GetRole() == OT_DEVICE_ROLE_LEADER, error = OT_ERROR_INVALID_STATE); VerifyOrExit(IsAllocated(aRouterId), error = OT_ERROR_NOT_FOUND); mAllocatedRouterIds.Remove(aRouterId); @@ -286,9 +286,9 @@ otError RouterTable::Release(uint8_t aRouterId) mRouterIdSequence++; mRouterIdSequenceLastUpdated = TimerMilli::GetNow(); - netif.GetAddressResolver().Remove(aRouterId); - netif.GetNetworkDataLeader().RemoveBorderRouter(rloc16, NetworkData::Leader::kMatchModeRouterId); - netif.GetMle().ResetAdvertiseInterval(); + Get().Remove(aRouterId); + Get().RemoveBorderRouter(rloc16, NetworkData::Leader::kMatchModeRouterId); + Get().ResetAdvertiseInterval(); otLogNoteMle("Release router id %d", aRouterId); @@ -298,8 +298,6 @@ exit: void RouterTable::RemoveNeighbor(Router &aRouter) { - ThreadNetif &netif = GetNetif(); - aRouter.SetLinkQualityOut(0); aRouter.SetLastHeard(TimerMilli::GetNow()); @@ -312,17 +310,17 @@ void RouterTable::RemoveNeighbor(Router &aRouter) if (GetLinkCost(*cur) >= Mle::kMaxRouteCost) { - netif.GetMle().ResetAdvertiseInterval(); + Get().ResetAdvertiseInterval(); } } } if (aRouter.GetNextHop() == Mle::kInvalidRouterId) { - netif.GetMle().ResetAdvertiseInterval(); + Get().ResetAdvertiseInterval(); // Clear all EID-to-RLOC entries associated with the router. - netif.GetAddressResolver().Remove(aRouter.GetRouterId()); + Get().Remove(aRouter.GetRouterId()); } } @@ -345,7 +343,7 @@ Router *RouterTable::GetNeighbor(uint16_t aRloc16) { Router *router = NULL; - VerifyOrExit(aRloc16 != GetNetif().GetMle().GetRloc16()); + VerifyOrExit(aRloc16 != Get().GetRloc16()); for (router = GetFirstEntry(); router != NULL; router = GetNextEntry(router)) { @@ -363,7 +361,7 @@ Router *RouterTable::GetNeighbor(const Mac::ExtAddress &aExtAddress) { Router *router = NULL; - VerifyOrExit(aExtAddress != GetNetif().GetMac().GetExtAddress()); + VerifyOrExit(aExtAddress != Get().GetExtAddress()); for (router = GetFirstEntry(); router != NULL; router = GetNextEntry(router)) { @@ -446,7 +444,7 @@ exit: Router *RouterTable::GetLeader(void) { - return GetRouter(GetNetif().GetMle().GetLeaderId()); + return GetRouter(Get().GetLeaderId()); } uint32_t RouterTable::GetLeaderAge(void) const @@ -474,7 +472,8 @@ uint8_t RouterTable::GetLinkCost(Router &aRouter) { uint8_t rval = Mle::kMaxRouteCost; - VerifyOrExit(aRouter.GetRloc16() != GetNetif().GetMle().GetRloc16() && aRouter.GetState() == Neighbor::kStateValid); + VerifyOrExit(aRouter.GetRloc16() != Get().GetRloc16() && + aRouter.GetState() == Neighbor::kStateValid); rval = aRouter.GetLinkInfo().GetLinkQuality(); @@ -524,7 +523,7 @@ void RouterTable::ProcessTlv(const Mle::RouteTlv &aTlv) if (allocationChanged) { UpdateAllocation(); - GetNetif().GetMle().ResetAdvertiseInterval(); + Get().ResetAdvertiseInterval(); } } @@ -557,13 +556,13 @@ void RouterTable::ProcessTlv(const ThreadRouterMaskTlv &aTlv) if (allocationChanged) { UpdateAllocation(); - GetNetif().GetMle().ResetAdvertiseInterval(); + Get().ResetAdvertiseInterval(); } } void RouterTable::ProcessTimerTick(void) { - Mle::MleRouter &mle = GetNetif().GetMle(); + Mle::MleRouter &mle = Get(); if (mle.GetRole() == OT_DEVICE_ROLE_LEADER) { diff --git a/src/core/thread/thread_netif.cpp b/src/core/thread/thread_netif.cpp index 04e3e44c6..ea225fa85 100644 --- a/src/core/thread/thread_netif.cpp +++ b/src/core/thread/thread_netif.cpp @@ -36,6 +36,7 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/message.hpp" #include "net/ip6.hpp" #include "net/netif.hpp" @@ -59,10 +60,10 @@ ThreadNetif::ThreadNetif(Instance &aInstance) , mSlaac(aInstance) #endif #if OPENTHREAD_ENABLE_DNS_CLIENT - , mDnsClient(aInstance.GetThreadNetif()) + , mDnsClient(Get()) #endif // OPENTHREAD_ENABLE_DNS_CLIENT #if OPENTHREAD_ENABLE_SNTP_CLIENT - , mSntpClient(aInstance.GetThreadNetif()) + , mSntpClient(Get()) #endif // OPENTHREAD_ENABLE_SNTP_CLIENT , mActiveDataset(aInstance) , mPendingDataset(aInstance) @@ -108,7 +109,7 @@ ThreadNetif::ThreadNetif(Instance &aInstance) , mTimeSync(aInstance) #endif { - mCoap.SetInterceptor(&ThreadNetif::TmfFilter, this); + Get().SetInterceptor(&ThreadNetif::TmfFilter, this); } void ThreadNetif::Up(void) @@ -116,25 +117,25 @@ void ThreadNetif::Up(void) VerifyOrExit(!mIsUp); // Enable the MAC just in case it was disabled while the Interface was down. - mMac.SetEnabled(true); + Get().SetEnabled(true); #if OPENTHREAD_ENABLE_CHANNEL_MONITOR - GetInstance().GetChannelMonitor().Start(); + Get().Start(); #endif - mMeshForwarder.Start(); - GetIp6().AddNetif(*this); + Get().Start(); + Get().AddNetif(*this); mIsUp = true; SubscribeAllNodesMulticast(); - mMleRouter.Enable(); - mCoap.Start(kCoapUdpPort); + Get().Enable(); + Get().Start(kCoapUdpPort); #if OPENTHREAD_ENABLE_DNS_CLIENT - mDnsClient.Start(); + Get().Start(); #endif #if OPENTHREAD_ENABLE_SNTP_CLIENT - mSntpClient.Start(); + Get().Start(); #endif - GetNotifier().Signal(OT_CHANGED_THREAD_NETIF_STATE); + Get().Signal(OT_CHANGED_THREAD_NETIF_STATE); exit: return; @@ -145,28 +146,28 @@ void ThreadNetif::Down(void) VerifyOrExit(mIsUp); #if OPENTHREAD_ENABLE_DNS_CLIENT - mDnsClient.Stop(); + Get().Stop(); #endif #if OPENTHREAD_ENABLE_SNTP_CLIENT - mSntpClient.Stop(); + Get().Stop(); #endif #if OPENTHREAD_ENABLE_DTLS - mCoapSecure.Stop(); + Get().Stop(); #endif - mCoap.Stop(); - mMleRouter.Disable(); + Get().Stop(); + Get().Disable(); RemoveAllExternalUnicastAddresses(); UnsubscribeAllExternalMulticastAddresses(); UnsubscribeAllRoutersMulticast(); UnsubscribeAllNodesMulticast(); mIsUp = false; - GetIp6().RemoveNetif(*this); - mMeshForwarder.Stop(); + Get().RemoveNetif(*this); + Get().Stop(); #if OPENTHREAD_ENABLE_CHANNEL_MONITOR - GetInstance().GetChannelMonitor().Stop(); + Get().Stop(); #endif - GetNotifier().Signal(OT_CHANGED_THREAD_NETIF_STATE); + Get().Signal(OT_CHANGED_THREAD_NETIF_STATE); exit: return; @@ -176,7 +177,7 @@ otError ThreadNetif::GetLinkAddress(Ip6::LinkAddress &aAddress) const { aAddress.mType = Ip6::LinkAddress::kEui64; aAddress.mLength = sizeof(aAddress.mExtAddress); - aAddress.mExtAddress = mMac.GetExtAddress(); + aAddress.mExtAddress = Get().GetExtAddress(); return OT_ERROR_NONE; } @@ -185,9 +186,9 @@ otError ThreadNetif::RouteLookup(const Ip6::Address &aSource, const Ip6::Address otError error; uint16_t rloc; - SuccessOrExit(error = mNetworkDataLeader.RouteLookup(aSource, aDestination, aPrefixMatch, &rloc)); + SuccessOrExit(error = Get().RouteLookup(aSource, aDestination, aPrefixMatch, &rloc)); - if (rloc == mMleRouter.GetRloc16()) + if (rloc == Get().GetRloc16()) { error = OT_ERROR_NO_ROUTE; } @@ -212,9 +213,9 @@ bool ThreadNetif::IsTmfMessage(const Ip6::MessageInfo &aMessageInfo) // and the source is a Mesh Local Address. Or // 2. Both the destination and the source are Link-Local Addresses. VerifyOrExit( - ((mMleRouter.IsMeshLocalAddress(aMessageInfo.GetSockAddr()) || + ((Get().IsMeshLocalAddress(aMessageInfo.GetSockAddr()) || aMessageInfo.GetSockAddr().IsLinkLocalMulticast() || aMessageInfo.GetSockAddr().IsRealmLocalMulticast()) && - mMleRouter.IsMeshLocalAddress(aMessageInfo.GetPeerAddr())) || + Get().IsMeshLocalAddress(aMessageInfo.GetPeerAddr())) || ((aMessageInfo.GetSockAddr().IsLinkLocal() || aMessageInfo.GetSockAddr().IsLinkLocalMulticast()) && aMessageInfo.GetPeerAddr().IsLinkLocal()), rval = false); diff --git a/src/core/thread/thread_netif.hpp b/src/core/thread/thread_netif.hpp index 3551dd1e5..f3b3eff41 100644 --- a/src/core/thread/thread_netif.hpp +++ b/src/core/thread/thread_netif.hpp @@ -96,6 +96,8 @@ namespace ot { class ThreadNetif : public Ip6::Netif { + friend class Instance; + public: /** * This constructor initializes the Thread network interface. @@ -157,281 +159,6 @@ public: */ virtual otError RouteLookup(const Ip6::Address &aSource, const Ip6::Address &aDestination, uint8_t *aPrefixMatch); -#if OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC - /** - * This method returns a reference to the network diagnostic object. - * - * @returns A reference to the address resolver object. - * - */ - NetworkDiagnostic::NetworkDiagnostic &GetNetworkDiagnostic(void) { return mNetworkDiagnostic; } -#endif // OPENTHREAD_FTD || OPENTHREAD_ENABLE_MTD_NETWORK_DIAGNOSTIC - -#if OPENTHREAD_ENABLE_DHCP6_CLIENT - /** - * This method returns a reference to the dhcp client object. - * - * @returns A reference to the dhcp client object. - * - */ - Dhcp6::Dhcp6Client &GetDhcp6Client(void) { return mDhcp6Client; } -#endif // OPENTHREAD_ENABLE_DHCP6_CLIENT - -#if OPENTHREAD_ENABLE_DHCP6_SERVER - /** - * This method returns a reference to the dhcp server object. - * - * @returns A reference to the dhcp server object. - * - */ - Dhcp6::Dhcp6Server &GetDhcp6Server(void) { return mDhcp6Server; } -#endif // OPENTHREAD_ENABLE_DHCP6_SERVER - -#if OPENTHREAD_CONFIG_ENABLE_SLAAC - /** - * This method returns a reference to the SLAAC manager object. - * - * @returns A reference to the SLAAC manager object. - * - */ - Utils::Slaac &GetSlaac(void) { return mSlaac; } -#endif - -#if OPENTHREAD_ENABLE_DNS_CLIENT - /** - * This method returns a reference to the dns client object. - * - * @returns A reference to the dns client object. - * - */ - Dns::Client &GetDnsClient(void) { return mDnsClient; } -#endif // OPENTHREAD_ENABLE_DNS_CLIENT - - /** - * This method returns a reference to the CoAP object. - * - * @returns A reference to the CoAP object. - * - */ - Coap::Coap &GetCoap(void) { return mCoap; } - - /** - * This method returns a reference to the IPv6 filter object. - * - * @returns A reference to the IPv6 filter object. - * - */ - Ip6::Filter &GetIp6Filter(void) { return mIp6Filter; } - - /** - * This method returns a reference to the key manager object. - * - * @returns A reference to the key manager object. - * - */ - KeyManager &GetKeyManager(void) { return mKeyManager; } - - /** - * This method returns a reference to the lowpan object. - * - * @returns A reference to the lowpan object. - * - */ - Lowpan::Lowpan &GetLowpan(void) { return mLowpan; } - - /** - * This method returns a reference to the mac object. - * - * @returns A reference to the mac object. - * - */ - Mac::Mac &GetMac(void) { return mMac; } - - /** - * This method returns a reference to the mle object. - * - * @returns A reference to the mle object. - * - */ - Mle::MleRouter &GetMle(void) { return mMleRouter; } - - /** - * This method returns a reference to the mesh forwarder object. - * - * @returns A reference to the mesh forwarder object. - * - */ - MeshForwarder &GetMeshForwarder(void) { return mMeshForwarder; } - -#if OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - /** - * This method returns a reference to the network data local object. - * - * @returns A reference to the network data local object. - * - */ - NetworkData::Local &GetNetworkDataLocal(void) { return mNetworkDataLocal; } -#endif // OPENTHREAD_ENABLE_BORDER_ROUTER || OPENTHREAD_ENABLE_SERVICE - - /** - * This method returns a reference to the network data leader object. - * - * @returns A reference to the network data leader object. - * - */ - NetworkData::Leader &GetNetworkDataLeader(void) { return mNetworkDataLeader; } - - /** - * This method returns a reference to the active dataset object. - * - * @returns A reference to the active dataset object. - * - */ - MeshCoP::ActiveDataset &GetActiveDataset(void) { return mActiveDataset; } - - /** - * This method returns a reference to the pending dataset object. - * - * @returns A reference to the pending dataset object. - * - */ - MeshCoP::PendingDataset &GetPendingDataset(void) { return mPendingDataset; } - -#if OPENTHREAD_FTD - /** - * This method returns a reference to the joiner router object. - * - * @returns A reference to the joiner router object. - * - */ - MeshCoP::JoinerRouter &GetJoinerRouter(void) { return mJoinerRouter; } - - /** - * This method returns a reference to the MeshCoP leader object. - * - * @returns A reference to the MeshCoP leader object. - * - */ - MeshCoP::Leader &GetLeader(void) { return mLeader; } - - /** - * This method returns a reference to the address resolver object. - * - * @returns A reference to the address resolver object. - * - */ - AddressResolver &GetAddressResolver(void) { return mAddressResolver; } -#endif // OPENTHREAD_FTD - - /** - * This method returns a reference to the announce begin server object. - * - * @returns A reference to the announce begin server object. - * - */ - AnnounceBeginServer &GetAnnounceBeginServer(void) { return mAnnounceBegin; } - -#if OPENTHREAD_ENABLE_BORDER_AGENT - /** - * This method returns a reference to the border agent object. - * - * @returns A reference to the border agent object. - * - */ - MeshCoP::BorderAgent &GetBorderAgent(void) { return mBorderAgent; } -#endif -#if OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - /** - * This method returns a reference to the commissioner object. - * - * @returns A reference to the commissioner object. - * - */ - MeshCoP::Commissioner &GetCommissioner(void) { return mCommissioner; } -#endif // OPENTHREAD_ENABLE_COMMISSIONER && OPENTHREAD_FTD - -#if OPENTHREAD_ENABLE_DTLS - /** - * This method returns a reference to the secure CoAP object. - * - * @returns A reference to the secure CoAP object. - * - */ - Coap::CoapSecure &GetCoapSecure(void) { return mCoapSecure; } -#endif // OPENTHREAD_ENABLE_DTLS - -#if OPENTHREAD_ENABLE_JOINER - /** - * This method returns a reference to the joiner object. - * - * @returns A reference to the joiner object. - * - */ - MeshCoP::Joiner &GetJoiner(void) { return mJoiner; } -#endif // OPENTHREAD_ENABLE_JOINER - -#if OPENTHREAD_ENABLE_JAM_DETECTION - /** - * This method returns the jam detector instance. - * - * @returns Reference to the JamDetector instance. - * - */ - Utils::JamDetector &GetJamDetector(void) { return mJamDetector; } -#endif // OPENTHREAD_ENABLE_JAM_DETECTION - - /** - * This method returns a reference to the child supervisor object. - * - * @returns A reference to the child supervisor object. - * - */ - Utils::ChildSupervisor &GetChildSupervisor(void) { return mChildSupervisor; } - - /** - * This method returns a reference to the supervision listener object. - * - * @returns A reference to the supervision listener object. - * - */ - Utils::SupervisionListener &GetSupervisionListener(void) { return mSupervisionListener; } - - /** - * 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; } - -#if OPENTHREAD_CONFIG_ENABLE_TIME_SYNC - /** - * This method returns a reference to the Time Synchronization Service object. - * - * @returns A reference to the Time Synchronization Service object. - * - */ - TimeSync &GetTimeSync(void) { return mTimeSync; } -#endif - -#if OPENTHREAD_ENABLE_SNTP_CLIENT - /** - * This method returns a reference to the SNTP client object. - * - * @returns A reference to the SNTP client object. - * - */ - Sntp::Client &GetSntpClient(void) { return mSntpClient; } -#endif // OPENTHREAD_ENABLE_SNTP_CLIENT - /** * This method returns whether Thread Management Framework Addressing Rules are met. * diff --git a/src/core/thread/time_sync_service.cpp b/src/core/thread/time_sync_service.cpp index b956e31cc..869e143e0 100644 --- a/src/core/thread/time_sync_service.cpp +++ b/src/core/thread/time_sync_service.cpp @@ -42,8 +42,8 @@ #include #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #define ABS(value) (((value) >= 0) ? (value) : -(value)) @@ -87,14 +87,14 @@ void TimeSync::HandleTimeSyncMessage(const Message &aMessage) // receive older time sync sequence. mTimeSyncRequired = true; } - else if (GetInstance().GetThreadNetif().GetMle().GetRole() != OT_DEVICE_ROLE_LEADER) + else if (Get().GetRole() != OT_DEVICE_ROLE_LEADER) { // Update network time in following three cases: // 1. during first attach; // 2. already attached, receive newer time sync sequence; // 3. during reattach or migration process. if (mTimeSyncSeq == OT_TIME_SYNC_INVALID_SEQ || (int8_t)(aMessage.GetTimeSyncSeq() - mTimeSyncSeq) > 0 || - GetInstance().GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_DETACHED) + Get().GetRole() == OT_DEVICE_ROLE_DETACHED) { // update network time and forward it. mLastTimeSyncReceived = TimerMilli::GetNow(); @@ -132,7 +132,7 @@ void TimeSync::NotifyTimeSyncCallback(void) #if OPENTHREAD_FTD void TimeSync::ProcessTimeSync(void) { - if (GetInstance().GetThreadNetif().GetMle().GetRole() == OT_DEVICE_ROLE_LEADER && + if (Get().GetRole() == OT_DEVICE_ROLE_LEADER && TimerMilli::GetNow() - mLastTimeSyncSent > TimerMilli::SecToMsec(mTimeSyncPeriod)) { IncrementTimeSyncSeq(); @@ -141,7 +141,7 @@ void TimeSync::ProcessTimeSync(void) if (mTimeSyncRequired) { - VerifyOrExit(GetInstance().GetThreadNetif().GetMle().SendTimeSync() == OT_ERROR_NONE); + VerifyOrExit(Get().SendTimeSync() == OT_ERROR_NONE); mLastTimeSyncSent = TimerMilli::GetNow(); mTimeSyncRequired = false; @@ -178,7 +178,7 @@ void TimeSync::HandleTimeout(Timer &aTimer) void TimeSync::CheckAndHandleChanges(bool aTimeUpdated) { otNetworkTimeStatus networkTimeStatus = OT_NETWORK_TIME_SYNCHRONIZED; - const otDeviceRole role = GetInstance().GetThreadNetif().GetMle().GetRole(); + const otDeviceRole role = Get().GetRole(); const uint32_t resyncNeededThresholdMs = 2 * TimerMilli::SecToMsec(mTimeSyncPeriod); const uint32_t timeSyncLastSyncMs = TimerMilli::GetNow() - mLastTimeSyncReceived; diff --git a/src/core/thread/topology.cpp b/src/core/thread/topology.cpp index 53207a737..877efdea5 100644 --- a/src/core/thread/topology.cpp +++ b/src/core/thread/topology.cpp @@ -38,6 +38,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" namespace ot { @@ -104,7 +105,7 @@ otError Child::GetMeshLocalIp6Address(Instance &aInstance, Ip6::Address &aAddres VerifyOrExit(!IsAllZero(mMeshLocalIid, sizeof(mMeshLocalIid)), error = OT_ERROR_NOT_FOUND); - memcpy(aAddress.mFields.m8, aInstance.GetThreadNetif().GetMle().GetMeshLocalPrefix().m8, + memcpy(aAddress.mFields.m8, aInstance.Get().GetMeshLocalPrefix().m8, Ip6::Address::kMeshLocalPrefixSize); aAddress.SetIid(mMeshLocalIid); @@ -144,7 +145,7 @@ otError Child::AddIp6Address(Instance &aInstance, const Ip6::Address &aAddress) VerifyOrExit(!aAddress.IsUnspecified(), error = OT_ERROR_INVALID_ARGS); - if (aInstance.GetThreadNetif().GetMle().IsMeshLocalAddress(aAddress)) + if (aInstance.Get().IsMeshLocalAddress(aAddress)) { VerifyOrExit(IsAllZero(mMeshLocalIid, sizeof(mMeshLocalIid)), error = OT_ERROR_ALREADY); memcpy(mMeshLocalIid, aAddress.GetIid(), Ip6::Address::kInterfaceIdentifierSize); @@ -175,7 +176,7 @@ otError Child::RemoveIp6Address(Instance &aInstance, const Ip6::Address &aAddres VerifyOrExit(!aAddress.IsUnspecified(), error = OT_ERROR_INVALID_ARGS); - if (aInstance.GetThreadNetif().GetMle().IsMeshLocalAddress(aAddress)) + if (aInstance.Get().IsMeshLocalAddress(aAddress)) { if (memcmp(aAddress.GetIid(), mMeshLocalIid, Ip6::Address::kInterfaceIdentifierSize) == 0) { @@ -216,7 +217,7 @@ bool Child::HasIp6Address(Instance &aInstance, const Ip6::Address &aAddress) con VerifyOrExit(!aAddress.IsUnspecified()); - if (aInstance.GetThreadNetif().GetMle().IsMeshLocalAddress(aAddress)) + if (aInstance.Get().IsMeshLocalAddress(aAddress)) { retval = (memcmp(aAddress.GetIid(), mMeshLocalIid, Ip6::Address::kInterfaceIdentifierSize) == 0); ExitNow(); diff --git a/src/core/utils/channel_manager.cpp b/src/core/utils/channel_manager.cpp index ee3ae22ac..b9a37ab02 100644 --- a/src/core/utils/channel_manager.cpp +++ b/src/core/utils/channel_manager.cpp @@ -38,8 +38,8 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "phy/phy.hpp" @@ -67,7 +67,7 @@ void ChannelManager::RequestChannelChange(uint8_t aChannel) { otLogInfoUtil("ChannelManager: Request to change to channel %d with delay %d sec", aChannel, mDelay); - if (aChannel == GetInstance().Get().GetPanChannel()) + if (aChannel == Get().GetPanChannel()) { otLogInfoUtil("ChannelManager: Already operating on the requested channel %d", aChannel); ExitNow(); @@ -79,7 +79,7 @@ void ChannelManager::RequestChannelChange(uint8_t aChannel) mTimer.Start(1 + Random::GetUint32InRange(0, kRequestStartJitterInterval)); - GetNotifier().Signal(OT_CHANGED_CHANNEL_MANAGER_NEW_CHANNEL); + Get().Signal(OT_CHANGED_CHANNEL_MANAGER_NEW_CHANNEL); exit: return; @@ -98,7 +98,6 @@ exit: void ChannelManager::PreparePendingDataset(void) { - ThreadNetif & netif = GetInstance().GetThreadNetif(); uint64_t pendingTimestamp = 0; uint64_t pendingActiveTimestamp = 0; uint32_t delayInMs = TimerMilli::SecToMsec(static_cast(mDelay)); @@ -107,9 +106,9 @@ void ChannelManager::PreparePendingDataset(void) VerifyOrExit(mState == kStateChangeRequested); - VerifyOrExit(mChannel != GetInstance().Get().GetPanChannel()); + VerifyOrExit(mChannel != Get().GetPanChannel()); - if (netif.GetPendingDataset().Read(dataset) == OT_ERROR_NONE) + if (Get().Read(dataset) == OT_ERROR_NONE) { if (dataset.mComponents.mIsPendingTimestampPresent) { @@ -134,7 +133,7 @@ void ChannelManager::PreparePendingDataset(void) pendingTimestamp += 1 + Random::GetUint32InRange(0, kMaxTimestampIncrease); - error = netif.GetActiveDataset().Read(dataset); + error = Get().Read(dataset); if (error != OT_ERROR_NONE) { @@ -143,7 +142,7 @@ void ChannelManager::PreparePendingDataset(void) // situation where a channel change request comes right after the // network is formed but before the active dataset is created. - if (GetInstance().Get().GetRole() != OT_DEVICE_ROLE_DISABLED) + if (Get().GetRole() != OT_DEVICE_ROLE_DISABLED) { mTimer.Start(kPendingDatasetTxRetryInterval); } @@ -207,7 +206,7 @@ void ChannelManager::PreparePendingDataset(void) dataset.mDelay = delayInMs; dataset.mComponents.mIsDelayPresent = true; - error = netif.GetPendingDataset().SendSetRequest(dataset, NULL, 0); + error = Get().SendSetRequest(dataset, NULL, 0); if (error == OT_ERROR_NONE) { @@ -263,7 +262,7 @@ void ChannelManager::HandleStateChanged(Notifier::Callback &aCallback, otChanged void ChannelManager::HandleStateChanged(otChangedFlags aChangedFlags) { VerifyOrExit((aChangedFlags & OT_CHANGED_THREAD_CHANNEL) != 0); - VerifyOrExit(mChannel == GetInstance().Get().GetPanChannel()); + VerifyOrExit(mChannel == Get().GetPanChannel()); mState = kStateIdle; StartAutoSelectTimer(); @@ -313,26 +312,25 @@ exit: otError ChannelManager::FindBetterChannel(uint8_t &aNewChannel, uint16_t &aOccupancy) { - otError error = OT_ERROR_NONE; - ChannelMonitor & monitor = GetInstance().GetChannelMonitor(); + otError error = OT_ERROR_NONE; Mac::ChannelMask favoredAndSupported; Mac::ChannelMask favoredBest; Mac::ChannelMask supportedBest; uint16_t favoredOccupancy; uint16_t supportedOccupancy; - if (monitor.GetSampleCount() <= kMinChannelMonitorSampleCount) + if (Get().GetSampleCount() <= kMinChannelMonitorSampleCount) { - otLogInfoUtil("ChannelManager: Too few samples (%d <= %d) to select channel", monitor.GetSampleCount(), - kMinChannelMonitorSampleCount); + otLogInfoUtil("ChannelManager: Too few samples (%d <= %d) to select channel", + Get().GetSampleCount(), kMinChannelMonitorSampleCount); ExitNow(error = OT_ERROR_INVALID_STATE); } favoredAndSupported = mFavoredChannelMask; favoredAndSupported.Intersect(mSupportedChannelMask); - favoredBest = monitor.FindBestChannels(favoredAndSupported, favoredOccupancy); - supportedBest = monitor.FindBestChannels(mSupportedChannelMask, supportedOccupancy); + favoredBest = Get().FindBestChannels(favoredAndSupported, favoredOccupancy); + supportedBest = Get().FindBestChannels(mSupportedChannelMask, supportedOccupancy); otLogInfoUtil("ChannelManager: Best favored %s, occupancy 0x%04x", favoredBest.ToString().AsCString(), favoredOccupancy); @@ -366,7 +364,7 @@ exit: bool ChannelManager::ShouldAttemptChannelChange(void) { - uint16_t ccaFailureRate = GetInstance().Get().GetCcaFailureRate(); + uint16_t ccaFailureRate = Get().GetCcaFailureRate(); bool shouldAttempt = (ccaFailureRate >= kCcaFailureRateThreshold); otLogInfoUtil("ChannelManager: CCA-err-rate: 0x%04x %s 0x%04x, selecting channel: %s", ccaFailureRate, @@ -384,14 +382,14 @@ otError ChannelManager::RequestChannelSelect(bool aSkipQualityCheck) otLogInfoUtil("ChannelManager: Request to select channel (skip quality check: %s)", aSkipQualityCheck ? "yes" : "no"); - VerifyOrExit(GetInstance().Get().GetRole() != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); + VerifyOrExit(Get().GetRole() != OT_DEVICE_ROLE_DISABLED, error = OT_ERROR_INVALID_STATE); VerifyOrExit(aSkipQualityCheck || ShouldAttemptChannelChange()); SuccessOrExit(error = FindBetterChannel(newChannel, newOccupancy)); - curChannel = GetInstance().Get().GetPanChannel(); - curOccupancy = GetInstance().GetChannelMonitor().GetChannelOccupancy(curChannel); + curChannel = Get().GetPanChannel(); + curOccupancy = Get().GetChannelOccupancy(curChannel); if (newChannel == curChannel) { diff --git a/src/core/utils/channel_monitor.cpp b/src/core/utils/channel_monitor.cpp index bee8dc37f..dc9eca616 100644 --- a/src/core/utils/channel_monitor.cpp +++ b/src/core/utils/channel_monitor.cpp @@ -34,8 +34,8 @@ #include "channel_monitor.hpp" #include "common/code_utils.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #if OPENTHREAD_ENABLE_CHANNEL_MONITOR @@ -119,8 +119,7 @@ void ChannelMonitor::HandleTimer(Timer &aTimer) void ChannelMonitor::HandleTimer(void) { - GetInstance().Get().EnergyScan(mScanChannelMasks[mChannelMaskIndex], 0, - &ChannelMonitor::HandleEnergyScanResult); + Get().EnergyScan(mScanChannelMasks[mChannelMaskIndex], 0, &ChannelMonitor::HandleEnergyScanResult); mTimer.StartAt(mTimer.GetFireTime(), Random::AddJitter(kTimerInterval, kMaxJitterInterval)); } diff --git a/src/core/utils/child_supervision.cpp b/src/core/utils/child_supervision.cpp index 886bc6b82..0c200c00b 100644 --- a/src/core/utils/child_supervision.cpp +++ b/src/core/utils/child_supervision.cpp @@ -36,8 +36,8 @@ #include "openthread-core-config.h" #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "thread/thread_netif.hpp" namespace ot { @@ -69,7 +69,7 @@ Child *ChildSupervisor::GetDestination(const Message &aMessage) const VerifyOrExit(aMessage.GetType() == Message::kTypeSupervision); aMessage.Read(0, sizeof(childIndex), &childIndex); - child = GetNetif().GetMle().GetChildTable().GetChildAtIndex(childIndex); + child = Get().GetChildAtIndex(childIndex); exit: return child; @@ -77,13 +77,12 @@ exit: void ChildSupervisor::SendMessage(Child &aChild) { - ThreadNetif &netif = GetNetif(); - Message * message = NULL; - uint8_t childIndex; + Message *message = NULL; + uint8_t childIndex; VerifyOrExit(aChild.GetIndirectMessageCount() == 0); - message = netif.GetInstance().GetMessagePool().New(Message::kTypeSupervision, sizeof(uint8_t)); + message = Get().New(Message::kTypeSupervision, sizeof(uint8_t)); VerifyOrExit(message != NULL); // Supervision message is an empty payload 15.4 data frame. @@ -91,10 +90,10 @@ void ChildSupervisor::SendMessage(Child &aChild) // the destination of the message to be later retrieved using // `ChildSupervisor::GetDestination(message)`. - childIndex = netif.GetMle().GetChildTable().GetChildIndex(aChild); + childIndex = Get().GetChildIndex(aChild); SuccessOrExit(message->Append(&childIndex, sizeof(childIndex))); - SuccessOrExit(netif.SendMessage(*message)); + SuccessOrExit(Get().SendMessage(*message)); message = NULL; otLogInfoUtil("Sending supervision message to child 0x%04x", aChild.GetRloc16()); @@ -141,15 +140,14 @@ exit: void ChildSupervisor::CheckState(void) { - bool shouldRun = false; - Mle::MleRouter &mle = GetInstance().Get(); + bool shouldRun = false; // Child Supervision should run if `mSupervisionInterval` is not // zero, Thread MLE operation is enabled, and there is at least one // "valid" child in the child table. - shouldRun = ((mSupervisionInterval != 0) && (mle.GetRole() != OT_DEVICE_ROLE_DISABLED) && - mle.GetChildTable().HasChildren(ChildTable::kInStateValid)); + shouldRun = ((mSupervisionInterval != 0) && (Get().GetRole() != OT_DEVICE_ROLE_DISABLED) && + Get().HasChildren(ChildTable::kInStateValid)); if (shouldRun && !mTimer.IsRunning()) { @@ -208,12 +206,10 @@ 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 && (netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && - (netif.GetMle().GetNeighbor(aSourceAddress) == netif.GetMle().GetParent())); + VerifyOrExit(mTimer.IsRunning() && aIsSecure && (Get().GetRole() == OT_DEVICE_ROLE_CHILD) && + (Get().GetNeighbor(aSourceAddress) == Get().GetParent())); RestartTimer(); @@ -223,10 +219,8 @@ exit: void SupervisionListener::RestartTimer(void) { - ThreadNetif &netif = GetNetif(); - - if ((mTimeout != 0) && (netif.GetMle().GetRole() != OT_DEVICE_ROLE_DISABLED) && - (netif.GetMeshForwarder().GetRxOnWhenIdle() == false)) + if ((mTimeout != 0) && (Get().GetRole() != OT_DEVICE_ROLE_DISABLED) && + (Get().GetRxOnWhenIdle() == false)) { mTimer.Start(TimerMilli::SecToMsec(mTimeout)); } @@ -243,14 +237,12 @@ void SupervisionListener::HandleTimer(Timer &aTimer) void SupervisionListener::HandleTimer(void) { - ThreadNetif &netif = GetNetif(); - - VerifyOrExit((netif.GetMle().GetRole() == OT_DEVICE_ROLE_CHILD) && - (netif.GetMeshForwarder().GetRxOnWhenIdle() == false)); + VerifyOrExit((Get().GetRole() == OT_DEVICE_ROLE_CHILD) && + (Get().GetRxOnWhenIdle() == false)); otLogWarnUtil("Supervision timeout. No frame from parent in %d sec", mTimeout); - netif.GetMle().SendChildUpdateRequest(); + Get().SendChildUpdateRequest(); exit: RestartTimer(); diff --git a/src/core/utils/jam_detector.cpp b/src/core/utils/jam_detector.cpp index 912dc298b..9ac157129 100644 --- a/src/core/utils/jam_detector.cpp +++ b/src/core/utils/jam_detector.cpp @@ -35,8 +35,8 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "thread/thread_netif.hpp" @@ -103,7 +103,7 @@ void JamDetector::CheckState(void) { VerifyOrExit(mEnabled); - switch (GetInstance().Get().GetRole()) + switch (Get().GetRole()) { case OT_DEVICE_ROLE_DISABLED: VerifyOrExit(mTimer.IsRunning()); diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index b3f47f612..eadf150bc 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -37,8 +37,8 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/locator-getters.hpp" #include "common/logging.hpp" -#include "common/owner-locator.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "crypto/sha256.hpp" @@ -142,8 +142,6 @@ exit: void Slaac::Update(UpdateMode aMode) { - ThreadNetif & netif = GetNetif(); - NetworkData::Leader & networkData = GetInstance().Get(); otNetworkDataIterator iterator; otBorderRouterConfig config; Ip6::NetifUnicastAddress *slaacAddr; @@ -167,7 +165,7 @@ void Slaac::Update(UpdateMode aMode) { iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (networkData.GetNextOnMeshPrefix(&iterator, &config) == OT_ERROR_NONE) + while (Get().GetNextOnMeshPrefix(&iterator, &config) == OT_ERROR_NONE) { otIp6Prefix &prefix = config.mPrefix; @@ -184,7 +182,7 @@ void Slaac::Update(UpdateMode aMode) { otLogInfoUtil("SLAAC: Removing address %s", slaacAddr->GetAddress().ToString().AsCString()); - netif.RemoveUnicastAddress(*slaacAddr); + Get().RemoveUnicastAddress(*slaacAddr); slaacAddr->mValid = false; } } @@ -196,7 +194,7 @@ void Slaac::Update(UpdateMode aMode) iterator = OT_NETWORK_DATA_ITERATOR_INIT; - while (networkData.GetNextOnMeshPrefix(&iterator, &config) == OT_ERROR_NONE) + while (Get().GetNextOnMeshPrefix(&iterator, &config) == OT_ERROR_NONE) { otIp6Prefix &prefix = config.mPrefix; @@ -207,8 +205,8 @@ void Slaac::Update(UpdateMode aMode) found = false; - for (const Ip6::NetifUnicastAddress *netifAddr = netif.GetUnicastAddresses(); netifAddr != NULL; - netifAddr = netifAddr->GetNext()) + for (const Ip6::NetifUnicastAddress *netifAddr = Get().GetUnicastAddresses(); + netifAddr != NULL; netifAddr = netifAddr->GetNext()) { if ((netifAddr->mPrefixLength == prefix.mLength) && (netifAddr->GetAddress().PrefixMatch(prefix.mPrefix) >= prefix.mLength)) @@ -240,7 +238,7 @@ void Slaac::Update(UpdateMode aMode) otLogInfoUtil("SLAAC: Adding address %s", slaacAddr->GetAddress().ToString().AsCString()); - netif.AddUnicastAddress(*slaacAddr); + Get().AddUnicastAddress(*slaacAddr); added = true; break; @@ -311,10 +309,9 @@ exit: void Slaac::GetIidSecretKey(IidSecretKey &aKey) const { - otError error; - Settings &settings = GetInstance().GetSettings(); + otError error; - error = settings.ReadSlaacIidSecretKey(aKey); + error = Get().ReadSlaacIidSecretKey(aKey); VerifyOrExit(error != OT_ERROR_NONE); // If there is no previously saved secret key, generate @@ -327,7 +324,7 @@ void Slaac::GetIidSecretKey(IidSecretKey &aKey) const Random::FillBuffer(aKey.m8, sizeof(IidSecretKey)); } - settings.SaveSlaacIidSecretKey(aKey); + Get().SaveSlaacIidSecretKey(aKey); otLogInfoUtil("SLAAC: Generated and saved secret key"); diff --git a/src/ncp/ncp_base.cpp b/src/ncp/ncp_base.cpp index 016e92d3f..1901876a9 100644 --- a/src/ncp/ncp_base.cpp +++ b/src/ncp/ncp_base.cpp @@ -291,7 +291,7 @@ NcpBase::NcpBase(Instance *aInstance) mUpdateChangedPropsTask.Post(); #if OPENTHREAD_ENABLE_VENDOR_EXTENSION - aInstance->GetExtension().SignalNcpInit(*this); + aInstance->Get().SignalNcpInit(*this); #endif } diff --git a/tests/unit/test_child.cpp b/tests/unit/test_child.cpp index 604a44a62..4fc3f88e5 100644 --- a/tests/unit/test_child.cpp +++ b/tests/unit/test_child.cpp @@ -88,7 +88,7 @@ void VerifyChildIp6Addresses(const Child &aChild, uint8_t aAddressListLength, co { VerifyOrQuit(addressObserved[index], "Child::GetNextIp6Address() missed an entry from the expected list\n"); - if (sInstance->GetThreadNetif().GetMle().IsMeshLocalAddress(aAddressList[index])) + if (sInstance->Get().IsMeshLocalAddress(aAddressList[index])) { SuccessOrQuit(aChild.GetMeshLocalIp6Address(*sInstance, address), "Child::GetMeshLocalIp6Address() failed\n"); @@ -127,7 +127,7 @@ void TestChildIp6Address(void) numAddresses = 0; // First addresses uses the mesh local prefix (mesh-local address). - addresses[numAddresses] = sInstance->GetThreadNetif().GetMle().GetMeshLocal64(); + addresses[numAddresses] = sInstance->Get().GetMeshLocal64(); addresses[numAddresses].SetIid(meshLocalIid); numAddresses++; diff --git a/tests/unit/test_lowpan.cpp b/tests/unit/test_lowpan.cpp index cff450dbf..0375f8baa 100644 --- a/tests/unit/test_lowpan.cpp +++ b/tests/unit/test_lowpan.cpp @@ -38,7 +38,6 @@ namespace ot { ot::Instance * sInstance; Ip6::Ip6 * sIp6; -ThreadNetif * sThreadNetif; Lowpan::Lowpan *sLowpan; void TestIphcVector::GetCompressedStream(uint8_t *aIphc, uint16_t &aIphcLength) @@ -110,7 +109,7 @@ void TestIphcVector::GetUncompressedStream(Message &aMessage) static void Init() { otMeshLocalPrefix meshLocalPrefix = {{0xfd, 0x00, 0xca, 0xfe, 0xfa, 0xce, 0x12, 0x34}}; - sThreadNetif->GetMle().SetMeshLocalPrefix(meshLocalPrefix); + sInstance->Get().SetMeshLocalPrefix(meshLocalPrefix); // Emulate global prefixes with contextes. uint8_t mockNetworkData[] = { @@ -128,12 +127,12 @@ static void Init() 0x02, 0x40 // Context ID = 2, C = FALSE }; - Message *message = sInstance->GetMessagePool().New(Message::kTypeIp6, 0); + Message *message = sInstance->Get().New(Message::kTypeIp6, 0); VerifyOrQuit(message != NULL, "6lo: Ip6::NewMessage failed"); SuccessOrQuit(message->Append(mockNetworkData, sizeof(mockNetworkData)), "6lo: Message::Append failed"); - sThreadNetif->GetNetworkDataLeader().SetNetworkData(0, 0, true, *message, 0); + sInstance->Get().SetNetworkData(0, 0, true, *message, 0); } /** @@ -180,7 +179,7 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) { Lowpan::BufferWriter buffer(result, 127); - VerifyOrQuit((message = sInstance->GetMessagePool().New(Message::kTypeIp6, 0)) != NULL, + VerifyOrQuit((message = sInstance->Get().New(Message::kTypeIp6, 0)) != NULL, "6lo: Ip6::NewMessage failed"); aVector.GetUncompressedStream(*message); @@ -210,7 +209,7 @@ static void Test(TestIphcVector &aVector, bool aCompress, bool aDecompress) if (aDecompress) { - VerifyOrQuit((message = sInstance->GetMessagePool().New(Message::kTypeIp6, 0)) != NULL, + VerifyOrQuit((message = sInstance->Get().New(Message::kTypeIp6, 0)) != NULL, "6lo: Ip6::NewMessage failed"); int decompressedBytes = @@ -1754,9 +1753,8 @@ void TestLowpanIphc(void) VerifyOrQuit(sInstance != NULL, "NULL instance"); - sIp6 = &sInstance->GetIp6(); - sThreadNetif = &sInstance->GetThreadNetif(); - sLowpan = &sThreadNetif->GetLowpan(); + sIp6 = &sInstance->Get(); + sLowpan = &sInstance->Get(); Init(); diff --git a/tests/unit/test_message.cpp b/tests/unit/test_message.cpp index f508f4ef5..080a542c6 100644 --- a/tests/unit/test_message.cpp +++ b/tests/unit/test_message.cpp @@ -45,7 +45,7 @@ void TestMessage(void) instance = static_cast(testInitInstance()); VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); - messagePool = &instance->GetMessagePool(); + messagePool = &instance->Get(); for (unsigned i = 0; i < sizeof(writeBuffer); i++) { diff --git a/tests/unit/test_message_queue.cpp b/tests/unit/test_message_queue.cpp index 4a99a5bae..3cd4da247 100644 --- a/tests/unit/test_message_queue.cpp +++ b/tests/unit/test_message_queue.cpp @@ -86,7 +86,7 @@ void TestMessageQueue(void) sInstance = testInitInstance(); VerifyOrQuit(sInstance != NULL, "Null instance"); - sMessagePool = &sInstance->GetMessagePool(); + sMessagePool = &sInstance->Get(); for (int i = 0; i < kNumTestMessages; i++) { diff --git a/tests/unit/test_ncp_buffer.cpp b/tests/unit/test_ncp_buffer.cpp index 3ab6e8230..d05ba5a6c 100644 --- a/tests/unit/test_ncp_buffer.cpp +++ b/tests/unit/test_ncp_buffer.cpp @@ -381,7 +381,7 @@ void TestNcpFrameBuffer(void) NcpFrameBuffer::WritePosition pos1, pos2; sInstance = testInitInstance(); - sMessagePool = &sInstance->GetMessagePool(); + sMessagePool = &sInstance->Get(); for (i = 0; i < sizeof(buffer); i++) { @@ -1006,7 +1006,7 @@ void TestFuzzNcpFrameBuffer(void) uint32_t lensArrayCount[kNumPrios]; sInstance = testInitInstance(); - sMessagePool = &sInstance->GetMessagePool(); + sMessagePool = &sInstance->Get(); memset(buffer, 0, sizeof(buffer)); diff --git a/tests/unit/test_priority_queue.cpp b/tests/unit/test_priority_queue.cpp index fc7cb05a8..1c1b5c806 100644 --- a/tests/unit/test_priority_queue.cpp +++ b/tests/unit/test_priority_queue.cpp @@ -220,7 +220,7 @@ void TestPriorityQueue(void) instance = testInitInstance(); VerifyOrQuit(instance != NULL, "Null OpenThread instance\n"); - messagePool = &instance->GetMessagePool(); + messagePool = &instance->Get(); // Use the function "New()" to allocate messages with different priorities for (int i = 0; i < kNumNewPriorityTestMessages; i++)