From 6153855ae06f95903177d040dfc6fff994faf505 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Tue, 21 Sep 2021 13:28:19 -0700 Subject: [PATCH] [cli] simplify generating output (adding `Output` & `OutputWrapper`) (#7012) This commit adds a new class `Cli::Output` which now includes all the simple `Output{Item}()` methods that are used by CLI and its sub-modules. It also adds new `Output` method flavors that output an item (e.g., an IPv6 address) with an appended newline at the end. These patterns are often used by CLI modules so having such new methods help simplify the code. The commit also adds `OutputWrapper` which is a wrapper over an `Output` instance providing similar methods. This class is used as the base class of different CLI sub-modules (e.g., `Cli::Dataset` or `Cli::Joiner`, etc.) which helps simplify their implementation (allow them to use the same set of `Output` helper methods as the ones used by the `Cli::Interpreter` class). --- Android.mk | 1 + src/cli/BUILD.gn | 2 + src/cli/CMakeLists.txt | 1 + src/cli/Makefile.am | 3 + src/cli/cli.cpp | 802 +++++++++++------------------------ src/cli/cli.hpp | 177 +------- src/cli/cli_coap.cpp | 122 +++--- src/cli/cli_coap.hpp | 16 +- src/cli/cli_coap_secure.cpp | 114 +++-- src/cli/cli_coap_secure.hpp | 16 +- src/cli/cli_commissioner.cpp | 60 ++- src/cli/cli_commissioner.hpp | 13 +- src/cli/cli_dataset.cpp | 140 +++--- src/cli/cli_dataset.hpp | 11 +- src/cli/cli_history.cpp | 112 +++-- src/cli/cli_history.hpp | 13 +- src/cli/cli_joiner.cpp | 21 +- src/cli/cli_joiner.hpp | 13 +- src/cli/cli_network_data.cpp | 76 ++-- src/cli/cli_network_data.hpp | 17 +- src/cli/cli_output.cpp | 360 ++++++++++++++++ src/cli/cli_output.hpp | 394 +++++++++++++++++ src/cli/cli_srp_client.cpp | 126 +++--- src/cli/cli_srp_client.hpp | 12 +- src/cli/cli_srp_server.cpp | 100 ++--- src/cli/cli_srp_server.hpp | 15 +- src/cli/cli_tcp.cpp | 50 ++- src/cli/cli_tcp.hpp | 13 +- src/cli/cli_udp.cpp | 30 +- src/cli/cli_udp.hpp | 11 +- src/cli/radio.cmake | 1 + 31 files changed, 1543 insertions(+), 1299 deletions(-) create mode 100644 src/cli/cli_output.cpp create mode 100644 src/cli/cli_output.hpp diff --git a/Android.mk b/Android.mk index a00dc6db8..decf9095d 100644 --- a/Android.mk +++ b/Android.mk @@ -508,6 +508,7 @@ LOCAL_SRC_FILES := \ src/cli/cli_history.cpp \ src/cli/cli_joiner.cpp \ src/cli/cli_network_data.cpp \ + src/cli/cli_output.cpp \ src/cli/cli_srp_client.cpp \ src/cli/cli_srp_server.cpp \ src/cli/cli_tcp.cpp \ diff --git a/src/cli/BUILD.gn b/src/cli/BUILD.gn index 4ead712c7..2d4e8f6a0 100644 --- a/src/cli/BUILD.gn +++ b/src/cli/BUILD.gn @@ -45,6 +45,8 @@ openthread_cli_sources = [ "cli_joiner.hpp", "cli_network_data.cpp", "cli_network_data.hpp", + "cli_output.cpp", + "cli_output.hpp", "cli_srp_client.cpp", "cli_srp_client.hpp", "cli_srp_server.cpp", diff --git a/src/cli/CMakeLists.txt b/src/cli/CMakeLists.txt index f3b12513d..67c8b01b8 100644 --- a/src/cli/CMakeLists.txt +++ b/src/cli/CMakeLists.txt @@ -40,6 +40,7 @@ set(COMMON_SOURCES cli_history.cpp cli_joiner.cpp cli_network_data.cpp + cli_output.cpp cli_srp_client.cpp cli_srp_server.cpp cli_tcp.cpp diff --git a/src/cli/Makefile.am b/src/cli/Makefile.am index 7ce34c8c8..f6e32d02d 100644 --- a/src/cli/Makefile.am +++ b/src/cli/Makefile.am @@ -160,6 +160,7 @@ SOURCES_COMMON = \ cli_history.cpp \ cli_joiner.cpp \ cli_network_data.cpp \ + cli_output.cpp \ cli_srp_client.cpp \ cli_srp_server.cpp \ cli_tcp.cpp \ @@ -176,6 +177,7 @@ libopenthread_cli_mtd_a_SOURCES = \ libopenthread_cli_radio_a_SOURCES = \ cli.cpp \ + cli_output.cpp \ $(NULL) noinst_HEADERS = \ @@ -188,6 +190,7 @@ noinst_HEADERS = \ cli_history.hpp \ cli_joiner.hpp \ cli_network_data.hpp \ + cli_output.hpp \ cli_srp_client.hpp \ cli_srp_server.hpp \ cli_tcp.hpp \ diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index c476fe320..3ded9fa02 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -99,9 +99,7 @@ Interpreter *Interpreter::sInterpreter = nullptr; static OT_DEFINE_ALIGNED_VAR(sInterpreterRaw, sizeof(Interpreter), uint64_t); Interpreter::Interpreter(Instance *aInstance, otCliOutputCallback aCallback, void *aContext) - : mInstance(aInstance) - , mOutputCallback(aCallback) - , mOutputContext(aContext) + : Output(aInstance, aCallback, aContext) , mUserCommands(nullptr) , mUserCommandsLength(0) , mCommandIsPending(false) @@ -137,17 +135,13 @@ Interpreter::Interpreter(Instance *aInstance, otCliOutputCallback aCallback, voi #if OPENTHREAD_CONFIG_HISTORY_TRACKER_ENABLE , mHistory(*this) #endif -#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - , mOutputLength(0) - , mIsLogging(false) -#endif #if OPENTHREAD_CONFIG_TMF_ANYCAST_LOCATOR_ENABLE , mLocateInProgress(false) #endif #endif // OPENTHREAD_FTD || OPENTHREAD_MTD { #if OPENTHREAD_FTD - otThreadSetDiscoveryRequestCallback(mInstance, &Interpreter::HandleDiscoveryRequest, this); + otThreadSetDiscoveryRequestCallback(GetInstancePtr(), &Interpreter::HandleDiscoveryRequest, this); #endif OutputPrompt(); @@ -176,14 +170,6 @@ exit: return; } -void Interpreter::OutputBytes(const uint8_t *aBytes, uint16_t aLength) -{ - for (uint16_t i = 0; i < aLength; i++) - { - OutputFormat("%02x", aBytes[i]); - } -} - const char *Interpreter::LinkModeToString(const otLinkModeConfig &aLinkMode, char (&aStringBuffer)[kLinkModeStringSize]) { char *flagsPtr = &aStringBuffer[0]; @@ -213,66 +199,6 @@ const char *Interpreter::LinkModeToString(const otLinkModeConfig &aLinkMode, cha return aStringBuffer; } -void Interpreter::OutputEnabledDisabledStatus(bool aEnabled) -{ - OutputLine(aEnabled ? "Enabled" : "Disabled"); -} - -#if OPENTHREAD_FTD || OPENTHREAD_MTD -int Interpreter::OutputIp6Address(const otIp6Address &aAddress) -{ - char string[OT_IP6_ADDRESS_STRING_SIZE]; - - otIp6AddressToString(&aAddress, string, sizeof(string)); - - return OutputFormat("%s", string); -} - -void Interpreter::OutputTableHeader(uint8_t aNumColumns, const char *const aTitles[], const uint8_t aWidths[]) -{ - for (uint8_t index = 0; index < aNumColumns; index++) - { - const char *title = aTitles[index]; - uint8_t width = aWidths[index]; - size_t titleLength = strlen(title); - - if (titleLength + 2 <= width) - { - // `title` fits in column width so we write it with extra space - // at beginning and end ("| Title |"). - - OutputFormat("| %*s", -static_cast(width - 1), title); - } - else - { - // Use narrow style (no space at beginning) and write as many - // chars from `title` as it can fit in the given column width - // ("|Title|"). - - OutputFormat("|%*.*s", -static_cast(width), width, title); - } - } - - OutputLine("|"); - OutputTableSeperator(aNumColumns, aWidths); -} - -void Interpreter::OutputTableSeperator(uint8_t aNumColumns, const uint8_t aWidths[]) -{ - for (uint8_t index = 0; index < aNumColumns; index++) - { - OutputFormat("+"); - - for (uint8_t width = aWidths[index]; width != 0; width--) - { - OutputFormat("-"); - } - } - - OutputLine("+"); -} -#endif // OPENTHREAD_FTD || OPENTHREAD_MTD - #if OPENTHREAD_CONFIG_DIAG_ENABLE otError Interpreter::ProcessDiag(Arg aArgs[]) { @@ -283,7 +209,7 @@ otError Interpreter::ProcessDiag(Arg aArgs[]) // all diagnostics related features are processed within diagnostics module Arg::CopyArgsToStringArray(aArgs, args); - error = otDiagProcessCmd(mInstance, Arg::GetArgsLength(aArgs), args, output, sizeof(output)); + error = otDiagProcessCmd(GetInstancePtr(), Arg::GetArgsLength(aArgs), args, output, sizeof(output)); OutputFormat("%s", output); @@ -335,7 +261,7 @@ otError Interpreter::ProcessReset(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otInstanceReset(mInstance); + otInstanceReset(GetInstancePtr()); return OT_ERROR_NONE; } @@ -362,7 +288,7 @@ void Interpreter::ProcessLine(char *aBuf) VerifyOrExit(!args[0].IsEmpty(), mCommandIsPending = false); #if OPENTHREAD_CONFIG_DIAG_ENABLE - if (otDiagIsEnabled(mInstance) && (args[0] != "diag")) + if (otDiagIsEnabled(GetInstancePtr()) && (args[0] != "diag")) { OutputLine("under diagnostics mode, execute 'diag stop' before running any other commands."); ExitNow(error = OT_ERROR_INVALID_STATE); @@ -524,13 +450,13 @@ otError Interpreter::ProcessBorderAgent(Arg aArgs[]) if (aArgs[0] == "port") { - OutputLine("%hu", otBorderAgentGetUdpPort(mInstance)); + OutputLine("%hu", otBorderAgentGetUdpPort(GetInstancePtr())); } else if (aArgs[0] == "state") { const char *state; - switch (otBorderAgentGetState(mInstance)) + switch (otBorderAgentGetState(GetInstancePtr())) { case OT_BORDER_AGENT_STATE_STOPPED: state = "Stopped"; @@ -565,23 +491,21 @@ otError Interpreter::ProcessBorderRouting(Arg aArgs[]) if (ParseEnableOrDisable(aArgs[0], enable) == OT_ERROR_NONE) { - SuccessOrExit(error = otBorderRoutingSetEnabled(mInstance, enable)); + SuccessOrExit(error = otBorderRoutingSetEnabled(GetInstancePtr(), enable)); } else if (aArgs[0] == "omrprefix") { otIp6Prefix omrPrefix; - SuccessOrExit(error = otBorderRoutingGetOmrPrefix(mInstance, &omrPrefix)); - OutputIp6Prefix(omrPrefix); - OutputLine(""); + SuccessOrExit(error = otBorderRoutingGetOmrPrefix(GetInstancePtr(), &omrPrefix)); + OutputIp6PrefixLine(omrPrefix); } else if (aArgs[0] == "onlinkprefix") { otIp6Prefix onLinkPrefix; - SuccessOrExit(error = otBorderRoutingGetOnLinkPrefix(mInstance, &onLinkPrefix)); - OutputIp6Prefix(onLinkPrefix); - OutputLine(""); + SuccessOrExit(error = otBorderRoutingGetOnLinkPrefix(GetInstancePtr(), &onLinkPrefix)); + OutputIp6PrefixLine(onLinkPrefix); } else { @@ -601,7 +525,7 @@ otError Interpreter::ProcessBackboneRouter(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - if (otBackboneRouterGetPrimary(mInstance, &config) == OT_ERROR_NONE) + if (otBackboneRouterGetPrimary(GetInstancePtr(), &config) == OT_ERROR_NONE) { OutputLine("BBR Primary:"); OutputLine("server16: 0x%04X", config.mServer16); @@ -641,7 +565,7 @@ otError Interpreter::ProcessBackboneRouter(Arg aArgs[]) VerifyOrExit(aArgs[4].IsEmpty(), error = OT_ERROR_INVALID_ARGS); } - otBackboneRouterConfigNextDuaRegistrationResponse(mInstance, mlIid, status); + otBackboneRouterConfigNextDuaRegistrationResponse(GetInstancePtr(), mlIid, status); ExitNow(); } #endif @@ -679,7 +603,7 @@ otError Interpreter::ProcessBackboneRouterMgmtMlr(Arg aArgs[]) #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE if (aArgs[1] == "clear") { - otBackboneRouterMulticastListenerClear(mInstance); + otBackboneRouterMulticastListenerClear(GetInstancePtr()); error = OT_ERROR_NONE; } else if (aArgs[1] == "add") @@ -695,7 +619,7 @@ otError Interpreter::ProcessBackboneRouterMgmtMlr(Arg aArgs[]) VerifyOrExit(aArgs[4].IsEmpty(), error = OT_ERROR_INVALID_ARGS); } - error = otBackboneRouterMulticastListenerAdd(mInstance, &address, timeout); + error = otBackboneRouterMulticastListenerAdd(GetInstancePtr(), &address, timeout); } } else if (aArgs[0] == "response") @@ -713,7 +637,7 @@ void Interpreter::PrintMulticastListenersTable(void) otBackboneRouterMulticastListenerIterator iter = OT_BACKBONE_ROUTER_MULTICAST_LISTENER_ITERATOR_INIT; otBackboneRouterMulticastListenerInfo listenerInfo; - while (otBackboneRouterMulticastListenerGetNext(mInstance, &iter, &listenerInfo) == OT_ERROR_NONE) + while (otBackboneRouterMulticastListenerGetNext(GetInstancePtr(), &iter, &listenerInfo) == OT_ERROR_NONE) { OutputIp6Address(listenerInfo.mAddress); OutputLine(" %u", listenerInfo.mTimeout); @@ -730,7 +654,7 @@ otError Interpreter::ProcessBackboneRouterLocal(Arg aArgs[]) if (ParseEnableOrDisable(aArgs[0], enable) == OT_ERROR_NONE) { - otBackboneRouterSetEnabled(mInstance, enable); + otBackboneRouterSetEnabled(GetInstancePtr(), enable); } else if (aArgs[0] == "jitter") { @@ -738,11 +662,11 @@ otError Interpreter::ProcessBackboneRouterLocal(Arg aArgs[]) } else if (aArgs[0] == "register") { - SuccessOrExit(error = otBackboneRouterRegister(mInstance)); + SuccessOrExit(error = otBackboneRouterRegister(GetInstancePtr())); } else if (aArgs[0] == "state") { - switch (otBackboneRouterGetState(mInstance)) + switch (otBackboneRouterGetState(GetInstancePtr())) { case OT_BACKBONE_ROUTER_STATE_DISABLED: OutputLine("Disabled"); @@ -757,7 +681,7 @@ otError Interpreter::ProcessBackboneRouterLocal(Arg aArgs[]) } else if (aArgs[0] == "config") { - otBackboneRouterGetConfig(mInstance, &config); + otBackboneRouterGetConfig(GetInstancePtr(), &config); if (aArgs[1].IsEmpty()) { @@ -791,7 +715,7 @@ otError Interpreter::ProcessBackboneRouterLocal(Arg aArgs[]) } } - SuccessOrExit(error = otBackboneRouterSetConfig(mInstance, &config)); + SuccessOrExit(error = otBackboneRouterSetConfig(GetInstancePtr(), &config)); } } else @@ -810,11 +734,11 @@ otError Interpreter::ProcessDomainName(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("%s", otThreadGetDomainName(mInstance)); + OutputLine("%s", otThreadGetDomainName(GetInstancePtr())); } else { - SuccessOrExit(error = otThreadSetDomainName(mInstance, aArgs[0].GetCString())); + SuccessOrExit(error = otThreadSetDomainName(GetInstancePtr(), aArgs[0].GetCString())); } exit: @@ -830,24 +754,23 @@ otError Interpreter::ProcessDua(Arg aArgs[]) { if (aArgs[1].IsEmpty()) { - const otIp6InterfaceIdentifier *iid = otThreadGetFixedDuaInterfaceIdentifier(mInstance); + const otIp6InterfaceIdentifier *iid = otThreadGetFixedDuaInterfaceIdentifier(GetInstancePtr()); if (iid != nullptr) { - OutputBytes(iid->mFields.m8); - OutputLine(""); + OutputBytesLine(iid->mFields.m8); } } else if (aArgs[1] == "clear") { - error = otThreadSetFixedDuaInterfaceIdentifier(mInstance, nullptr); + error = otThreadSetFixedDuaInterfaceIdentifier(GetInstancePtr(), nullptr); } else { otIp6InterfaceIdentifier iid; SuccessOrExit(error = aArgs[1].ParseAsHexString(iid.mFields.m8)); - error = otThreadSetFixedDuaInterfaceIdentifier(mInstance, &iid); + error = otThreadSetFixedDuaInterfaceIdentifier(GetInstancePtr(), &iid); } } else @@ -887,7 +810,7 @@ otError Interpreter::ProcessBufferInfo(Arg aArgs[]) otBufferInfo bufferInfo; - otMessageGetBufferInfo(mInstance, &bufferInfo); + otMessageGetBufferInfo(GetInstancePtr(), &bufferInfo); OutputLine("total: %d", bufferInfo.mTotalBuffers); OutputLine("free: %d", bufferInfo.mFreeBuffers); @@ -907,13 +830,13 @@ otError Interpreter::ProcessCcaThreshold(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - SuccessOrExit(error = otPlatRadioGetCcaEnergyDetectThreshold(mInstance, &cca)); + SuccessOrExit(error = otPlatRadioGetCcaEnergyDetectThreshold(GetInstancePtr(), &cca)); OutputLine("%d dBm", cca); } else { SuccessOrExit(error = aArgs[0].ParseAsInt8(cca)); - error = otPlatRadioSetCcaEnergyDetectThreshold(mInstance, cca); + error = otPlatRadioSetCcaEnergyDetectThreshold(GetInstancePtr(), cca); } exit: @@ -926,27 +849,27 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) if (aArgs[0] == "supported") { - OutputLine("0x%x", otPlatRadioGetSupportedChannelMask(mInstance)); + OutputLine("0x%x", otPlatRadioGetSupportedChannelMask(GetInstancePtr())); } else if (aArgs[0] == "preferred") { - OutputLine("0x%x", otPlatRadioGetPreferredChannelMask(mInstance)); + OutputLine("0x%x", otPlatRadioGetPreferredChannelMask(GetInstancePtr())); } #if OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE else if (aArgs[0] == "monitor") { if (aArgs[1].IsEmpty()) { - OutputLine("enabled: %d", otChannelMonitorIsEnabled(mInstance)); - if (otChannelMonitorIsEnabled(mInstance)) + OutputLine("enabled: %d", otChannelMonitorIsEnabled(GetInstancePtr())); + if (otChannelMonitorIsEnabled(GetInstancePtr())) { - uint32_t channelMask = otLinkGetSupportedChannelMask(mInstance); + uint32_t channelMask = otLinkGetSupportedChannelMask(GetInstancePtr()); uint8_t channelNum = sizeof(channelMask) * CHAR_BIT; - OutputLine("interval: %u", otChannelMonitorGetSampleInterval(mInstance)); - OutputLine("threshold: %d", otChannelMonitorGetRssiThreshold(mInstance)); - OutputLine("window: %u", otChannelMonitorGetSampleWindow(mInstance)); - OutputLine("count: %u", otChannelMonitorGetSampleCount(mInstance)); + OutputLine("interval: %u", otChannelMonitorGetSampleInterval(GetInstancePtr())); + OutputLine("threshold: %d", otChannelMonitorGetRssiThreshold(GetInstancePtr())); + OutputLine("window: %u", otChannelMonitorGetSampleWindow(GetInstancePtr())); + OutputLine("count: %u", otChannelMonitorGetSampleCount(GetInstancePtr())); OutputLine("occupancies:"); for (uint8_t channel = 0; channel < channelNum; channel++) @@ -958,7 +881,7 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) continue; } - occupancy = otChannelMonitorGetChannelOccupancy(mInstance, channel); + occupancy = otChannelMonitorGetChannelOccupancy(GetInstancePtr(), channel); OutputFormat("ch %d (0x%04x) ", channel, occupancy); occupancy = (occupancy * 10000) / 0xffff; @@ -969,11 +892,11 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) } else if (aArgs[1] == "start") { - error = otChannelMonitorSetEnabled(mInstance, true); + error = otChannelMonitorSetEnabled(GetInstancePtr(), true); } else if (aArgs[1] == "stop") { - error = otChannelMonitorSetEnabled(mInstance, false); + error = otChannelMonitorSetEnabled(GetInstancePtr(), false); } else { @@ -986,17 +909,17 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) { if (aArgs[1].IsEmpty()) { - OutputLine("channel: %d", otChannelManagerGetRequestedChannel(mInstance)); - OutputLine("auto: %d", otChannelManagerGetAutoChannelSelectionEnabled(mInstance)); + OutputLine("channel: %d", otChannelManagerGetRequestedChannel(GetInstancePtr())); + OutputLine("auto: %d", otChannelManagerGetAutoChannelSelectionEnabled(GetInstancePtr())); - if (otChannelManagerGetAutoChannelSelectionEnabled(mInstance)) + if (otChannelManagerGetAutoChannelSelectionEnabled(GetInstancePtr())) { - Mac::ChannelMask supportedMask(otChannelManagerGetSupportedChannels(mInstance)); - Mac::ChannelMask favoredMask(otChannelManagerGetFavoredChannels(mInstance)); + Mac::ChannelMask supportedMask(otChannelManagerGetSupportedChannels(GetInstancePtr())); + Mac::ChannelMask favoredMask(otChannelManagerGetFavoredChannels(GetInstancePtr())); - OutputLine("delay: %d", otChannelManagerGetDelay(mInstance)); - OutputLine("interval: %u", otChannelManagerGetAutoChannelSelectionInterval(mInstance)); - OutputLine("cca threshold: 0x%04x", otChannelManagerGetCcaFailureRateThreshold(mInstance)); + OutputLine("delay: %d", otChannelManagerGetDelay(GetInstancePtr())); + OutputLine("interval: %u", otChannelManagerGetAutoChannelSelectionInterval(GetInstancePtr())); + OutputLine("cca threshold: 0x%04x", otChannelManagerGetCcaFailureRateThreshold(GetInstancePtr())); OutputLine("supported: %s", supportedMask.ToString().AsCString()); OutputLine("favored: %s", supportedMask.ToString().AsCString()); } @@ -1011,7 +934,7 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) bool enable; SuccessOrExit(error = aArgs[2].ParseAsBool(enable)); - error = otChannelManagerRequestChannelSelect(mInstance, enable); + error = otChannelManagerRequestChannelSelect(GetInstancePtr(), enable); } #endif else if (aArgs[1] == "auto") @@ -1019,7 +942,7 @@ otError Interpreter::ProcessChannel(Arg aArgs[]) bool enable; SuccessOrExit(error = aArgs[2].ParseAsBool(enable)); - otChannelManagerSetAutoChannelSelectionEnabled(mInstance, enable); + otChannelManagerSetAutoChannelSelectionEnabled(GetInstancePtr(), enable); } else if (aArgs[1] == "delay") { @@ -1086,11 +1009,12 @@ otError Interpreter::ProcessChild(Arg aArgs[]) OutputTableHeader(kChildTableTitles, kChildTableColumnWidths); } - maxChildren = otThreadGetMaxAllowedChildren(mInstance); + maxChildren = otThreadGetMaxAllowedChildren(GetInstancePtr()); for (uint16_t i = 0; i < maxChildren; i++) { - if ((otThreadGetChildInfoByIndex(mInstance, i, &childInfo) != OT_ERROR_NONE) || childInfo.mIsStateRestoring) + if ((otThreadGetChildInfoByIndex(GetInstancePtr(), i, &childInfo) != OT_ERROR_NONE) || + childInfo.mIsStateRestoring) { continue; } @@ -1124,13 +1048,12 @@ otError Interpreter::ProcessChild(Arg aArgs[]) } SuccessOrExit(error = aArgs[0].ParseAsUint16(childId)); - SuccessOrExit(error = otThreadGetChildInfoById(mInstance, childId, &childInfo)); + SuccessOrExit(error = otThreadGetChildInfoById(GetInstancePtr(), childId, &childInfo)); OutputLine("Child ID: %d", childInfo.mChildId); OutputLine("Rloc: %04x", childInfo.mRloc16); OutputFormat("Ext Addr: "); - OutputExtAddress(childInfo.mExtAddress); - OutputLine(""); + OutputExtAddressLine(childInfo.mExtAddress); linkMode.mRxOnWhenIdle = childInfo.mRxOnWhenIdle; linkMode.mDeviceType = childInfo.mFullThreadDevice; linkMode.mNetworkData = childInfo.mFullThreadDevice; @@ -1151,7 +1074,7 @@ otError Interpreter::ProcessChildIp(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - uint16_t maxChildren = otThreadGetMaxAllowedChildren(mInstance); + uint16_t maxChildren = otThreadGetMaxAllowedChildren(GetInstancePtr()); for (uint16_t childIndex = 0; childIndex < maxChildren; childIndex++) { @@ -1159,7 +1082,7 @@ otError Interpreter::ProcessChildIp(Arg aArgs[]) otIp6Address ip6Address; otChildInfo childInfo; - if ((otThreadGetChildInfoByIndex(mInstance, childIndex, &childInfo) != OT_ERROR_NONE) || + if ((otThreadGetChildInfoByIndex(GetInstancePtr(), childIndex, &childInfo) != OT_ERROR_NONE) || childInfo.mIsStateRestoring) { continue; @@ -1167,11 +1090,11 @@ otError Interpreter::ProcessChildIp(Arg aArgs[]) iterator = OT_CHILD_IP6_ADDRESS_ITERATOR_INIT; - while (otThreadGetChildNextIp6Address(mInstance, childIndex, &iterator, &ip6Address) == OT_ERROR_NONE) + while (otThreadGetChildNextIp6Address(GetInstancePtr(), childIndex, &iterator, &ip6Address) == + OT_ERROR_NONE) { OutputFormat("%04x: ", childInfo.mRloc16); - OutputIp6Address(ip6Address); - OutputLine(""); + OutputIp6AddressLine(ip6Address); } } } @@ -1244,11 +1167,11 @@ otError Interpreter::ProcessCoexMetrics(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputEnabledDisabledStatus(otPlatRadioIsCoexEnabled(mInstance)); + OutputEnabledDisabledStatus(otPlatRadioIsCoexEnabled(GetInstancePtr())); } else if (ParseEnableOrDisable(aArgs[0], enable) == OT_ERROR_NONE) { - error = otPlatRadioSetCoexEnabled(mInstance, enable); + error = otPlatRadioSetCoexEnabled(GetInstancePtr(), enable); } else if (aArgs[0] == "metrics") { @@ -1283,7 +1206,7 @@ otError Interpreter::ProcessCoexMetrics(Arg aArgs[]) otRadioCoexMetrics metrics; - SuccessOrExit(error = otPlatRadioGetCoexMetrics(mInstance, &metrics)); + SuccessOrExit(error = otPlatRadioGetCoexMetrics(GetInstancePtr(), &metrics)); OutputLine("Stopped: %s", metrics.mStopped ? "true" : "false"); OutputLine("Grant Glitch: %u", metrics.mNumGrantGlitch); @@ -1373,7 +1296,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) {&otMacCounters::mRxErrOther, "RxErrOther"}, }; - const otMacCounters *macCounters = otLinkGetCounters(mInstance); + const otMacCounters *macCounters = otLinkGetCounters(GetInstancePtr()); OutputLine("TxTotal: %d", macCounters->mTxTotal); @@ -1391,7 +1314,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) } else if ((aArgs[1] == "reset") && aArgs[2].IsEmpty()) { - otLinkResetCounters(mInstance); + otLinkResetCounters(GetInstancePtr()); } else { @@ -1420,7 +1343,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) {&otMleCounters::mParentChanges, "Parent Changes"}, }; - const otMleCounters *mleCounters = otThreadGetMleCounters(mInstance); + const otMleCounters *mleCounters = otThreadGetMleCounters(GetInstancePtr()); for (const MleCounterName &counter : kCounterNames) { @@ -1429,7 +1352,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) } else if ((aArgs[1] == "reset") && aArgs[2].IsEmpty()) { - otThreadResetMleCounters(mInstance); + otThreadResetMleCounters(GetInstancePtr()); } else { @@ -1453,7 +1376,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) {&otIpCounters::mRxFailure, "RxFailed"}, }; - const otIpCounters *ipCounters = otThreadGetIp6Counters(mInstance); + const otIpCounters *ipCounters = otThreadGetIp6Counters(GetInstancePtr()); for (const IpCounterName &counter : kCounterNames) { @@ -1462,7 +1385,7 @@ otError Interpreter::ProcessCounters(Arg aArgs[]) } else if ((aArgs[1] == "reset") && aArgs[2].IsEmpty()) { - otThreadResetIp6Counters(mInstance); + otThreadResetIp6Counters(GetInstancePtr()); } else { @@ -1486,10 +1409,10 @@ otError Interpreter::ProcessCsl(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("Channel: %u", otLinkCslGetChannel(mInstance)); - OutputLine("Period: %u(in units of 10 symbols), %ums", otLinkCslGetPeriod(mInstance), - otLinkCslGetPeriod(mInstance) * kUsPerTenSymbols / 1000); - OutputLine("Timeout: %us", otLinkCslGetTimeout(mInstance)); + OutputLine("Channel: %u", otLinkCslGetChannel(GetInstancePtr())); + OutputLine("Period: %u(in units of 10 symbols), %ums", otLinkCslGetPeriod(GetInstancePtr()), + otLinkCslGetPeriod(GetInstancePtr()) * kUsPerTenSymbols / 1000); + OutputLine("Timeout: %us", otLinkCslGetTimeout(GetInstancePtr())); } else if (aArgs[0] == "channel") { @@ -1519,13 +1442,13 @@ otError Interpreter::ProcessDelayTimerMin(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("%d", (otDatasetGetDelayTimerMinimal(mInstance) / 1000)); + OutputLine("%d", (otDatasetGetDelayTimerMinimal(GetInstancePtr()) / 1000)); } else if (aArgs[1].IsEmpty()) { uint32_t delay; SuccessOrExit(error = aArgs[0].ParseAsUint32(delay)); - SuccessOrExit(error = otDatasetSetDelayTimerMinimal(mInstance, static_cast(delay * 1000))); + SuccessOrExit(error = otDatasetSetDelayTimerMinimal(GetInstancePtr(), static_cast(delay * 1000))); } else { @@ -1551,7 +1474,7 @@ otError Interpreter::ProcessDiscover(Arg aArgs[]) scanChannels = 1 << channel; } - SuccessOrExit(error = otThreadDiscover(mInstance, scanChannels, OT_PANID_BROADCAST, false, false, + SuccessOrExit(error = otThreadDiscover(GetInstancePtr(), scanChannels, OT_PANID_BROADCAST, false, false, &Interpreter::HandleActiveScanResult, this)); OutputScanTableHeader(); @@ -1562,51 +1485,6 @@ exit: return error; } -void Interpreter::OutputDnsTxtData(const uint8_t *aTxtData, uint16_t aTxtDataLength) -{ - otDnsTxtEntry entry; - otDnsTxtEntryIterator iterator; - bool isFirst = true; - - otDnsInitTxtEntryIterator(&iterator, aTxtData, aTxtDataLength); - - OutputFormat("["); - - while (otDnsGetNextTxtEntry(&iterator, &entry) == OT_ERROR_NONE) - { - if (!isFirst) - { - OutputFormat(", "); - } - - if (entry.mKey == nullptr) - { - // A null `mKey` indicates that the key in the entry is - // longer than the recommended max key length, so the entry - // could not be parsed. In this case, the whole entry is - // returned encoded in `mValue`. - - OutputFormat("["); - OutputBytes(entry.mValue, entry.mValueLength); - OutputFormat("]"); - } - else - { - OutputFormat("%s", entry.mKey); - - if (entry.mValue != nullptr) - { - OutputFormat("="); - OutputBytes(entry.mValue, entry.mValueLength); - } - } - - isFirst = false; - } - - OutputFormat("]"); -} - otError Interpreter::ProcessDns(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); @@ -1642,7 +1520,7 @@ otError Interpreter::ProcessDns(Arg aArgs[]) { if (aArgs[1].IsEmpty()) { - const otDnsQueryConfig *defaultConfig = otDnsClientGetDefaultConfig(mInstance); + const otDnsQueryConfig *defaultConfig = otDnsClientGetDefaultConfig(GetInstancePtr()); OutputFormat("Server: ["); OutputIp6Address(defaultConfig->mServerSockAddr.mAddress); @@ -1655,14 +1533,14 @@ otError Interpreter::ProcessDns(Arg aArgs[]) else { SuccessOrExit(error = GetDnsConfig(aArgs + 1, config)); - otDnsClientSetDefaultConfig(mInstance, config); + otDnsClientSetDefaultConfig(GetInstancePtr(), config); } } else if (aArgs[0] == "resolve") { VerifyOrExit(!aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(error = GetDnsConfig(aArgs + 2, config)); - SuccessOrExit(error = otDnsClientResolveAddress(mInstance, aArgs[1].GetCString(), + SuccessOrExit(error = otDnsClientResolveAddress(GetInstancePtr(), aArgs[1].GetCString(), &Interpreter::HandleDnsAddressResponse, this, config)); error = OT_ERROR_PENDING; } @@ -1671,15 +1549,15 @@ otError Interpreter::ProcessDns(Arg aArgs[]) { VerifyOrExit(!aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(error = GetDnsConfig(aArgs + 2, config)); - SuccessOrExit(error = otDnsClientBrowse(mInstance, aArgs[1].GetCString(), &Interpreter::HandleDnsBrowseResponse, - this, config)); + SuccessOrExit(error = otDnsClientBrowse(GetInstancePtr(), aArgs[1].GetCString(), + &Interpreter::HandleDnsBrowseResponse, this, config)); error = OT_ERROR_PENDING; } else if (aArgs[0] == "service") { VerifyOrExit(!aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(error = GetDnsConfig(aArgs + 3, config)); - SuccessOrExit(error = otDnsClientResolveService(mInstance, aArgs[1].GetCString(), aArgs[2].GetCString(), + SuccessOrExit(error = otDnsClientResolveService(GetInstancePtr(), aArgs[1].GetCString(), aArgs[2].GetCString(), &Interpreter::HandleDnsServiceResponse, this, config)); error = OT_ERROR_PENDING; } @@ -1904,7 +1782,7 @@ otError Interpreter::ProcessEidCache(Arg aArgs[]) for (uint8_t i = 0;; i++) { - SuccessOrExit(otThreadGetNextCacheEntry(mInstance, &entry, &iterator)); + SuccessOrExit(otThreadGetNextCacheEntry(GetInstancePtr(), &entry, &iterator)); OutputEidCacheEntry(entry); } @@ -1922,9 +1800,8 @@ otError Interpreter::ProcessEui64(Arg aArgs[]) VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otLinkGetFactoryAssignedIeeeEui64(mInstance, &extAddress); - OutputExtAddress(extAddress); - OutputLine(""); + otLinkGetFactoryAssignedIeeeEui64(GetInstancePtr(), &extAddress); + OutputExtAddressLine(extAddress); exit: return error; @@ -1936,15 +1813,14 @@ otError Interpreter::ProcessExtAddress(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputExtAddress(*otLinkGetExtendedAddress(mInstance)); - OutputLine(""); + OutputExtAddressLine(*otLinkGetExtendedAddress(GetInstancePtr())); } else { otExtAddress extAddress; SuccessOrExit(error = aArgs[0].ParseAsHexString(extAddress.m8)); - error = otLinkSetExtendedAddress(mInstance, &extAddress); + error = otLinkSetExtendedAddress(GetInstancePtr(), &extAddress); } exit: @@ -1996,15 +1872,14 @@ otError Interpreter::ProcessExtPanId(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputBytes(otThreadGetExtendedPanId(mInstance)->m8); - OutputLine(""); + OutputBytesLine(otThreadGetExtendedPanId(GetInstancePtr())->m8); } else { otExtendedPanId extPanId; SuccessOrExit(error = aArgs[0].ParseAsHexString(extPanId.m8)); - error = otThreadSetExtendedPanId(mInstance, &extPanId); + error = otThreadSetExtendedPanId(GetInstancePtr(), &extPanId); } exit: @@ -2015,7 +1890,7 @@ otError Interpreter::ProcessFactoryReset(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otInstanceFactoryReset(mInstance); + otInstanceFactoryReset(GetInstancePtr()); return OT_ERROR_NONE; } @@ -2033,7 +1908,7 @@ otError Interpreter::ProcessFake(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsIp6Address(destination)); SuccessOrExit(error = aArgs[2].ParseAsIp6Address(target)); SuccessOrExit(error = aArgs[3].ParseAsHexString(mlIid.mFields.m8)); - otThreadSendAddressNotification(mInstance, &destination, &target, &mlIid); + otThreadSendAddressNotification(GetInstancePtr(), &destination, &target, &mlIid); } #if OPENTHREAD_CONFIG_BACKBONE_ROUTER_DUA_NDPROXYING_ENABLE else if (aArgs[0] == "/b/ba") @@ -2046,7 +1921,7 @@ otError Interpreter::ProcessFake(Arg aArgs[]) SuccessOrExit(error = aArgs[2].ParseAsHexString(mlIid.mFields.m8)); SuccessOrExit(error = aArgs[3].ParseAsUint32(timeSinceLastTransaction)); - error = otThreadSendProactiveBackboneNotification(mInstance, &target, &mlIid, timeSinceLastTransaction); + error = otThreadSendProactiveBackboneNotification(GetInstancePtr(), &target, &mlIid, timeSinceLastTransaction); } #endif @@ -2063,7 +1938,7 @@ otError Interpreter::ProcessFem(Arg aArgs[]) { int8_t lnaGain; - SuccessOrExit(error = otPlatRadioGetFemLnaGain(mInstance, &lnaGain)); + SuccessOrExit(error = otPlatRadioGetFemLnaGain(GetInstancePtr(), &lnaGain)); OutputLine("LNA gain %d dBm", lnaGain); } else if (aArgs[0] == "lnagain") @@ -2072,7 +1947,7 @@ otError Interpreter::ProcessFem(Arg aArgs[]) { int8_t lnaGain; - SuccessOrExit(error = otPlatRadioGetFemLnaGain(mInstance, &lnaGain)); + SuccessOrExit(error = otPlatRadioGetFemLnaGain(GetInstancePtr(), &lnaGain)); OutputLine("%d", lnaGain); } else @@ -2080,7 +1955,7 @@ otError Interpreter::ProcessFem(Arg aArgs[]) int8_t lnaGain; SuccessOrExit(error = aArgs[1].ParseAsInt8(lnaGain)); - SuccessOrExit(error = otPlatRadioSetFemLnaGain(mInstance, lnaGain)); + SuccessOrExit(error = otPlatRadioSetFemLnaGain(GetInstancePtr(), lnaGain)); } } else @@ -2098,7 +1973,7 @@ otError Interpreter::ProcessIfconfig(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - if (otIp6IsEnabled(mInstance)) + if (otIp6IsEnabled(GetInstancePtr())) { OutputLine("up"); } @@ -2109,11 +1984,11 @@ otError Interpreter::ProcessIfconfig(Arg aArgs[]) } else if (aArgs[0] == "up") { - SuccessOrExit(error = otIp6SetEnabled(mInstance, true)); + SuccessOrExit(error = otIp6SetEnabled(GetInstancePtr(), true)); } else if (aArgs[0] == "down") { - SuccessOrExit(error = otIp6SetEnabled(mInstance, false)); + SuccessOrExit(error = otIp6SetEnabled(GetInstancePtr(), false)); } else { @@ -2135,7 +2010,7 @@ otError Interpreter::ProcessIpAddrAdd(Arg aArgs[]) aAddress.mValid = true; aAddress.mAddressOrigin = OT_ADDRESS_ORIGIN_MANUAL; - error = otIp6AddUnicastAddress(mInstance, &aAddress); + error = otIp6AddUnicastAddress(GetInstancePtr(), &aAddress); exit: return error; @@ -2147,7 +2022,7 @@ otError Interpreter::ProcessIpAddrDel(Arg aArgs[]) otIp6Address address; SuccessOrExit(error = aArgs[0].ParseAsIp6Address(address)); - error = otIp6RemoveUnicastAddress(mInstance, &address); + error = otIp6RemoveUnicastAddress(GetInstancePtr(), &address); exit: return error; @@ -2159,12 +2034,11 @@ otError Interpreter::ProcessIpAddr(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - const otNetifAddress *unicastAddrs = otIp6GetUnicastAddresses(mInstance); + const otNetifAddress *unicastAddrs = otIp6GetUnicastAddresses(GetInstancePtr()); for (const otNetifAddress *addr = unicastAddrs; addr; addr = addr->mNext) { - OutputIp6Address(addr->mAddress); - OutputLine(""); + OutputIp6AddressLine(addr->mAddress); } } else @@ -2179,18 +2053,15 @@ otError Interpreter::ProcessIpAddr(Arg aArgs[]) } else if (aArgs[0] == "linklocal") { - OutputIp6Address(*otThreadGetLinkLocalIp6Address(mInstance)); - OutputLine(""); + OutputIp6AddressLine(*otThreadGetLinkLocalIp6Address(GetInstancePtr())); } else if (aArgs[0] == "rloc") { - OutputIp6Address(*otThreadGetRloc(mInstance)); - OutputLine(""); + OutputIp6AddressLine(*otThreadGetRloc(GetInstancePtr())); } else if (aArgs[0] == "mleid") { - OutputIp6Address(*otThreadGetMeshLocalEid(mInstance)); - OutputLine(""); + OutputIp6AddressLine(*otThreadGetMeshLocalEid(GetInstancePtr())); } else { @@ -2208,7 +2079,7 @@ otError Interpreter::ProcessIpMulticastAddrAdd(Arg aArgs[]) otIp6Address address; SuccessOrExit(error = aArgs[0].ParseAsIp6Address(address)); - error = otIp6SubscribeMulticastAddress(mInstance, &address); + error = otIp6SubscribeMulticastAddress(GetInstancePtr(), &address); exit: return error; @@ -2220,7 +2091,7 @@ otError Interpreter::ProcessIpMulticastAddrDel(Arg aArgs[]) otIp6Address address; SuccessOrExit(error = aArgs[0].ParseAsIp6Address(address)); - error = otIp6UnsubscribeMulticastAddress(mInstance, &address); + error = otIp6UnsubscribeMulticastAddress(GetInstancePtr(), &address); exit: return error; @@ -2232,14 +2103,14 @@ otError Interpreter::ProcessMulticastPromiscuous(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputEnabledDisabledStatus(otIp6IsMulticastPromiscuousEnabled(mInstance)); + OutputEnabledDisabledStatus(otIp6IsMulticastPromiscuousEnabled(GetInstancePtr())); } else { bool enable; SuccessOrExit(error = ParseEnableOrDisable(aArgs[0], enable)); - otIp6SetMulticastPromiscuousEnabled(mInstance, enable); + otIp6SetMulticastPromiscuousEnabled(GetInstancePtr(), enable); } exit: @@ -2252,10 +2123,10 @@ otError Interpreter::ProcessIpMulticastAddr(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - for (const otNetifMulticastAddress *addr = otIp6GetMulticastAddresses(mInstance); addr; addr = addr->mNext) + for (const otNetifMulticastAddress *addr = otIp6GetMulticastAddresses(GetInstancePtr()); addr; + addr = addr->mNext) { - OutputIp6Address(addr->mAddress); - OutputLine(""); + OutputIp6AddressLine(addr->mAddress); } } else @@ -2274,13 +2145,11 @@ otError Interpreter::ProcessIpMulticastAddr(Arg aArgs[]) } else if (aArgs[0] == "llatn") { - OutputIp6Address(*otThreadGetLinkLocalAllThreadNodesMulticastAddress(mInstance)); - OutputLine(""); + OutputIp6AddressLine(*otThreadGetLinkLocalAllThreadNodesMulticastAddress(GetInstancePtr())); } else if (aArgs[0] == "rlatn") { - OutputIp6Address(*otThreadGetRealmLocalAllThreadNodesMulticastAddress(mInstance)); - OutputLine(""); + OutputIp6AddressLine(*otThreadGetRealmLocalAllThreadNodesMulticastAddress(GetInstancePtr())); } else { @@ -2315,7 +2184,7 @@ otError Interpreter::ProcessLeaderData(Arg aArgs[]) otError error; otLeaderData leaderData; - SuccessOrExit(error = otThreadGetLeaderData(mInstance, &leaderData)); + SuccessOrExit(error = otThreadGetLeaderData(GetInstancePtr(), &leaderData)); OutputLine("Partition ID: %u", leaderData.mPartitionId); OutputLine("Weighting: %d", leaderData.mWeighting); @@ -2334,7 +2203,7 @@ otError Interpreter::ProcessPartitionId(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("%u", otThreadGetPartitionId(mInstance)); + OutputLine("%u", otThreadGetPartitionId(GetInstancePtr())); error = OT_ERROR_NONE; } #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE @@ -2393,8 +2262,7 @@ void Interpreter::HandleLinkMetricsReport(const otIp6Address * aAddress, uint8_t aStatus) { OutputFormat("Received Link Metrics Report from: "); - OutputIp6Address(*aAddress); - OutputLine(""); + OutputIp6AddressLine(*aAddress); if (aMetricsValues != nullptr) { @@ -2414,8 +2282,7 @@ void Interpreter::HandleLinkMetricsMgmtResponse(const otIp6Address *aAddress, ui void Interpreter::HandleLinkMetricsMgmtResponse(const otIp6Address *aAddress, uint8_t aStatus) { OutputFormat("Received Link Metrics Management Response from: "); - OutputIp6Address(*aAddress); - OutputLine(""); + OutputIp6AddressLine(*aAddress); OutputLine("Status: %s", LinkMetricsStatusToStr(aStatus)); } @@ -2434,8 +2301,7 @@ void Interpreter::HandleLinkMetricsEnhAckProbingIe(otShortAddress aS { OutputFormat("Received Link Metrics data in Enh Ack from neighbor, short address:0x%02x , extended address:", aShortAddress); - OutputExtAddress(*aExtAddress); - OutputLine(""); + OutputExtAddressLine(*aExtAddress); if (aMetricsValues != nullptr) { @@ -2516,7 +2382,7 @@ otError Interpreter::ProcessLinkMetricsQuery(Arg aArgs[]) { VerifyOrExit(!aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(error = ParseLinkMetricsFlags(linkMetrics, aArgs[2])); - error = otLinkMetricsQuery(mInstance, &address, /* aSeriesId */ 0, &linkMetrics, + error = otLinkMetricsQuery(GetInstancePtr(), &address, /* aSeriesId */ 0, &linkMetrics, &Interpreter::HandleLinkMetricsReport, this); } else if (aArgs[1] == "forward") @@ -2524,7 +2390,8 @@ otError Interpreter::ProcessLinkMetricsQuery(Arg aArgs[]) uint8_t seriesId; SuccessOrExit(error = aArgs[2].ParseAsUint8(seriesId)); - error = otLinkMetricsQuery(mInstance, &address, seriesId, nullptr, &Interpreter::HandleLinkMetricsReport, this); + error = otLinkMetricsQuery(GetInstancePtr(), &address, seriesId, nullptr, &Interpreter::HandleLinkMetricsReport, + this); } else { @@ -2627,7 +2494,7 @@ otError Interpreter::ProcessLinkMetricsMgmt(Arg aArgs[]) SuccessOrExit(error = ParseLinkMetricsFlags(linkMetrics, aArgs[4])); } - error = otLinkMetricsConfigForwardTrackingSeries(mInstance, &address, seriesId, seriesFlags, + error = otLinkMetricsConfigForwardTrackingSeries(GetInstancePtr(), &address, seriesId, seriesFlags, clear ? nullptr : &linkMetrics, &Interpreter::HandleLinkMetricsMgmtResponse, this); } @@ -2659,7 +2526,7 @@ otError Interpreter::ProcessLinkMetricsMgmt(Arg aArgs[]) ExitNow(error = OT_ERROR_INVALID_ARGS); } - error = otLinkMetricsConfigEnhAckProbing(mInstance, &address, enhAckFlags, pLinkMetrics, + error = otLinkMetricsConfigEnhAckProbing(GetInstancePtr(), &address, enhAckFlags, pLinkMetrics, &Interpreter::HandleLinkMetricsMgmtResponse, this, &Interpreter::HandleLinkMetricsEnhAckProbingIe, this); } @@ -2683,7 +2550,7 @@ otError Interpreter::ProcessLinkMetricsProbe(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint8(seriesId)); SuccessOrExit(error = aArgs[2].ParseAsUint8(length)); - error = otLinkMetricsSendLinkProbe(mInstance, &address, seriesId, length); + error = otLinkMetricsSendLinkProbe(GetInstancePtr(), &address, seriesId, length); exit: return error; @@ -2699,12 +2566,13 @@ otError Interpreter::ProcessLocate(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine(otThreadIsAnycastLocateInProgress(mInstance) ? "In Progress" : "Idle"); + OutputLine(otThreadIsAnycastLocateInProgress(GetInstancePtr()) ? "In Progress" : "Idle"); ExitNow(error = OT_ERROR_NONE); } SuccessOrExit(error = aArgs[0].ParseAsIp6Address(anycastAddress)); - SuccessOrExit(error = otThreadLocateAnycastDestination(mInstance, &anycastAddress, HandleLocateResult, this)); + SuccessOrExit(error = + otThreadLocateAnycastDestination(GetInstancePtr(), &anycastAddress, HandleLocateResult, this)); SetCommandTimeout(kLocateTimeoutMsecs); mLocateInProgress = true; error = OT_ERROR_PENDING; @@ -2750,9 +2618,8 @@ otError Interpreter::ProcessPskc(Arg aArgs[]) { otPskc pskc; - otThreadGetPskc(mInstance, &pskc); - OutputBytes(pskc.m8); - OutputLine(""); + otThreadGetPskc(GetInstancePtr(), &pskc); + OutputBytesLine(pskc.m8); } else { @@ -2766,15 +2633,15 @@ otError Interpreter::ProcessPskc(Arg aArgs[]) { SuccessOrExit(error = otDatasetGeneratePskc( aArgs[1].GetCString(), - reinterpret_cast(otThreadGetNetworkName(mInstance)), - otThreadGetExtendedPanId(mInstance), &pskc)); + reinterpret_cast(otThreadGetNetworkName(GetInstancePtr())), + otThreadGetExtendedPanId(GetInstancePtr()), &pskc)); } else { ExitNow(error = OT_ERROR_INVALID_ARGS); } - SuccessOrExit(error = otThreadSetPskc(mInstance, &pskc)); + SuccessOrExit(error = otThreadSetPskc(GetInstancePtr(), &pskc)); } exit: @@ -2788,7 +2655,7 @@ otError Interpreter::ProcessPskcRef(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("0x%04x", otThreadGetPskcRef(mInstance)); + OutputLine("0x%04x", otThreadGetPskcRef(GetInstancePtr())); } else { @@ -2803,7 +2670,7 @@ otError Interpreter::ProcessPskcRef(Arg aArgs[]) ExitNow(error = OT_ERROR_INVALID_ARGS); } - SuccessOrExit(error = otThreadSetPskcRef(mInstance, pskcRef)); + SuccessOrExit(error = otThreadSetPskcRef(GetInstancePtr(), pskcRef)); } exit: @@ -2821,7 +2688,7 @@ otError Interpreter::ProcessMlIid(Arg aArgs[]) VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); SuccessOrExit(error = aArgs[0].ParseAsHexString(iid.mFields.m8)); - SuccessOrExit(error = otIp6SetMeshLocalIid(mInstance, &iid)); + SuccessOrExit(error = otIp6SetMeshLocalIid(GetInstancePtr(), &iid)); exit: return error; @@ -2869,7 +2736,7 @@ otError Interpreter::ProcessMlrReg(Arg aArgs[]) VerifyOrExit(aArgs->IsEmpty() && (numAddresses > 0), error = OT_ERROR_INVALID_ARGS); - SuccessOrExit(error = otIp6RegisterMulticastListeners(mInstance, addresses, numAddresses, + SuccessOrExit(error = otIp6RegisterMulticastListeners(GetInstancePtr(), addresses, numAddresses, hasTimeout ? &timeout : nullptr, Interpreter::HandleMlrRegResult, this)); @@ -2899,8 +2766,7 @@ void Interpreter::HandleMlrRegResult(otError aError, for (uint8_t i = 0; i < aFailedAddressNum; i++) { - OutputIp6Address(aFailedAddresses[i]); - OutputLine(""); + OutputIp6AddressLine(aFailedAddresses[i]); } } @@ -2920,7 +2786,7 @@ otError Interpreter::ProcessMode(Arg aArgs[]) { char linkModeString[kLinkModeStringSize]; - OutputLine("%s", LinkModeToString(otThreadGetLinkMode(mInstance), linkModeString)); + OutputLine("%s", LinkModeToString(otThreadGetLinkMode(GetInstancePtr()), linkModeString)); ExitNow(); } @@ -2948,7 +2814,7 @@ otError Interpreter::ProcessMode(Arg aArgs[]) } } - error = otThreadSetLinkMode(mInstance, linkMode); + error = otThreadSetLinkMode(GetInstancePtr(), linkMode); exit: return error; @@ -2986,9 +2852,10 @@ otError Interpreter::ProcessMultiRadio(Arg aArgs[]) otNeighborInfoIterator iterator = OT_NEIGHBOR_INFO_ITERATOR_INIT; otNeighborInfo neighInfo; - while (otThreadGetNextNeighborInfo(mInstance, &iterator, &neighInfo) == OT_ERROR_NONE) + while (otThreadGetNextNeighborInfo(GetInstancePtr(), &iterator, &neighInfo) == OT_ERROR_NONE) { - if (otMultiRadioGetNeighborInfo(mInstance, &neighInfo.mExtAddress, &multiRadioInfo) != OT_ERROR_NONE) + if (otMultiRadioGetNeighborInfo(GetInstancePtr(), &neighInfo.mExtAddress, &multiRadioInfo) != + OT_ERROR_NONE) { continue; } @@ -3004,7 +2871,7 @@ otError Interpreter::ProcessMultiRadio(Arg aArgs[]) otExtAddress extAddress; SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddress.m8)); - SuccessOrExit(error = otMultiRadioGetNeighborInfo(mInstance, &extAddress, &multiRadioInfo)); + SuccessOrExit(error = otMultiRadioGetNeighborInfo(GetInstancePtr(), &extAddress, &multiRadioInfo)); OutputMultiRadioInfo(multiRadioInfo); } } @@ -3065,7 +2932,7 @@ otError Interpreter::ProcessNeighbor(Arg aArgs[]) OutputTableHeader(kNeighborTableTitles, kNeighborTableColumnWidths); } - while (otThreadGetNextNeighborInfo(mInstance, &iterator, &neighborInfo) == OT_ERROR_NONE) + while (otThreadGetNextNeighborInfo(GetInstancePtr(), &iterator, &neighborInfo) == OT_ERROR_NONE) { if (isTable) { @@ -3109,7 +2976,7 @@ otError Interpreter::ProcessNetstat(Arg aArgs[]) OutputTableHeader(kNetstatTableTitles, kNetstatTableColumnWidths); - for (const otUdpSocket *socket = otUdpGetSockets(mInstance); socket != nullptr; socket = socket->mNext) + for (const otUdpSocket *socket = otUdpGetSockets(GetInstancePtr()); socket != nullptr; socket = socket->mNext) { otIp6SockAddrToString(&socket->mSockName, string, sizeof(string)); OutputFormat("| %-47s ", string); @@ -3126,7 +2993,7 @@ otError Interpreter::ProcessServiceList(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otServiceConfig config; - while (otServerGetNextService(mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otServerGetNextService(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { mNetworkData.OutputService(config); } @@ -3163,11 +3030,12 @@ otError Interpreter::ProcessService(Arg aArgs[]) cfg.mServerConfig.mStable = true; - error = otServerAddService(mInstance, &cfg); + error = otServerAddService(GetInstancePtr(), &cfg); } else if (aArgs[0] == "remove") { - error = otServerRemoveService(mInstance, cfg.mEnterpriseNumber, cfg.mServiceData, cfg.mServiceDataLength); + error = otServerRemoveService(GetInstancePtr(), cfg.mEnterpriseNumber, cfg.mServiceData, + cfg.mServiceDataLength); } } @@ -3196,16 +3064,15 @@ otError Interpreter::ProcessNetworkKey(Arg aArgs[]) { otNetworkKey networkKey; - otThreadGetNetworkKey(mInstance, &networkKey); - OutputBytes(networkKey.m8); - OutputLine(""); + otThreadGetNetworkKey(GetInstancePtr(), &networkKey); + OutputBytesLine(networkKey.m8); } else { otNetworkKey key; SuccessOrExit(error = aArgs[0].ParseAsHexString(key.m8)); - SuccessOrExit(error = otThreadSetNetworkKey(mInstance, &key)); + SuccessOrExit(error = otThreadSetNetworkKey(GetInstancePtr(), &key)); } exit: @@ -3219,14 +3086,14 @@ otError Interpreter::ProcessNetworkKeyRef(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("0x%04x", otThreadGetNetworkKeyRef(mInstance)); + OutputLine("0x%04x", otThreadGetNetworkKeyRef(GetInstancePtr())); } else { otNetworkKeyRef keyRef; SuccessOrExit(error = aArgs[0].ParseAsUint32(keyRef)); - SuccessOrExit(error = otThreadSetNetworkKeyRef(mInstance, keyRef)); + SuccessOrExit(error = otThreadSetNetworkKeyRef(GetInstancePtr(), keyRef)); } exit: @@ -3240,11 +3107,11 @@ otError Interpreter::ProcessNetworkName(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("%s", otThreadGetNetworkName(mInstance)); + OutputLine("%s", otThreadGetNetworkName(GetInstancePtr())); } else { - SuccessOrExit(error = otThreadSetNetworkName(mInstance, aArgs[0].GetCString())); + SuccessOrExit(error = otThreadSetNetworkName(GetInstancePtr(), aArgs[0].GetCString())); } exit: @@ -3261,7 +3128,7 @@ otError Interpreter::ProcessNetworkTime(Arg aArgs[]) uint64_t time; otNetworkTimeStatus networkTimeStatus; - networkTimeStatus = otNetworkTimeGet(mInstance, &time); + networkTimeStatus = otNetworkTimeGet(GetInstancePtr(), &time); OutputFormat("Network Time: %luus", time); @@ -3283,8 +3150,8 @@ otError Interpreter::ProcessNetworkTime(Arg aArgs[]) break; } - OutputLine("Time Sync Period: %ds", otNetworkTimeGetSyncPeriod(mInstance)); - OutputLine("XTAL Threshold: %dppm", otNetworkTimeGetXtalThreshold(mInstance)); + OutputLine("Time Sync Period: %ds", otNetworkTimeGetSyncPeriod(GetInstancePtr())); + OutputLine("XTAL Threshold: %dppm", otNetworkTimeGetXtalThreshold(GetInstancePtr())); } else { @@ -3293,8 +3160,8 @@ otError Interpreter::ProcessNetworkTime(Arg aArgs[]) SuccessOrExit(error = aArgs[0].ParseAsUint16(period)); SuccessOrExit(error = aArgs[1].ParseAsUint16(xtalThreshold)); - SuccessOrExit(error = otNetworkTimeSetSyncPeriod(mInstance, period)); - SuccessOrExit(error = otNetworkTimeSetXtalThreshold(mInstance, xtalThreshold)); + SuccessOrExit(error = otNetworkTimeSetSyncPeriod(GetInstancePtr(), period)); + SuccessOrExit(error = otNetworkTimeSetXtalThreshold(GetInstancePtr(), xtalThreshold)); } exit: @@ -3308,7 +3175,7 @@ otError Interpreter::ProcessPanId(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("0x%04x", otLinkGetPanId(mInstance)); + OutputLine("0x%04x", otLinkGetPanId(GetInstancePtr())); } else { @@ -3325,10 +3192,9 @@ otError Interpreter::ProcessParent(Arg aArgs[]) otError error = OT_ERROR_NONE; otRouterInfo parentInfo; - SuccessOrExit(error = otThreadGetParentInfo(mInstance, &parentInfo)); + SuccessOrExit(error = otThreadGetParentInfo(GetInstancePtr(), &parentInfo)); OutputFormat("Ext Addr: "); - OutputExtAddress(parentInfo.mExtAddress); - OutputLine(""); + OutputExtAddressLine(parentInfo.mExtAddress); OutputLine("Rloc: %x", parentInfo.mRloc16); OutputLine("Link Quality In: %d", parentInfo.mLinkQualityIn); OutputLine("Link Quality Out: %d", parentInfo.mLinkQualityOut); @@ -3399,7 +3265,7 @@ otError Interpreter::ProcessPing(Arg aArgs[]) if (aArgs[0] == "stop") { - otPingSenderStop(mInstance); + otPingSenderStop(GetInstancePtr()); ExitNow(); } else if (aArgs[0] == "async") @@ -3417,7 +3283,7 @@ otError Interpreter::ProcessPing(Arg aArgs[]) #if !OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE { bool valid = false; - const otNetifAddress *unicastAddrs = otIp6GetUnicastAddresses(mInstance); + const otNetifAddress *unicastAddrs = otIp6GetUnicastAddresses(GetInstancePtr()); for (const otNetifAddress *addr = unicastAddrs; addr; addr = addr->mNext) { @@ -3473,7 +3339,7 @@ otError Interpreter::ProcessPing(Arg aArgs[]) config.mStatisticsCallback = Interpreter::HandlePingStatistics; config.mCallbackContext = this; - SuccessOrExit(error = otPingSenderPing(mInstance, &config)); + SuccessOrExit(error = otPingSenderPing(GetInstancePtr(), &config)); mPingIsAsync = async; @@ -3499,7 +3365,8 @@ otError Interpreter::ProcessPromiscuous(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputEnabledDisabledStatus(otLinkIsPromiscuous(mInstance) && otPlatRadioGetPromiscuous(mInstance)); + OutputEnabledDisabledStatus(otLinkIsPromiscuous(GetInstancePtr()) && + otPlatRadioGetPromiscuous(GetInstancePtr())); } else { @@ -3509,14 +3376,14 @@ otError Interpreter::ProcessPromiscuous(Arg aArgs[]) if (!enable) { - otLinkSetPcapCallback(mInstance, nullptr, nullptr); + otLinkSetPcapCallback(GetInstancePtr(), nullptr, nullptr); } - SuccessOrExit(error = otLinkSetPromiscuous(mInstance, enable)); + SuccessOrExit(error = otLinkSetPromiscuous(GetInstancePtr(), enable)); if (enable) { - otLinkSetPcapCallback(mInstance, &HandleLinkPcapReceive, this); + otLinkSetPcapCallback(GetInstancePtr(), &HandleLinkPcapReceive, this); } } @@ -3681,7 +3548,7 @@ otError Interpreter::ProcessPrefixAdd(Arg aArgs[]) otBorderRouterConfig config; SuccessOrExit(error = ParsePrefix(aArgs, config)); - error = otBorderRouterAddOnMeshPrefix(mInstance, &config); + error = otBorderRouterAddOnMeshPrefix(GetInstancePtr(), &config); exit: return error; @@ -3694,7 +3561,7 @@ otError Interpreter::ProcessPrefixRemove(Arg aArgs[]) SuccessOrExit(error = aArgs[0].ParseAsIp6Prefix(prefix)); - error = otBorderRouterRemoveOnMeshPrefix(mInstance, &prefix); + error = otBorderRouterRemoveOnMeshPrefix(GetInstancePtr(), &prefix); exit: return error; @@ -3705,15 +3572,15 @@ otError Interpreter::ProcessPrefixList(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otBorderRouterConfig config; - while (otBorderRouterGetNextOnMeshPrefix(mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otBorderRouterGetNextOnMeshPrefix(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { mNetworkData.OutputPrefix(config); } #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE - if (otBackboneRouterGetState(mInstance) == OT_BACKBONE_ROUTER_STATE_DISABLED) + if (otBackboneRouterGetState(GetInstancePtr()) == OT_BACKBONE_ROUTER_STATE_DISABLED) { - SuccessOrExit(otBackboneRouterGetDomainPrefix(mInstance, &config)); + SuccessOrExit(otBackboneRouterGetDomainPrefix(GetInstancePtr(), &config)); OutputFormat("- "); mNetworkData.OutputPrefix(config); } @@ -3742,8 +3609,7 @@ otError Interpreter::ProcessPrefix(Arg aArgs[]) } else if (aArgs[0] == "meshlocal") { - OutputPrefix(*otThreadGetMeshLocalPrefix(mInstance)); - OutputLine(""); + OutputIp6PrefixLine(*otThreadGetMeshLocalPrefix(GetInstancePtr())); } else { @@ -3765,7 +3631,7 @@ otError Interpreter::ProcessPreferRouterId(Arg aArgs[]) otError Interpreter::ProcessRcp(Arg aArgs[]) { otError error = OT_ERROR_NONE; - const char *version = otPlatRadioGetVersionString(mInstance); + const char *version = otPlatRadioGetVersionString(GetInstancePtr()); VerifyOrExit(version != otGetVersionString(), error = OT_ERROR_NOT_IMPLEMENTED); @@ -3789,7 +3655,7 @@ otError Interpreter::ProcessRegion(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - SuccessOrExit(error = otPlatRadioGetRegion(mInstance, ®ionCode)); + SuccessOrExit(error = otPlatRadioGetRegion(GetInstancePtr(), ®ionCode)); OutputLine("%c%c", regionCode >> 8, regionCode & 0xff); } else @@ -3798,7 +3664,7 @@ otError Interpreter::ProcessRegion(Arg aArgs[]) regionCode = static_cast(static_cast(aArgs[0].GetCString()[0]) << 8) + static_cast(aArgs[0].GetCString()[1]); - error = otPlatRadioSetRegion(mInstance, regionCode); + error = otPlatRadioSetRegion(GetInstancePtr(), regionCode); } exit: @@ -3816,7 +3682,7 @@ otError Interpreter::ProcessRloc16(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - OutputLine("%04x", otThreadGetRloc16(mInstance)); + OutputLine("%04x", otThreadGetRloc16(GetInstancePtr())); return OT_ERROR_NONE; } @@ -3869,7 +3735,7 @@ otError Interpreter::ProcessRouteAdd(Arg aArgs[]) otExternalRouteConfig config; SuccessOrExit(error = ParseRoute(aArgs, config)); - error = otBorderRouterAddRoute(mInstance, &config); + error = otBorderRouterAddRoute(GetInstancePtr(), &config); exit: return error; @@ -3882,7 +3748,7 @@ otError Interpreter::ProcessRouteRemove(Arg aArgs[]) SuccessOrExit(error = aArgs[0].ParseAsIp6Prefix(prefix)); - error = otBorderRouterRemoveRoute(mInstance, &prefix); + error = otBorderRouterRemoveRoute(GetInstancePtr(), &prefix); exit: return error; @@ -3893,7 +3759,7 @@ otError Interpreter::ProcessRouteList(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig config; - while (otBorderRouterGetNextRoute(mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otBorderRouterGetNextRoute(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { mNetworkData.OutputRoute(config); } @@ -3954,11 +3820,11 @@ otError Interpreter::ProcessRouter(Arg aArgs[]) OutputTableHeader(kRouterTableTitles, kRouterTableColumnWidths); } - maxRouterId = otThreadGetMaxRouterId(mInstance); + maxRouterId = otThreadGetMaxRouterId(GetInstancePtr()); for (uint8_t i = 0; i <= maxRouterId; i++) { - if (otThreadGetRouterInfo(mInstance, i, &routerInfo) != OT_ERROR_NONE) + if (otThreadGetRouterInfo(GetInstancePtr(), i, &routerInfo) != OT_ERROR_NONE) { continue; } @@ -3987,7 +3853,7 @@ otError Interpreter::ProcessRouter(Arg aArgs[]) } SuccessOrExit(error = aArgs[0].ParseAsUint16(routerId)); - SuccessOrExit(error = otThreadGetRouterInfo(mInstance, routerId, &routerInfo)); + SuccessOrExit(error = otThreadGetRouterInfo(GetInstancePtr(), routerId, &routerInfo)); OutputLine("Alloc: %d", routerInfo.mAllocated); @@ -4001,8 +3867,7 @@ otError Interpreter::ProcessRouter(Arg aArgs[]) if (routerInfo.mLinkEstablished) { OutputFormat("Ext Addr: "); - OutputExtAddress(routerInfo.mExtAddress); - OutputLine(""); + OutputExtAddressLine(routerInfo.mExtAddress); OutputLine("Cost: %d", routerInfo.mPathCost); OutputLine("Link Quality In: %d", routerInfo.mLinkQualityIn); OutputLine("Link Quality Out: %d", routerInfo.mLinkQualityOut); @@ -4025,14 +3890,14 @@ otError Interpreter::ProcessRouterEligible(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputEnabledDisabledStatus(otThreadIsRouterEligible(mInstance)); + OutputEnabledDisabledStatus(otThreadIsRouterEligible(GetInstancePtr())); } else { bool enable; SuccessOrExit(error = ParseEnableOrDisable(aArgs[0], enable)); - error = otThreadSetRouterEligible(mInstance, enable); + error = otThreadSetRouterEligible(GetInstancePtr(), enable); } exit: @@ -4084,13 +3949,13 @@ otError Interpreter::ProcessScan(Arg aArgs[]) static const uint8_t kEnergyScanTableColumnWidths[] = {4, 6}; OutputTableHeader(kEnergyScanTableTitles, kEnergyScanTableColumnWidths); - SuccessOrExit(error = otLinkEnergyScan(mInstance, scanChannels, scanDuration, + SuccessOrExit(error = otLinkEnergyScan(GetInstancePtr(), scanChannels, scanDuration, &Interpreter::HandleEnergyScanResult, this)); } else { OutputScanTableHeader(); - SuccessOrExit(error = otLinkActiveScan(mInstance, scanChannels, scanDuration, + SuccessOrExit(error = otLinkActiveScan(GetInstancePtr(), scanChannels, scanDuration, &Interpreter::HandleActiveScanResult, this)); } @@ -4167,7 +4032,7 @@ otError Interpreter::ProcessSingleton(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - if (otThreadIsSingleton(mInstance)) + if (otThreadIsSingleton(GetInstancePtr())) { OutputLine("true"); } @@ -4210,7 +4075,7 @@ otError Interpreter::ProcessSntp(Arg aArgs[]) query.mMessageInfo = static_cast(&messageInfo); - SuccessOrExit(error = otSntpClientQuery(mInstance, &query, &Interpreter::HandleSntpResponse, this)); + SuccessOrExit(error = otSntpClientQuery(GetInstancePtr(), &query, &Interpreter::HandleSntpResponse, this)); mSntpQueryingInProgress = true; error = OT_ERROR_PENDING; @@ -4291,27 +4156,27 @@ otError Interpreter::ProcessState(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputLine("%s", otThreadDeviceRoleToString(otThreadGetDeviceRole(mInstance))); + OutputLine("%s", otThreadDeviceRoleToString(otThreadGetDeviceRole(GetInstancePtr()))); } else { if (aArgs[0] == "detached") { - SuccessOrExit(error = otThreadBecomeDetached(mInstance)); + SuccessOrExit(error = otThreadBecomeDetached(GetInstancePtr())); } else if (aArgs[0] == "child") { - SuccessOrExit(error = otThreadBecomeChild(mInstance)); + SuccessOrExit(error = otThreadBecomeChild(GetInstancePtr())); } #if OPENTHREAD_FTD else if (aArgs[0] == "router") { - SuccessOrExit(error = otThreadBecomeRouter(mInstance)); + SuccessOrExit(error = otThreadBecomeRouter(GetInstancePtr())); } else if (aArgs[0] == "leader") { - SuccessOrExit(error = otThreadBecomeLeader(mInstance)); + SuccessOrExit(error = otThreadBecomeLeader(GetInstancePtr())); } #endif else @@ -4330,11 +4195,11 @@ otError Interpreter::ProcessThread(Arg aArgs[]) if (aArgs[0] == "start") { - error = otThreadSetEnabled(mInstance, true); + error = otThreadSetEnabled(GetInstancePtr(), true); } else if (aArgs[0] == "stop") { - error = otThreadSetEnabled(mInstance, false); + error = otThreadSetEnabled(GetInstancePtr(), false); } else if (aArgs[0] == "version") { @@ -4360,13 +4225,13 @@ otError Interpreter::ProcessTxPower(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - SuccessOrExit(error = otPlatRadioGetTransmitPower(mInstance, &power)); + SuccessOrExit(error = otPlatRadioGetTransmitPower(GetInstancePtr(), &power)); OutputLine("%d dBm", power); } else { SuccessOrExit(error = aArgs[0].ParseAsInt8(power)); - SuccessOrExit(error = otPlatRadioSetTransmitPower(mInstance, power)); + SuccessOrExit(error = otPlatRadioSetTransmitPower(GetInstancePtr(), power)); } exit: @@ -4397,7 +4262,7 @@ otError Interpreter::ProcessUnsecurePort(Arg aArgs[]) { if (aArgs[1] == "all") { - otIp6RemoveAllUnsecurePorts(mInstance); + otIp6RemoveAllUnsecurePorts(GetInstancePtr()); } else { @@ -4409,7 +4274,7 @@ otError Interpreter::ProcessUnsecurePort(Arg aArgs[]) const uint16_t *ports; uint8_t numPorts; - ports = otIp6GetUnsecurePorts(mInstance, &numPorts); + ports = otIp6GetUnsecurePorts(GetInstancePtr(), &numPorts); if (ports != nullptr) { @@ -4439,12 +4304,12 @@ otError Interpreter::ProcessUptime(Arg aArgs[]) { char string[OT_UPTIME_STRING_SIZE]; - otInstanceGetUptimeAsString(mInstance, string, sizeof(string)); + otInstanceGetUptimeAsString(GetInstancePtr(), string, sizeof(string)); OutputLine("%s", string); } else if (aArgs[0] == "ms") { - OutputLine("%lu", otInstanceGetUptime(mInstance)); + OutputLine("%lu", otInstanceGetUptime(GetInstancePtr())); } else { @@ -4508,7 +4373,7 @@ void Interpreter::PrintMacFilter(void) { otMacFilterEntry entry; otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; - otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); + otMacFilterAddressMode mode = otLinkFilterGetAddressMode(GetInstancePtr()); if (mode == OT_MAC_FILTER_ADDRESS_MODE_DISABLED) { @@ -4523,13 +4388,14 @@ void Interpreter::PrintMacFilter(void) OutputLine("Address Mode: Denylist"); } - while (otLinkFilterGetNextAddress(mInstance, &iterator, &entry) == OT_ERROR_NONE) + while (otLinkFilterGetNextAddress(GetInstancePtr(), &iterator, &entry) == OT_ERROR_NONE) { OutputExtAddress(entry.mExtAddress); if (entry.mRssIn != OT_MAC_FILTER_FIXED_RSS_DISABLED) { - OutputFormat(" : rss %d (lqi %d)", entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + OutputFormat(" : rss %d (lqi %d)", entry.mRssIn, + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } OutputLine(""); @@ -4538,7 +4404,7 @@ void Interpreter::PrintMacFilter(void) iterator = OT_MAC_FILTER_ITERATOR_INIT; OutputLine("RssIn List:"); - while (otLinkFilterGetNextRssIn(mInstance, &iterator, &entry) == OT_ERROR_NONE) + while (otLinkFilterGetNextRssIn(GetInstancePtr(), &iterator, &entry) == OT_ERROR_NONE) { uint8_t i = 0; @@ -4553,12 +4419,13 @@ void Interpreter::PrintMacFilter(void) if (i == OT_EXT_ADDRESS_SIZE) { OutputLine("Default rss : %d (lqi %d)", entry.mRssIn, - otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } else { OutputExtAddress(entry.mExtAddress); - OutputLine(" : rss %d (lqi %d)", entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + OutputLine(" : rss %d (lqi %d)", entry.mRssIn, + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } } } @@ -4569,7 +4436,7 @@ otError Interpreter::ProcessMacFilterAddress(Arg aArgs[]) otExtAddress extAddr; otMacFilterEntry entry; otMacFilterIterator iterator = OT_MAC_FILTER_ITERATOR_INIT; - otMacFilterAddressMode mode = otLinkFilterGetAddressMode(mInstance); + otMacFilterAddressMode mode = otLinkFilterGetAddressMode(GetInstancePtr()); if (aArgs[0].IsEmpty()) { @@ -4586,14 +4453,14 @@ otError Interpreter::ProcessMacFilterAddress(Arg aArgs[]) OutputLine("Denylist"); } - while (otLinkFilterGetNextAddress(mInstance, &iterator, &entry) == OT_ERROR_NONE) + while (otLinkFilterGetNextAddress(GetInstancePtr(), &iterator, &entry) == OT_ERROR_NONE) { OutputExtAddress(entry.mExtAddress); if (entry.mRssIn != OT_MAC_FILTER_FIXED_RSS_DISABLED) { OutputFormat(" : rss %d (lqi %d)", entry.mRssIn, - otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } OutputLine(""); @@ -4604,22 +4471,22 @@ otError Interpreter::ProcessMacFilterAddress(Arg aArgs[]) if (aArgs[0] == "disable") { VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otLinkFilterSetAddressMode(mInstance, OT_MAC_FILTER_ADDRESS_MODE_DISABLED); + otLinkFilterSetAddressMode(GetInstancePtr(), OT_MAC_FILTER_ADDRESS_MODE_DISABLED); } else if (aArgs[0] == "allowlist") { VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otLinkFilterSetAddressMode(mInstance, OT_MAC_FILTER_ADDRESS_MODE_ALLOWLIST); + otLinkFilterSetAddressMode(GetInstancePtr(), OT_MAC_FILTER_ADDRESS_MODE_ALLOWLIST); } else if (aArgs[0] == "denylist") { VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otLinkFilterSetAddressMode(mInstance, OT_MAC_FILTER_ADDRESS_MODE_DENYLIST); + otLinkFilterSetAddressMode(GetInstancePtr(), OT_MAC_FILTER_ADDRESS_MODE_DENYLIST); } else if (aArgs[0] == "add") { SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddr.m8)); - error = otLinkFilterAddAddress(mInstance, &extAddr); + error = otLinkFilterAddAddress(GetInstancePtr(), &extAddr); VerifyOrExit(error == OT_ERROR_NONE || error == OT_ERROR_ALREADY); @@ -4628,17 +4495,17 @@ otError Interpreter::ProcessMacFilterAddress(Arg aArgs[]) int8_t rss; SuccessOrExit(error = aArgs[2].ParseAsInt8(rss)); - SuccessOrExit(error = otLinkFilterAddRssIn(mInstance, &extAddr, rss)); + SuccessOrExit(error = otLinkFilterAddRssIn(GetInstancePtr(), &extAddr, rss)); } } else if (aArgs[0] == "remove") { SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddr.m8)); - otLinkFilterRemoveAddress(mInstance, &extAddr); + otLinkFilterRemoveAddress(GetInstancePtr(), &extAddr); } else if (aArgs[0] == "clear") { - otLinkFilterClearAddresses(mInstance); + otLinkFilterClearAddresses(GetInstancePtr()); } else { @@ -4660,7 +4527,7 @@ otError Interpreter::ProcessMacFilterRss(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - while (otLinkFilterGetNextRssIn(mInstance, &iterator, &entry) == OT_ERROR_NONE) + while (otLinkFilterGetNextRssIn(GetInstancePtr(), &iterator, &entry) == OT_ERROR_NONE) { uint8_t i = 0; @@ -4675,12 +4542,13 @@ otError Interpreter::ProcessMacFilterRss(Arg aArgs[]) if (i == OT_EXT_ADDRESS_SIZE) { OutputLine("Default rss: %d (lqi %d)", entry.mRssIn, - otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } else { OutputExtAddress(entry.mExtAddress); - OutputLine(" : rss %d (lqi %d)", entry.mRssIn, otLinkConvertRssToLinkQuality(mInstance, entry.mRssIn)); + OutputLine(" : rss %d (lqi %d)", entry.mRssIn, + otLinkConvertRssToLinkQuality(GetInstancePtr(), entry.mRssIn)); } } } @@ -4692,16 +4560,16 @@ otError Interpreter::ProcessMacFilterRss(Arg aArgs[]) SuccessOrExit(error = aArgs[2].ParseAsUint8(linkQuality)); VerifyOrExit(linkQuality <= 3, error = OT_ERROR_INVALID_ARGS); - rss = otLinkConvertLinkQualityToRss(mInstance, linkQuality); + rss = otLinkConvertLinkQualityToRss(GetInstancePtr(), linkQuality); if (aArgs[1] == "*") { - otLinkFilterSetDefaultRssIn(mInstance, rss); + otLinkFilterSetDefaultRssIn(GetInstancePtr(), rss); } else { SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddr.m8)); - SuccessOrExit(error = otLinkFilterAddRssIn(mInstance, &extAddr, rss)); + SuccessOrExit(error = otLinkFilterAddRssIn(GetInstancePtr(), &extAddr, rss)); } } else if (aArgs[0] == "add") @@ -4710,29 +4578,29 @@ otError Interpreter::ProcessMacFilterRss(Arg aArgs[]) if (aArgs[1] == "*") { - otLinkFilterSetDefaultRssIn(mInstance, rss); + otLinkFilterSetDefaultRssIn(GetInstancePtr(), rss); } else { SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddr.m8)); - SuccessOrExit(error = otLinkFilterAddRssIn(mInstance, &extAddr, rss)); + SuccessOrExit(error = otLinkFilterAddRssIn(GetInstancePtr(), &extAddr, rss)); } } else if (aArgs[0] == "remove") { if (aArgs[1] == "*") { - otLinkFilterClearDefaultRssIn(mInstance); + otLinkFilterClearDefaultRssIn(GetInstancePtr()); } else { SuccessOrExit(error = aArgs[1].ParseAsHexString(extAddr.m8)); - otLinkFilterRemoveRssIn(mInstance, &extAddr); + otLinkFilterRemoveRssIn(GetInstancePtr(), &extAddr); } } else if (aArgs[0] == "clear") { - otLinkFilterClearAllRssIn(mInstance); + otLinkFilterClearAllRssIn(GetInstancePtr()); } else { @@ -4799,11 +4667,11 @@ otError Interpreter::ProcessMacSend(Arg aArgs[]) if (aArgs[0] == "datarequest") { - error = otLinkSendDataRequest(mInstance); + error = otLinkSendDataRequest(GetInstancePtr()); } else if (aArgs[0] == "emptydata") { - error = otLinkSendEmptyData(mInstance); + error = otLinkSendEmptyData(GetInstancePtr()); } exit: @@ -4819,28 +4687,13 @@ otError Interpreter::ProcessTrel(Arg aArgs[]) SuccessOrExit(error = ParseEnableOrDisable(aArgs[0], enable)); - error = otPlatTrelUdp6SetTestMode(mInstance, enable); + error = otPlatTrelUdp6SetTestMode(GetInstancePtr(), enable); exit: return error; } #endif -void Interpreter::OutputPrefix(const otMeshLocalPrefix &aPrefix) -{ - OutputFormat("%x:%x:%x:%x::/64", (aPrefix.m8[0] << 8) | aPrefix.m8[1], (aPrefix.m8[2] << 8) | aPrefix.m8[3], - (aPrefix.m8[4] << 8) | aPrefix.m8[5], (aPrefix.m8[6] << 8) | aPrefix.m8[7]); -} - -void Interpreter::OutputIp6Prefix(const otIp6Prefix &aPrefix) -{ - char string[OT_IP6_PREFIX_STRING_SIZE]; - - otIp6PrefixToString(&aPrefix, string, sizeof(string)); - - OutputFormat("%s", string); -} - #if OPENTHREAD_FTD || OPENTHREAD_CONFIG_TMF_NETWORK_DIAG_MTD_ENABLE otError Interpreter::ProcessNetworkDiagnostic(Arg aArgs[]) { @@ -4859,14 +4712,14 @@ otError Interpreter::ProcessNetworkDiagnostic(Arg aArgs[]) if (aArgs[0] == "get") { - SuccessOrExit(error = otThreadSendDiagnosticGet(mInstance, &address, tlvTypes, count, + SuccessOrExit(error = otThreadSendDiagnosticGet(GetInstancePtr(), &address, tlvTypes, count, &Interpreter::HandleDiagnosticGetResponse, this)); SetCommandTimeout(kNetworkDiagnosticTimeoutMsecs); error = OT_ERROR_PENDING; } else if (aArgs[0] == "reset") { - IgnoreError(otThreadSendDiagnosticReset(mInstance, &address, tlvTypes, count)); + IgnoreError(otThreadSendDiagnosticReset(GetInstancePtr(), &address, tlvTypes, count)); } else { @@ -4925,8 +4778,7 @@ void Interpreter::HandleDiagnosticGetResponse(otError aError, { case OT_NETWORK_DIAGNOSTIC_TLV_EXT_ADDRESS: OutputFormat("Ext Address: '"); - OutputExtAddress(diagTlv.mData.mExtAddress); - OutputLine("'"); + OutputExtAddressLine(diagTlv.mData.mExtAddress); break; case OT_NETWORK_DIAGNOSTIC_TLV_SHORT_ADDRESS: OutputLine("Rloc16: 0x%04x", diagTlv.mData.mAddr16); @@ -4952,16 +4804,14 @@ void Interpreter::HandleDiagnosticGetResponse(otError aError, break; case OT_NETWORK_DIAGNOSTIC_TLV_NETWORK_DATA: OutputFormat("Network Data: '"); - OutputBytes(diagTlv.mData.mNetworkData.m8, diagTlv.mData.mNetworkData.mCount); - OutputLine("'"); + OutputBytesLine(diagTlv.mData.mNetworkData.m8, diagTlv.mData.mNetworkData.mCount); break; case OT_NETWORK_DIAGNOSTIC_TLV_IP6_ADDR_LIST: OutputLine("IP6 Address List:"); for (uint16_t i = 0; i < diagTlv.mData.mIp6AddrList.mCount; ++i) { OutputFormat(kIndentSize, "- "); - OutputIp6Address(diagTlv.mData.mIp6AddrList.mList[i]); - OutputLine(""); + OutputIp6AddressLine(diagTlv.mData.mIp6AddrList.mList[i]); } break; case OT_NETWORK_DIAGNOSTIC_TLV_MAC_COUNTERS: @@ -5079,158 +4929,6 @@ void Interpreter::HandleDiscoveryRequest(const otThreadDiscoveryRequestInfo &aIn #endif // OPENTHREAD_FTD || OPENTHREAD_MTD -int Interpreter::OutputFormat(const char *aFormat, ...) -{ - int rval; - va_list ap; - - va_start(ap, aFormat); - rval = OutputFormatV(aFormat, ap); - va_end(ap); - - return rval; -} - -void Interpreter::OutputFormat(uint8_t aIndentSize, const char *aFormat, ...) -{ - va_list ap; - - OutputSpaces(aIndentSize); - - va_start(ap, aFormat); - OutputFormatV(aFormat, ap); - va_end(ap); -} - -void Interpreter::OutputLine(const char *aFormat, ...) -{ - va_list args; - - va_start(args, aFormat); - OutputFormatV(aFormat, args); - va_end(args); - - OutputFormat("\r\n"); -} - -void Interpreter::OutputLine(uint8_t aIndentSize, const char *aFormat, ...) -{ - va_list args; - - OutputSpaces(aIndentSize); - - va_start(args, aFormat); - OutputFormatV(aFormat, args); - va_end(args); - - OutputFormat("\r\n"); -} - -void Interpreter::OutputSpaces(uint8_t aCount) -{ - char format[sizeof("%256s")]; - - snprintf(format, sizeof(format), "%%%us", aCount); - - OutputFormat(format, ""); -} - -int Interpreter::OutputFormatV(const char *aFormat, va_list aArguments) -{ - int rval; -#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - va_list args; - int charsWritten; - bool truncated = false; - - va_copy(args, aArguments); -#endif - - rval = mOutputCallback(mOutputContext, aFormat, aArguments); - -#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - VerifyOrExit(!IsLogging()); - - charsWritten = vsnprintf(&mOutputString[mOutputLength], sizeof(mOutputString) - mOutputLength, aFormat, args); - - VerifyOrExit(charsWritten >= 0, mOutputLength = 0); - - if (static_cast(charsWritten) >= sizeof(mOutputString) - mOutputLength) - { - truncated = true; - mOutputLength = sizeof(mOutputString) - 1; - } - else - { - mOutputLength += charsWritten; - } - - while (true) - { - char *lineEnd = strchr(mOutputString, '\r'); - - if (lineEnd == nullptr) - { - break; - } - - *lineEnd = '\0'; - - if (lineEnd > mOutputString) - { - otLogNoteCli("Output: %s", mOutputString); - } - - lineEnd++; - - while ((*lineEnd == '\n') || (*lineEnd == '\r')) - { - lineEnd++; - } - - // Example of the pointers and lengths. - // - // - mOutputString = "hi\r\nmore" - // - mOutputLength = 8 - // - lineEnd = &mOutputString[4] - // - // - // 0 1 2 3 4 5 6 7 8 9 - // +----+----+----+----+----+----+----+----+----+--- - // | h | i | \r | \n | m | o | r | e | \0 | - // +----+----+----+----+----+----+----+----+----+--- - // ^ ^ - // | | - // lineEnd mOutputString[mOutputLength] - // - // - // New length is `&mOutputString[8] - &mOutputString[4] -> 4`. - // - // We move (newLen + 1 = 5) chars from `lineEnd` to start of - // `mOutputString` which will include the `\0` char. - // - // If `lineEnd` and `mOutputString[mOutputLength]` are the same - // the code works correctly as well (new length set to zero and - // the `\0` is copied). - - mOutputLength = static_cast(&mOutputString[mOutputLength] - lineEnd); - memmove(mOutputString, lineEnd, mOutputLength + 1); - } - - if (truncated) - { - otLogNoteCli("Output: %s ...", mOutputString); - mOutputLength = 0; - } - -exit: - va_end(args); - -#endif // OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - - return rval; -} - void Interpreter::Initialize(otInstance *aInstance, otCliOutputCallback aCallback, void *aContext) { Instance *instance = static_cast(aInstance); diff --git a/src/cli/cli.hpp b/src/cli/cli.hpp index b3ec17907..2d76916da 100644 --- a/src/cli/cli.hpp +++ b/src/cli/cli.hpp @@ -60,6 +60,7 @@ #include "cli/cli_history.hpp" #include "cli/cli_joiner.hpp" #include "cli/cli_network_data.hpp" +#include "cli/cli_output.hpp" #include "cli/cli_srp_client.hpp" #include "cli/cli_srp_server.hpp" #include "cli/cli_tcp.hpp" @@ -91,28 +92,27 @@ namespace Cli { extern "C" void otCliPlatLogv(otLogLevel, otLogRegion, const char *, va_list); extern "C" void otCliPlatLogLine(otLogLevel, otLogRegion, const char *); +extern "C" void otCliAppendResult(otError aError); +extern "C" void otCliOutputBytes(const uint8_t *aBytes, uint8_t aLength); +extern "C" void otCliOutputFormat(const char *aFmt, ...); /** * This class implements the CLI interpreter. * */ -class Interpreter +class Interpreter : public Output { #if OPENTHREAD_FTD || OPENTHREAD_MTD - friend class Coap; - friend class CoapSecure; friend class Commissioner; - friend class Dataset; - friend class History; friend class Joiner; friend class NetworkData; friend class SrpClient; - friend class SrpServer; - friend class TcpExample; - friend class UdpExample; #endif friend void otCliPlatLogv(otLogLevel, otLogRegion, const char *, va_list); friend void otCliPlatLogLine(otLogLevel, otLogRegion, const char *); + friend void otCliAppendResult(otError aError); + friend void otCliOutputBytes(const uint8_t *aBytes, uint8_t aLength); + friend void otCliOutputFormat(const char *aFmt, ...); public: typedef Utils::CmdLineParser::Arg Arg; @@ -165,129 +165,6 @@ public: */ void ProcessLine(char *aBuf); - /** - * This method writes a number of bytes to the CLI console as a hex string. - * - * @param[in] aBytes A pointer to data which should be printed. - * @param[in] aLength @p aBytes length. - * - */ - void OutputBytes(const uint8_t *aBytes, uint16_t aLength); - - /** - * This method writes a number of bytes to the CLI console as a hex string. - * - * @tparam kBytesLength The length of @p aBytes array. - * - * @param[in] aBytes A array of @p kBytesLength bytes which should be printed. - * - */ - template void OutputBytes(const uint8_t (&aBytes)[kBytesLength]) - { - OutputBytes(aBytes, kBytesLength); - } - - /** - * This method delivers formatted output to the client. - * - * @param[in] aFormat A pointer to the format string. - * @param[in] ... A variable list of arguments to format. - * - * @returns The number of bytes placed in the output queue. - * - * @retval -1 Driver is broken. - * - */ - int OutputFormat(const char *aFormat, ...); - - /** - * This method delivers formatted output to the client. - * - * @param[in] aFormat A pointer to the format string. - * @param[in] aArguments A variable list of arguments for format. - * - * @returns The number of bytes placed in the output queue. - * - */ - int OutputFormatV(const char *aFormat, va_list aArguments); - - /** - * This method delivers formatted output (to which it prepends a given number indentation space chars) to the - * client. - * - * @param[in] aIndentSize Number of indentation space chars to prepend to the string. - * @param[in] aFormat A pointer to the format string. - * @param[in] ... A variable list of arguments to format. - * - */ - void OutputFormat(uint8_t aIndentSize, const char *aFormat, ...); - - /** - * This method delivers formatted output (to which it also appends newline `\r\n`) to the client. - * - * @param[in] aFormat A pointer to the format string. - * @param[in] ... A variable list of arguments to format. - * - */ - void OutputLine(const char *aFormat, ...); - - /** - * This method delivers formatted output (to which it prepends a given number indentation space chars and appends - * newline `\r\n`) to the client. - * - * @param[in] aIndentSize Number of indentation space chars to prepend to the string. - * @param[in] aFormat A pointer to the format string. - * @param[in] ... A variable list of arguments to format. - * - */ - void OutputLine(uint8_t aIndentSize, const char *aFormat, ...); - - /** - * This method writes a given number of space chars to the CLI console. - * - * @param[in] aCount Number of space chars to output. - * - */ - void OutputSpaces(uint8_t aCount); - - /** - * This method writes an Extended MAC Address to the CLI console. - * - * param[in] aExtAddress The Extended MAC Address to output. - * - */ - void OutputExtAddress(const otExtAddress &aExtAddress) { OutputBytes(aExtAddress.m8); } - - /** - * Write an IPv6 address to the CLI console. - * - * @param[in] aAddress A reference to the IPv6 address. - * - * @returns The number of bytes placed in the output queue. - * - * @retval -1 Driver is broken. - * - */ - int OutputIp6Address(const otIp6Address &aAddress); - - /** - * This method delivers a success or error message the client. - * - * If the @p aError is `OT_ERROR_PENDING` nothing will be outputted. - * - * @param[in] aError The error code. - * - */ - void OutputResult(otError aError); - - /** - * This method delivers "Enabled" or "Disabled" status to the CLI client (it also appends newline `\r\n`). - * - * @param[in] aEnabled A boolean indicating the status. TRUE outputs "Enabled", FALSE outputs "Disabled". - * - */ - void OutputEnabledDisabledStatus(bool aEnabled); - /** * This static method checks a given argument string against "enable" or "disable" commands. * @@ -366,7 +243,7 @@ private: otError error = OT_ERROR_NONE; VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - OutputLine(FormatStringFor(), aGetHandler(mInstance)); + OutputLine(FormatStringFor(), aGetHandler(GetInstancePtr())); exit: return error; @@ -380,7 +257,7 @@ private: SuccessOrExit(error = aArgs[0].ParseAs(value)); VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - aSetHandler(mInstance, value); + aSetHandler(GetInstancePtr(), value); exit: return error; @@ -394,7 +271,7 @@ private: SuccessOrExit(error = aArgs[0].ParseAs(value)); VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = aSetHandler(mInstance, value); + error = aSetHandler(GetInstancePtr(), value); exit: return error; @@ -424,21 +301,9 @@ private: return error; } - void OutputTableHeader(uint8_t aNumColumns, const char *const aTitles[], const uint8_t aWidths[]); - void OutputTableSeperator(uint8_t aNumColumns, const uint8_t aWidths[]); - - template - void OutputTableHeader(const char *const (&aTitles)[kTableNumColumns], const uint8_t (&aWidths)[kTableNumColumns]) - { - OutputTableHeader(kTableNumColumns, &aTitles[0], aWidths); - } - - template void OutputTableSeperator(const uint8_t (&aWidths)[kTableNumColumns]) - { - OutputTableSeperator(kTableNumColumns, aWidths); - } - void OutputPrompt(void); + void OutputResult(otError aError); + #if OPENTHREAD_CONFIG_PING_SENDER_ENABLE otError ParsePingInterval(const Arg &aArg, uint32_t &aInterval); #endif @@ -600,8 +465,6 @@ private: otError ProcessNetworkDataPrefix(void); otError ProcessNetworkDataRoute(void); otError ProcessNetworkDataService(void); - void OutputPrefix(const otMeshLocalPrefix &aPrefix); - void OutputIp6Prefix(const otIp6Prefix &aPrefix); otError ProcessNetstat(Arg aArgs[]); #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE @@ -724,8 +587,6 @@ private: void OutputChildTableEntry(uint8_t aIndentSize, const otNetworkDiagChildEntry &aChildEntry); #endif - void OutputDnsTxtData(const uint8_t *aTxtData, uint16_t aTxtDataLength); - #if OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE otError GetDnsConfig(Arg aArgs[], otDnsQueryConfig *&aConfig); static void HandleDnsAddressResponse(otError aError, const otDnsAddressResponse *aResponse, void *aContext); @@ -789,10 +650,6 @@ private: #endif // OPENTHREAD_FTD || OPENTHREAD_MTD -#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - bool IsLogging(void) const { return mIsLogging; } - void SetIsLogging(bool aIsLogging) { mIsLogging = aIsLogging; } -#endif void SetCommandTimeout(uint32_t aTimeoutMilli); static void HandleTimer(Timer &aTimer); @@ -1001,9 +858,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Instance * mInstance; - otCliOutputCallback mOutputCallback; - void * mOutputContext; const otCliCommand *mUserCommands; uint8_t mUserCommandsLength; void * mUserCommandsContext; @@ -1053,11 +907,6 @@ private: #endif #endif // OPENTHREAD_FTD || OPENTHREAD_MTD -#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE - char mOutputString[OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_LOG_STRING_SIZE]; - uint16_t mOutputLength; - bool mIsLogging; -#endif #if OPENTHREAD_CONFIG_PING_SENDER_ENABLE bool mPingIsAsync : 1; #endif diff --git a/src/cli/cli_coap.cpp b/src/cli/cli_coap.cpp index c7e584e59..56175f96c 100644 --- a/src/cli/cli_coap.cpp +++ b/src/cli/cli_coap.cpp @@ -46,8 +46,8 @@ namespace Cli { constexpr Coap::Command Coap::sCommands[]; -Coap::Coap(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) +Coap::Coap(Output &aOutput) + : OutputWrapper(aOutput) , mUseDefaultRequestTxParameters(true) , mUseDefaultResponseTxParameters(true) #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE @@ -86,7 +86,7 @@ otError Coap::CancelResourceSubscription(void) VerifyOrExit(mRequestTokenLength != 0, error = OT_ERROR_INVALID_STATE); - message = otCoapNewMessage(mInterpreter.mInstance, nullptr); + message = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(message != nullptr, error = OT_ERROR_NO_BUFS); otCoapMessageInit(message, OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_GET); @@ -94,8 +94,7 @@ otError Coap::CancelResourceSubscription(void) SuccessOrExit(error = otCoapMessageSetToken(message, mRequestToken, mRequestTokenLength)); SuccessOrExit(error = otCoapMessageAppendObserveOption(message, 1)); SuccessOrExit(error = otCoapMessageAppendUriPathOptions(message, mRequestUri)); - SuccessOrExit(error = - otCoapSendRequest(mInterpreter.mInstance, message, &messageInfo, &Coap::HandleResponse, this)); + SuccessOrExit(error = otCoapSendRequest(GetInstancePtr(), message, &messageInfo, &Coap::HandleResponse, this)); memset(&mRequestAddr, 0, sizeof(mRequestAddr)); memset(&mRequestUri, 0, sizeof(mRequestUri)); @@ -118,7 +117,7 @@ void Coap::CancelSubscriber(void) } #endif // OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE -void Coap::PrintPayload(otMessage *aMessage) const +void Coap::PrintPayload(otMessage *aMessage) { uint8_t buf[kMaxBufferSize]; uint16_t bytesToPrint; @@ -127,21 +126,21 @@ void Coap::PrintPayload(otMessage *aMessage) const if (length > 0) { - mInterpreter.OutputFormat(" with payload: "); + OutputFormat(" with payload: "); while (length > 0) { bytesToPrint = (length < sizeof(buf)) ? length : sizeof(buf); otMessageRead(aMessage, otMessageGetOffset(aMessage) + bytesPrinted, buf, bytesToPrint); - mInterpreter.OutputBytes(buf, static_cast(bytesToPrint)); + OutputBytes(buf, static_cast(bytesToPrint)); length -= bytesToPrint; bytesPrinted += bytesToPrint; } } - mInterpreter.OutputLine(""); + OutputLine(""); } #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE @@ -159,7 +158,7 @@ otError Coap::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -190,14 +189,14 @@ otError Coap::ProcessResource(Arg aArgs[]) strncpy(mUriPath, aArgs[0].GetCString(), sizeof(mUriPath) - 1); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - otCoapAddBlockWiseResource(mInterpreter.mInstance, &mResource); + otCoapAddBlockWiseResource(GetInstancePtr(), &mResource); #else - otCoapAddResource(mInterpreter.mInstance, &mResource); + otCoapAddResource(GetInstancePtr(), &mResource); #endif } else { - mInterpreter.OutputLine("%s", mResource.mUriPath != nullptr ? mResource.mUriPath : ""); + OutputLine("%s", mResource.mUriPath != nullptr ? mResource.mUriPath : ""); } exit: @@ -226,11 +225,10 @@ otError Coap::ProcessSet(Arg aArgs[]) messageInfo.mPeerAddr = mSubscriberSock.mAddress; messageInfo.mPeerPort = mSubscriberSock.mPort; - mInterpreter.OutputFormat("sending coap notification to "); - mInterpreter.OutputIp6Address(mSubscriberSock.mAddress); - mInterpreter.OutputLine(""); + OutputFormat("sending coap notification to "); + OutputIp6AddressLine(mSubscriberSock.mAddress); - notificationMessage = otCoapNewMessage(mInterpreter.mInstance, nullptr); + notificationMessage = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(notificationMessage != nullptr, error = OT_ERROR_NO_BUFS); otCoapMessageInit( @@ -244,14 +242,14 @@ otError Coap::ProcessSet(Arg aArgs[]) SuccessOrExit(error = otMessageAppend(notificationMessage, mResourceContent, static_cast(strlen(mResourceContent)))); - SuccessOrExit(error = otCoapSendRequest(mInterpreter.mInstance, notificationMessage, &messageInfo, + SuccessOrExit(error = otCoapSendRequest(GetInstancePtr(), notificationMessage, &messageInfo, &Coap::HandleNotificationResponse, this)); } #endif // OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE } else { - mInterpreter.OutputLine("%s", mResourceContent); + OutputLine("%s", mResourceContent); } exit: @@ -270,7 +268,7 @@ otError Coap::ProcessStart(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - return otCoapStart(mInterpreter.mInstance, OT_DEFAULT_COAP_PORT); + return otCoapStart(GetInstancePtr(), OT_DEFAULT_COAP_PORT); } otError Coap::ProcessStop(Arg aArgs[]) @@ -278,12 +276,12 @@ otError Coap::ProcessStop(Arg aArgs[]) OT_UNUSED_VARIABLE(aArgs); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - otCoapRemoveBlockWiseResource(mInterpreter.mInstance, &mResource); + otCoapRemoveBlockWiseResource(GetInstancePtr(), &mResource); #else - otCoapRemoveResource(mInterpreter.mInstance, &mResource); + otCoapRemoveResource(GetInstancePtr(), &mResource); #endif - return otCoapStop(mInterpreter.mInstance); + return otCoapStop(GetInstancePtr()); } otError Coap::ProcessParameters(Arg aArgs[]) @@ -327,17 +325,17 @@ otError Coap::ProcessParameters(Arg aArgs[]) } } - mInterpreter.OutputLine("Transmission parameters for %s:", aArgs[0].GetCString()); + OutputLine("Transmission parameters for %s:", aArgs[0].GetCString()); if (*defaultTxParameters) { - mInterpreter.OutputLine("default"); + OutputLine("default"); } else { - mInterpreter.OutputLine("ACK_TIMEOUT=%u ms, ACK_RANDOM_FACTOR=%u/%u, MAX_RETRANSMIT=%u", - txParameters->mAckTimeout, txParameters->mAckRandomFactorNumerator, - txParameters->mAckRandomFactorDenominator, txParameters->mMaxRetransmit); + OutputLine("ACK_TIMEOUT=%u ms, ACK_RANDOM_FACTOR=%u/%u, MAX_RETRANSMIT=%u", txParameters->mAckTimeout, + txParameters->mAckRandomFactorNumerator, txParameters->mAckRandomFactorDenominator, + txParameters->mMaxRetransmit); } exit: @@ -466,7 +464,7 @@ otError Coap::ProcessRequest(Arg aArgs[], otCoapCode aCoapCode) } #endif - message = otCoapNewMessage(mInterpreter.mInstance, nullptr); + message = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(message != nullptr, error = OT_ERROR_NO_BUFS); otCoapMessageInit(message, coapType, aCoapCode); @@ -548,22 +546,22 @@ otError Coap::ProcessRequest(Arg aArgs[], otCoapCode aCoapCode) { SuccessOrExit(error = otCoapMessageSetPayloadMarker(message)); } - error = otCoapSendRequestBlockWiseWithParameters(mInterpreter.mInstance, message, &messageInfo, + error = otCoapSendRequestBlockWiseWithParameters(GetInstancePtr(), message, &messageInfo, &Coap::HandleResponse, this, GetRequestTxParameters(), Coap::BlockwiseTransmitHook, Coap::BlockwiseReceiveHook); } else { #endif - error = otCoapSendRequestWithParameters(mInterpreter.mInstance, message, &messageInfo, - &Coap::HandleResponse, this, GetRequestTxParameters()); + error = otCoapSendRequestWithParameters(GetInstancePtr(), message, &messageInfo, &Coap::HandleResponse, + this, GetRequestTxParameters()); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE } #endif } else { - error = otCoapSendRequestWithParameters(mInterpreter.mInstance, message, &messageInfo, nullptr, nullptr, + error = otCoapSendRequestWithParameters(GetInstancePtr(), message, &messageInfo, nullptr, nullptr, GetResponseTxParameters()); } @@ -619,14 +617,14 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) otCoapOptionIterator iterator; #endif - mInterpreter.OutputFormat("coap request from "); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); - mInterpreter.OutputFormat(" "); + OutputFormat("coap request from "); + OutputIp6Address(aMessageInfo->mPeerAddr); + OutputFormat(" "); switch (otCoapMessageGetCode(aMessage)) { case OT_COAP_CODE_GET: - mInterpreter.OutputFormat("GET"); + OutputFormat("GET"); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE || OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE SuccessOrExit(error = otCoapOptionIteratorInit(&iterator, aMessage)); #endif @@ -636,7 +634,7 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) SuccessOrExit(error = otCoapOptionIteratorGetOptionUintValue(&iterator, &observe)); observePresent = true; - mInterpreter.OutputFormat(" OBS=%lu", static_cast(observe)); + OutputFormat(" OBS=%lu", static_cast(observe)); } #endif #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE @@ -649,19 +647,19 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) break; case OT_COAP_CODE_DELETE: - mInterpreter.OutputFormat("DELETE"); + OutputFormat("DELETE"); break; case OT_COAP_CODE_PUT: - mInterpreter.OutputFormat("PUT"); + OutputFormat("PUT"); break; case OT_COAP_CODE_POST: - mInterpreter.OutputFormat("POST"); + OutputFormat("POST"); break; default: - mInterpreter.OutputLine("Undefined"); + OutputLine("Undefined"); ExitNow(error = OT_ERROR_PARSE); } @@ -687,7 +685,7 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) if (observe == 0) { // New subscriber - mInterpreter.OutputLine("Subscribing client"); + OutputLine("Subscribing client"); mSubscriberSock.mAddress = aMessageInfo->mPeerAddr; mSubscriberSock.mPort = aMessageInfo->mPeerPort; mSubscriberTokenLength = otCoapMessageGetTokenLength(aMessage); @@ -721,7 +719,7 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) responseCode = OT_COAP_CODE_VALID; } - responseMessage = otCoapNewMessage(mInterpreter.mInstance, nullptr); + responseMessage = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(responseMessage != nullptr, error = OT_ERROR_NO_BUFS); SuccessOrExit( @@ -757,15 +755,15 @@ void Coap::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessageInfo) #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE if (blockPresent) { - SuccessOrExit(error = otCoapSendResponseBlockWiseWithParameters(mInterpreter.mInstance, responseMessage, + SuccessOrExit(error = otCoapSendResponseBlockWiseWithParameters(GetInstancePtr(), responseMessage, aMessageInfo, GetResponseTxParameters(), this, mResource.mTransmitHook)); } else { #endif - SuccessOrExit(error = otCoapSendResponseWithParameters(mInterpreter.mInstance, responseMessage, - aMessageInfo, GetResponseTxParameters())); + SuccessOrExit(error = otCoapSendResponseWithParameters(GetInstancePtr(), responseMessage, aMessageInfo, + GetResponseTxParameters())); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE } #endif @@ -777,13 +775,13 @@ exit: { if (responseMessage != nullptr) { - mInterpreter.OutputLine("coap send response error %d: %s", error, otThreadErrorToString(error)); + OutputLine("coap send response error %d: %s", error, otThreadErrorToString(error)); otMessageFree(responseMessage); } } else if (responseCode >= OT_COAP_CODE_RESPONSE_MIN) { - mInterpreter.OutputLine("coap response sent"); + OutputLine("coap response sent"); } } @@ -805,15 +803,13 @@ void Coap::HandleNotificationResponse(otMessage *aMessage, const otMessageInfo * case OT_ERROR_NONE: if (aMessageInfo != nullptr) { - mInterpreter.OutputFormat("Received ACK in reply to notification from "); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); - mInterpreter.OutputLine(""); + OutputFormat("Received ACK in reply to notification from "); + OutputIp6AddressLine(aMessageInfo->mPeerAddr); } break; default: - mInterpreter.OutputLine("coap receive notification response error %d: %s", aError, - otThreadErrorToString(aError)); + OutputLine("coap receive notification response error %d: %s", aError, otThreadErrorToString(aError)); CancelSubscriber(); break; } @@ -829,7 +825,7 @@ void Coap::HandleResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo { if (aError != OT_ERROR_NONE) { - mInterpreter.OutputLine("coap receive response error %d: %s", aError, otThreadErrorToString(aError)); + OutputLine("coap receive response error %d: %s", aError, otThreadErrorToString(aError)); } else if ((aMessageInfo != nullptr) && (aMessage != nullptr)) { @@ -837,8 +833,8 @@ void Coap::HandleResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo otCoapOptionIterator iterator; #endif - mInterpreter.OutputFormat("coap response from "); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); + OutputFormat("coap response from "); + OutputIp6Address(aMessageInfo->mPeerAddr); #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE if (otCoapOptionIteratorInit(&iterator, aMessage) == OT_ERROR_NONE) @@ -853,7 +849,7 @@ void Coap::HandleResponse(otMessage *aMessage, const otMessageInfo *aMessageInfo if (error == OT_ERROR_NONE) { - mInterpreter.OutputFormat(" OBS=%u", observeVal); + OutputFormat(" OBS=%u", observeVal); } } } @@ -882,12 +878,11 @@ otError Coap::BlockwiseReceiveHook(const uint8_t *aBlock, OT_UNUSED_VARIABLE(aMore); OT_UNUSED_VARIABLE(aTotalLength); - mInterpreter.OutputLine("received block: Num %i Len %i", aPosition / aBlockLength, aBlockLength); + OutputLine("received block: Num %i Len %i", aPosition / aBlockLength, aBlockLength); for (uint16_t i = 0; i < aBlockLength / 16; i++) { - mInterpreter.OutputBytes(&aBlock[i * 16], 16); - mInterpreter.OutputLine(""); + OutputBytesLine(&aBlock[i * 16], 16); } return OT_ERROR_NONE; @@ -910,12 +905,11 @@ otError Coap::BlockwiseTransmitHook(uint8_t *aBlock, uint32_t aPosition, uint16_ // Send a random payload otRandomNonCryptoFillBuffer(aBlock, *aBlockLength); - mInterpreter.OutputLine("send block: Num %i Len %i", blockCount, *aBlockLength); + OutputLine("send block: Num %i Len %i", blockCount, *aBlockLength); for (uint16_t i = 0; i < *aBlockLength / 16; i++) { - mInterpreter.OutputBytes(&aBlock[i * 16], 16); - mInterpreter.OutputLine(""); + OutputBytesLine(&aBlock[i * 16], 16); } if (blockCount == mBlockCount - 1) diff --git a/src/cli/cli_coap.hpp b/src/cli/cli_coap.hpp index 2723910fd..f1d158cf9 100644 --- a/src/cli/cli_coap.hpp +++ b/src/cli/cli_coap.hpp @@ -40,19 +40,18 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the CLI CoAP server and client. * */ -class Coap +class Coap : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -60,10 +59,10 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit Coap(Interpreter &aInterpreter); + explicit Coap(Output &aOutput); /** * This method interprets a list of CLI arguments. @@ -87,8 +86,7 @@ private: }; #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - enum BlockType : uint8_t - { + enum BlockType : uint8_t{ kBlockType1, kBlockType2, }; @@ -99,7 +97,7 @@ private: void CancelSubscriber(void); #endif - void PrintPayload(otMessage *aMessage) const; + void PrintPayload(otMessage *aMessage); otError ProcessHelp(Arg aArgs[]); #if OPENTHREAD_CONFIG_COAP_OBSERVE_API_ENABLE @@ -190,8 +188,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - bool mUseDefaultRequestTxParameters; bool mUseDefaultResponseTxParameters; diff --git a/src/cli/cli_coap_secure.cpp b/src/cli/cli_coap_secure.cpp index d74d3f54f..f6848948f 100644 --- a/src/cli/cli_coap_secure.cpp +++ b/src/cli/cli_coap_secure.cpp @@ -48,8 +48,8 @@ namespace Cli { constexpr CoapSecure::Command CoapSecure::sCommands[]; -CoapSecure::CoapSecure(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) +CoapSecure::CoapSecure(Output &aOutput) + : OutputWrapper(aOutput) , mShutdownFlag(false) , mUseCertificate(false) , mPskLength(0) @@ -66,7 +66,7 @@ CoapSecure::CoapSecure(Interpreter &aInterpreter) mResourceContent[sizeof(mResourceContent) - 1] = '\0'; } -void CoapSecure::PrintPayload(otMessage *aMessage) const +void CoapSecure::PrintPayload(otMessage *aMessage) { uint8_t buf[kMaxBufferSize]; uint16_t bytesToPrint; @@ -75,21 +75,21 @@ void CoapSecure::PrintPayload(otMessage *aMessage) const if (length > 0) { - mInterpreter.OutputFormat(" with payload: "); + OutputFormat(" with payload: "); while (length > 0) { bytesToPrint = (length < sizeof(buf)) ? length : sizeof(buf); otMessageRead(aMessage, otMessageGetOffset(aMessage) + bytesPrinted, buf, bytesToPrint); - mInterpreter.OutputBytes(buf, static_cast(bytesToPrint)); + OutputBytes(buf, static_cast(bytesToPrint)); length -= bytesToPrint; bytesPrinted += bytesToPrint; } } - mInterpreter.OutputLine(""); + OutputLine(""); } otError CoapSecure::ProcessHelp(Arg aArgs[]) @@ -98,7 +98,7 @@ otError CoapSecure::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -128,14 +128,14 @@ otError CoapSecure::ProcessResource(Arg aArgs[]) strncpy(mUriPath, aArgs[0].GetCString(), sizeof(mUriPath) - 1); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - otCoapSecureAddBlockWiseResource(mInterpreter.mInstance, &mResource); + otCoapSecureAddBlockWiseResource(GetInstancePtr(), &mResource); #else - otCoapSecureAddResource(mInterpreter.mInstance, &mResource); + otCoapSecureAddResource(GetInstancePtr(), &mResource); #endif } else { - mInterpreter.OutputLine("%s", mResource.mUriPath != nullptr ? mResource.mUriPath : ""); + OutputLine("%s", mResource.mUriPath != nullptr ? mResource.mUriPath : ""); } exit: @@ -154,7 +154,7 @@ otError CoapSecure::ProcessSet(Arg aArgs[]) } else { - mInterpreter.OutputLine("%s", mResourceContent); + OutputLine("%s", mResourceContent); } exit: @@ -178,14 +178,14 @@ otError CoapSecure::ProcessStart(Arg aArgs[]) } } - otCoapSecureSetSslAuthMode(mInterpreter.mInstance, verifyPeerCert); - otCoapSecureSetClientConnectedCallback(mInterpreter.mInstance, &CoapSecure::HandleConnected, this); + otCoapSecureSetSslAuthMode(GetInstancePtr(), verifyPeerCert); + otCoapSecureSetClientConnectedCallback(GetInstancePtr(), &CoapSecure::HandleConnected, this); #if CLI_COAP_SECURE_USE_COAP_DEFAULT_HANDLER - otCoapSecureSetDefaultHandler(mInterpreter.mInstance, &CoapSecure::DefaultHandler, this); + otCoapSecureSetDefaultHandler(GetInstancePtr(), &CoapSecure::DefaultHandler, this); #endif - error = otCoapSecureStart(mInterpreter.mInstance, OT_DEFAULT_COAP_SECURE_PORT); + error = otCoapSecureStart(GetInstancePtr(), OT_DEFAULT_COAP_SECURE_PORT); exit: return error; @@ -196,14 +196,14 @@ otError CoapSecure::ProcessStop(Arg aArgs[]) OT_UNUSED_VARIABLE(aArgs); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - otCoapRemoveBlockWiseResource(mInterpreter.mInstance, &mResource); + otCoapRemoveBlockWiseResource(GetInstancePtr(), &mResource); #else - otCoapRemoveResource(mInterpreter.mInstance, &mResource); + otCoapRemoveResource(GetInstancePtr(), &mResource); #endif - if (otCoapSecureIsConnectionActive(mInterpreter.mInstance)) + if (otCoapSecureIsConnectionActive(GetInstancePtr())) { - otCoapSecureDisconnect(mInterpreter.mInstance); + otCoapSecureDisconnect(GetInstancePtr()); mShutdownFlag = true; } else @@ -305,7 +305,7 @@ otError CoapSecure::ProcessRequest(Arg aArgs[], otCoapCode aCoapCode) #endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE } - message = otCoapNewMessage(mInterpreter.mInstance, nullptr); + message = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(message != nullptr, error = OT_ERROR_NO_BUFS); otCoapMessageInit(message, coapType, aCoapCode); @@ -358,20 +358,20 @@ otError CoapSecure::ProcessRequest(Arg aArgs[], otCoapCode aCoapCode) if (coapBlock) { error = - otCoapSecureSendRequestBlockWise(mInterpreter.mInstance, message, &CoapSecure::HandleResponse, this, + otCoapSecureSendRequestBlockWise(GetInstancePtr(), message, &CoapSecure::HandleResponse, this, &CoapSecure::BlockwiseTransmitHook, &CoapSecure::BlockwiseReceiveHook); } else { #endif - error = otCoapSecureSendRequest(mInterpreter.mInstance, message, &CoapSecure::HandleResponse, this); + error = otCoapSecureSendRequest(GetInstancePtr(), message, &CoapSecure::HandleResponse, this); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE } #endif } else { - error = otCoapSecureSendRequest(mInterpreter.mInstance, message, nullptr, nullptr); + error = otCoapSecureSendRequest(GetInstancePtr(), message, nullptr, nullptr); } exit: @@ -398,7 +398,7 @@ otError CoapSecure::ProcessConnect(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint16(sockaddr.mPort)); } - SuccessOrExit(error = otCoapSecureConnect(mInterpreter.mInstance, &sockaddr, &CoapSecure::HandleConnected, this)); + SuccessOrExit(error = otCoapSecureConnect(GetInstancePtr(), &sockaddr, &CoapSecure::HandleConnected, this)); exit: return error; @@ -408,7 +408,7 @@ otError CoapSecure::ProcessDisconnect(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otCoapSecureDisconnect(mInterpreter.mInstance); + otCoapSecureDisconnect(GetInstancePtr()); return OT_ERROR_NONE; } @@ -431,7 +431,7 @@ otError CoapSecure::ProcessPsk(Arg aArgs[]) mPskIdLength = static_cast(length); memcpy(mPskId, aArgs[1].GetCString(), mPskIdLength); - otCoapSecureSetPsk(mInterpreter.mInstance, mPsk, mPskLength, mPskId, mPskIdLength); + otCoapSecureSetPsk(GetInstancePtr(), mPsk, mPskLength, mPskId, mPskIdLength); mUseCertificate = false; exit: @@ -444,11 +444,11 @@ otError CoapSecure::ProcessX509(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otCoapSecureSetCertificate(mInterpreter.mInstance, reinterpret_cast(OT_CLI_COAPS_X509_CERT), + otCoapSecureSetCertificate(GetInstancePtr(), reinterpret_cast(OT_CLI_COAPS_X509_CERT), sizeof(OT_CLI_COAPS_X509_CERT), reinterpret_cast(OT_CLI_COAPS_PRIV_KEY), sizeof(OT_CLI_COAPS_PRIV_KEY)); - otCoapSecureSetCaCertificateChain(mInterpreter.mInstance, + otCoapSecureSetCaCertificateChain(GetInstancePtr(), reinterpret_cast(OT_CLI_COAPS_TRUSTED_ROOT_CERTIFICATE), sizeof(OT_CLI_COAPS_TRUSTED_ROOT_CERTIFICATE)); mUseCertificate = true; @@ -480,11 +480,11 @@ exit: void CoapSecure::Stop(void) { #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - otCoapRemoveBlockWiseResource(mInterpreter.mInstance, &mResource); + otCoapRemoveBlockWiseResource(GetInstancePtr(), &mResource); #else - otCoapRemoveResource(mInterpreter.mInstance, &mResource); + otCoapRemoveResource(GetInstancePtr(), &mResource); #endif - otCoapSecureStop(mInterpreter.mInstance); + otCoapSecureStop(GetInstancePtr()); } void CoapSecure::HandleConnected(bool aConnected, void *aContext) @@ -496,11 +496,11 @@ void CoapSecure::HandleConnected(bool aConnected) { if (aConnected) { - mInterpreter.OutputLine("coaps connected"); + OutputLine("coaps connected"); } else { - mInterpreter.OutputLine("coaps disconnected"); + OutputLine("coaps disconnected"); if (mShutdownFlag) { @@ -526,14 +526,14 @@ void CoapSecure::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessag otCoapOptionIterator iterator; #endif - mInterpreter.OutputFormat("coaps request from "); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); - mInterpreter.OutputFormat(" "); + OutputFormat("coaps request from "); + OutputIp6Address(aMessageInfo->mPeerAddr); + OutputFormat(" "); switch (otCoapMessageGetCode(aMessage)) { case OT_COAP_CODE_GET: - mInterpreter.OutputFormat("GET"); + OutputFormat("GET"); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE SuccessOrExit(error = otCoapOptionIteratorInit(&iterator, aMessage)); if (otCoapOptionIteratorGetFirstOptionMatching(&iterator, OT_COAP_OPTION_BLOCK2) != nullptr) @@ -545,19 +545,19 @@ void CoapSecure::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessag break; case OT_COAP_CODE_DELETE: - mInterpreter.OutputFormat("DELETE"); + OutputFormat("DELETE"); break; case OT_COAP_CODE_PUT: - mInterpreter.OutputFormat("PUT"); + OutputFormat("PUT"); break; case OT_COAP_CODE_POST: - mInterpreter.OutputFormat("POST"); + OutputFormat("POST"); break; default: - mInterpreter.OutputLine("Undefined"); + OutputLine("Undefined"); return; } @@ -575,7 +575,7 @@ void CoapSecure::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessag responseCode = OT_COAP_CODE_VALID; } - responseMessage = otCoapNewMessage(mInterpreter.mInstance, nullptr); + responseMessage = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(responseMessage != nullptr, error = OT_ERROR_NO_BUFS); SuccessOrExit( @@ -606,13 +606,13 @@ void CoapSecure::HandleRequest(otMessage *aMessage, const otMessageInfo *aMessag #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE if (blockPresent) { - SuccessOrExit(error = otCoapSecureSendResponseBlockWise(mInterpreter.mInstance, responseMessage, - aMessageInfo, this, mResource.mTransmitHook)); + SuccessOrExit(error = otCoapSecureSendResponseBlockWise(GetInstancePtr(), responseMessage, aMessageInfo, + this, mResource.mTransmitHook)); } else { #endif - SuccessOrExit(error = otCoapSecureSendResponse(mInterpreter.mInstance, responseMessage, aMessageInfo)); + SuccessOrExit(error = otCoapSecureSendResponse(GetInstancePtr(), responseMessage, aMessageInfo)); #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE } #endif @@ -624,13 +624,13 @@ exit: { if (responseMessage != nullptr) { - mInterpreter.OutputLine("coaps send response error %d: %s", error, otThreadErrorToString(error)); + OutputLine("coaps send response error %d: %s", error, otThreadErrorToString(error)); otMessageFree(responseMessage); } } else if (responseCode >= OT_COAP_CODE_RESPONSE_MIN) { - mInterpreter.OutputLine("coaps response sent"); + OutputLine("coaps response sent"); } } @@ -645,12 +645,12 @@ void CoapSecure::HandleResponse(otMessage *aMessage, const otMessageInfo *aMessa if (aError != OT_ERROR_NONE) { - mInterpreter.OutputLine("coaps receive response error %d: %s", aError, otThreadErrorToString(aError)); + OutputLine("coaps receive response error %d: %s", aError, otThreadErrorToString(aError)); } else { - mInterpreter.OutputFormat("coaps response from "); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); + OutputFormat("coaps response from "); + OutputIp6Address(aMessageInfo->mPeerAddr); PrintPayload(aMessage); } @@ -670,13 +670,13 @@ void CoapSecure::DefaultHandler(otMessage *aMessage, const otMessageInfo *aMessa if ((otCoapMessageGetType(aMessage) == OT_COAP_TYPE_CONFIRMABLE) || (otCoapMessageGetCode(aMessage) == OT_COAP_CODE_GET)) { - responseMessage = otCoapNewMessage(mInterpreter.mInstance, nullptr); + responseMessage = otCoapNewMessage(GetInstancePtr(), nullptr); VerifyOrExit(responseMessage != nullptr, error = OT_ERROR_NO_BUFS); SuccessOrExit(error = otCoapMessageInitResponse(responseMessage, aMessage, OT_COAP_TYPE_NON_CONFIRMABLE, OT_COAP_CODE_NOT_FOUND)); - SuccessOrExit(error = otCoapSecureSendResponse(mInterpreter.mInstance, responseMessage, aMessageInfo)); + SuccessOrExit(error = otCoapSecureSendResponse(GetInstancePtr(), responseMessage, aMessageInfo)); } exit: @@ -708,12 +708,11 @@ otError CoapSecure::BlockwiseReceiveHook(const uint8_t *aBlock, OT_UNUSED_VARIABLE(aMore); OT_UNUSED_VARIABLE(aTotalLength); - mInterpreter.OutputLine("received block: Num %i Len %i", aPosition / aBlockLength, aBlockLength); + OutputLine("received block: Num %i Len %i", aPosition / aBlockLength, aBlockLength); for (uint16_t i = 0; i < aBlockLength / 16; i++) { - mInterpreter.OutputBytes(&aBlock[i * 16], 16); - mInterpreter.OutputLine(""); + OutputBytesLine(&aBlock[i * 16], 16); } return OT_ERROR_NONE; @@ -736,12 +735,11 @@ otError CoapSecure::BlockwiseTransmitHook(uint8_t *aBlock, uint32_t aPosition, u // Send a random payload otRandomNonCryptoFillBuffer(aBlock, *aBlockLength); - mInterpreter.OutputLine("send block: Num %i Len %i", blockCount, *aBlockLength); + OutputLine("send block: Num %i Len %i", blockCount, *aBlockLength); for (uint16_t i = 0; i < *aBlockLength / 16; i++) { - mInterpreter.OutputBytes(&aBlock[i * 16], 16); - mInterpreter.OutputLine(""); + OutputBytesLine(&aBlock[i * 16], 16); } if (blockCount == mBlockCount - 1) diff --git a/src/cli/cli_coap_secure.hpp b/src/cli/cli_coap_secure.hpp index b8480d90e..18f789780 100644 --- a/src/cli/cli_coap_secure.hpp +++ b/src/cli/cli_coap_secure.hpp @@ -42,6 +42,7 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -52,13 +53,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the CLI CoAP Secure server and client. * */ -class CoapSecure +class CoapSecure : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -66,10 +65,10 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit CoapSecure(Interpreter &aInterpreter); + explicit CoapSecure(Output &aOutput); /** * This method interprets a list of CLI arguments. @@ -95,14 +94,13 @@ private: }; #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE - enum BlockType : uint8_t - { + enum BlockType : uint8_t{ kBlockType1, kBlockType2, }; #endif - void PrintPayload(otMessage *aMessage) const; + void PrintPayload(otMessage *aMessage); otError ProcessConnect(Arg aArgs[]); otError ProcessDelete(Arg aArgs[]); @@ -179,8 +177,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - #if OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE otCoapBlockwiseResource mResource; #else diff --git a/src/cli/cli_commissioner.cpp b/src/cli/cli_commissioner.cpp index 0a2a2e310..122259c21 100644 --- a/src/cli/cli_commissioner.cpp +++ b/src/cli/cli_commissioner.cpp @@ -48,7 +48,7 @@ otError Commissioner::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -67,7 +67,7 @@ otError Commissioner::ProcessAnnounce(Arg aArgs[]) SuccessOrExit(error = aArgs[2].ParseAsUint16(period)); SuccessOrExit(error = aArgs[3].ParseAsIp6Address(address)); - error = otCommissionerAnnounceBegin(mInterpreter.mInstance, mask, count, period, &address); + error = otCommissionerAnnounceBegin(GetInstancePtr(), mask, count, period, &address); exit: return error; @@ -88,7 +88,7 @@ otError Commissioner::ProcessEnergy(Arg aArgs[]) SuccessOrExit(error = aArgs[3].ParseAsUint16(scanDuration)); SuccessOrExit(error = aArgs[4].ParseAsIp6Address(address)); - error = otCommissionerEnergyScan(mInterpreter.mInstance, mask, count, period, scanDuration, &address, + error = otCommissionerEnergyScan(GetInstancePtr(), mask, count, period, scanDuration, &address, &Commissioner::HandleEnergyReport, this); exit: @@ -136,23 +136,22 @@ otError Commissioner::ProcessJoiner(Arg aArgs[]) if (discerner.mLength) { - error = otCommissionerAddJoinerWithDiscerner(mInterpreter.mInstance, &discerner, aArgs[2].GetCString(), - timeout); + error = otCommissionerAddJoinerWithDiscerner(GetInstancePtr(), &discerner, aArgs[2].GetCString(), timeout); } else { - error = otCommissionerAddJoiner(mInterpreter.mInstance, addrPtr, aArgs[2].GetCString(), timeout); + error = otCommissionerAddJoiner(GetInstancePtr(), addrPtr, aArgs[2].GetCString(), timeout); } } else if (aArgs[0] == "remove") { if (discerner.mLength) { - error = otCommissionerRemoveJoinerWithDiscerner(mInterpreter.mInstance, &discerner); + error = otCommissionerRemoveJoinerWithDiscerner(GetInstancePtr(), &discerner); } else { - error = otCommissionerRemoveJoiner(mInterpreter.mInstance, addrPtr); + error = otCommissionerRemoveJoiner(GetInstancePtr(), addrPtr); } } else @@ -205,7 +204,7 @@ otError Commissioner::ProcessMgmtGet(Arg aArgs[]) } } - error = otCommissionerSendMgmtGet(mInterpreter.mInstance, tlvs, static_cast(length)); + error = otCommissionerSendMgmtGet(GetInstancePtr(), tlvs, static_cast(length)); exit: return error; @@ -267,7 +266,7 @@ otError Commissioner::ProcessMgmtSet(Arg aArgs[]) } } - error = otCommissionerSendMgmtSet(mInterpreter.mInstance, &dataset, tlvs, tlvsLength); + error = otCommissionerSendMgmtSet(GetInstancePtr(), &dataset, tlvs, tlvsLength); exit: return error; @@ -284,8 +283,7 @@ otError Commissioner::ProcessPanId(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint32(mask)); SuccessOrExit(error = aArgs[2].ParseAsIp6Address(address)); - error = otCommissionerPanIdQuery(mInterpreter.mInstance, panId, mask, &address, &Commissioner::HandlePanIdConflict, - this); + error = otCommissionerPanIdQuery(GetInstancePtr(), panId, mask, &address, &Commissioner::HandlePanIdConflict, this); exit: return error; @@ -295,14 +293,14 @@ otError Commissioner::ProcessProvisioningUrl(Arg aArgs[]) { // If aArgs[0] is empty, `GetCString() will return `nullptr` /// which will correctly clear the provisioning URL. - return otCommissionerSetProvisioningUrl(mInterpreter.mInstance, aArgs[0].GetCString()); + return otCommissionerSetProvisioningUrl(GetInstancePtr(), aArgs[0].GetCString()); } otError Commissioner::ProcessSessionId(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - mInterpreter.OutputLine("%d", otCommissionerGetSessionId(mInterpreter.mInstance)); + OutputLine("%d", otCommissionerGetSessionId(GetInstancePtr())); return OT_ERROR_NONE; } @@ -311,8 +309,8 @@ otError Commissioner::ProcessStart(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - return otCommissionerStart(mInterpreter.mInstance, &Commissioner::HandleStateChanged, - &Commissioner::HandleJoinerEvent, this); + return otCommissionerStart(GetInstancePtr(), &Commissioner::HandleStateChanged, &Commissioner::HandleJoinerEvent, + this); } void Commissioner::HandleStateChanged(otCommissionerState aState, void *aContext) @@ -322,7 +320,7 @@ void Commissioner::HandleStateChanged(otCommissionerState aState, void *aContext void Commissioner::HandleStateChanged(otCommissionerState aState) { - mInterpreter.OutputLine("Commissioner: %s", StateToString(aState)); + OutputLine("Commissioner: %s", StateToString(aState)); } const char *Commissioner::StateToString(otCommissionerState aState) @@ -359,47 +357,47 @@ void Commissioner::HandleJoinerEvent(otCommissionerJoinerEvent aEvent, { OT_UNUSED_VARIABLE(aJoinerInfo); - mInterpreter.OutputFormat("Commissioner: Joiner "); + OutputFormat("Commissioner: Joiner "); switch (aEvent) { case OT_COMMISSIONER_JOINER_START: - mInterpreter.OutputFormat("start "); + OutputFormat("start "); break; case OT_COMMISSIONER_JOINER_CONNECTED: - mInterpreter.OutputFormat("connect "); + OutputFormat("connect "); break; case OT_COMMISSIONER_JOINER_FINALIZE: - mInterpreter.OutputFormat("finalize "); + OutputFormat("finalize "); break; case OT_COMMISSIONER_JOINER_END: - mInterpreter.OutputFormat("end "); + OutputFormat("end "); break; case OT_COMMISSIONER_JOINER_REMOVED: - mInterpreter.OutputFormat("remove "); + OutputFormat("remove "); break; } if (aJoinerId != nullptr) { - mInterpreter.OutputExtAddress(*aJoinerId); + OutputExtAddress(*aJoinerId); } - mInterpreter.OutputLine(""); + OutputLine(""); } otError Commissioner::ProcessStop(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - return otCommissionerStop(mInterpreter.mInstance); + return otCommissionerStop(GetInstancePtr()); } otError Commissioner::ProcessState(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - mInterpreter.OutputLine(StateToString(otCommissionerGetState(mInterpreter.mInstance))); + OutputLine(StateToString(otCommissionerGetState(GetInstancePtr()))); return OT_ERROR_NONE; } @@ -434,14 +432,14 @@ void Commissioner::HandleEnergyReport(uint32_t aChannelMask, void Commissioner::HandleEnergyReport(uint32_t aChannelMask, const uint8_t *aEnergyList, uint8_t aEnergyListLength) { - mInterpreter.OutputFormat("Energy: %08x ", aChannelMask); + OutputFormat("Energy: %08x ", aChannelMask); for (uint8_t i = 0; i < aEnergyListLength; i++) { - mInterpreter.OutputFormat("%d ", static_cast(aEnergyList[i])); + OutputFormat("%d ", static_cast(aEnergyList[i])); } - mInterpreter.OutputLine(""); + OutputLine(""); } void Commissioner::HandlePanIdConflict(uint16_t aPanId, uint32_t aChannelMask, void *aContext) @@ -451,7 +449,7 @@ void Commissioner::HandlePanIdConflict(uint16_t aPanId, uint32_t aChannelMask, v void Commissioner::HandlePanIdConflict(uint16_t aPanId, uint32_t aChannelMask) { - mInterpreter.OutputLine("Conflict: %04x, %08x", aPanId, aChannelMask); + OutputLine("Conflict: %04x, %08x", aPanId, aChannelMask); } } // namespace Cli diff --git a/src/cli/cli_commissioner.hpp b/src/cli/cli_commissioner.hpp index 2ce82c8e5..175c5cde1 100644 --- a/src/cli/cli_commissioner.hpp +++ b/src/cli/cli_commissioner.hpp @@ -38,6 +38,7 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -46,13 +47,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the Commissioner CLI interpreter. * */ -class Commissioner +class Commissioner : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -60,11 +59,11 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit Commissioner(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) + explicit Commissioner(Output &aOutput) + : OutputWrapper(aOutput) { } @@ -133,8 +132,6 @@ private: }; static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - - Interpreter &mInterpreter; }; } // namespace Cli diff --git a/src/cli/cli_dataset.cpp b/src/cli/cli_dataset.cpp index f859b3177..158a6c90e 100644 --- a/src/cli/cli_dataset.cpp +++ b/src/cli/cli_dataset.cpp @@ -52,73 +52,68 @@ otError Dataset::Print(otOperationalDataset &aDataset) { if (aDataset.mComponents.mIsPendingTimestampPresent) { - mInterpreter.OutputLine("Pending Timestamp: %lu", aDataset.mPendingTimestamp); + OutputLine("Pending Timestamp: %lu", aDataset.mPendingTimestamp); } if (aDataset.mComponents.mIsActiveTimestampPresent) { - mInterpreter.OutputLine("Active Timestamp: %lu", aDataset.mActiveTimestamp); + OutputLine("Active Timestamp: %lu", aDataset.mActiveTimestamp); } if (aDataset.mComponents.mIsChannelPresent) { - mInterpreter.OutputLine("Channel: %d", aDataset.mChannel); + OutputLine("Channel: %d", aDataset.mChannel); } if (aDataset.mComponents.mIsChannelMaskPresent) { - mInterpreter.OutputLine("Channel Mask: 0x%08x", aDataset.mChannelMask); + OutputLine("Channel Mask: 0x%08x", aDataset.mChannelMask); } if (aDataset.mComponents.mIsDelayPresent) { - mInterpreter.OutputLine("Delay: %d", aDataset.mDelay); + OutputLine("Delay: %d", aDataset.mDelay); } if (aDataset.mComponents.mIsExtendedPanIdPresent) { - mInterpreter.OutputFormat("Ext PAN ID: "); - mInterpreter.OutputBytes(aDataset.mExtendedPanId.m8); - mInterpreter.OutputLine(""); + OutputFormat("Ext PAN ID: "); + OutputBytesLine(aDataset.mExtendedPanId.m8); } if (aDataset.mComponents.mIsMeshLocalPrefixPresent) { - mInterpreter.OutputFormat("Mesh Local Prefix: "); - mInterpreter.OutputPrefix(aDataset.mMeshLocalPrefix); - mInterpreter.OutputLine(""); + OutputFormat("Mesh Local Prefix: "); + OutputIp6PrefixLine(aDataset.mMeshLocalPrefix); } if (aDataset.mComponents.mIsNetworkKeyPresent) { - mInterpreter.OutputFormat("Network Key: "); - mInterpreter.OutputBytes(aDataset.mNetworkKey.m8); - mInterpreter.OutputLine(""); + OutputFormat("Network Key: "); + OutputBytesLine(aDataset.mNetworkKey.m8); } if (aDataset.mComponents.mIsNetworkNamePresent) { - mInterpreter.OutputFormat("Network Name: "); - mInterpreter.OutputLine("%s", aDataset.mNetworkName.m8); + OutputFormat("Network Name: "); + OutputLine("%s", aDataset.mNetworkName.m8); } if (aDataset.mComponents.mIsPanIdPresent) { - mInterpreter.OutputLine("PAN ID: 0x%04x", aDataset.mPanId); + OutputLine("PAN ID: 0x%04x", aDataset.mPanId); } if (aDataset.mComponents.mIsPskcPresent) { - mInterpreter.OutputFormat("PSKc: "); - mInterpreter.OutputBytes(aDataset.mPskc.m8); - mInterpreter.OutputLine(""); + OutputFormat("PSKc: "); + OutputBytesLine(aDataset.mPskc.m8); } if (aDataset.mComponents.mIsSecurityPolicyPresent) { - mInterpreter.OutputFormat("Security Policy: "); + OutputFormat("Security Policy: "); OutputSecurityPolicy(aDataset.mSecurityPolicy); - mInterpreter.OutputLine(""); } return OT_ERROR_NONE; @@ -149,7 +144,7 @@ otError Dataset::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -161,16 +156,16 @@ otError Dataset::ProcessInit(Arg aArgs[]) if (aArgs[0] == "active") { - error = otDatasetGetActive(mInterpreter.mInstance, &sDataset); + error = otDatasetGetActive(GetInstancePtr(), &sDataset); } else if (aArgs[0] == "pending") { - error = otDatasetGetPending(mInterpreter.mInstance, &sDataset); + error = otDatasetGetPending(GetInstancePtr(), &sDataset); } #if OPENTHREAD_FTD else if (aArgs[0] == "new") { - error = otDatasetCreateNewNetwork(mInterpreter.mInstance, &sDataset); + error = otDatasetCreateNewNetwork(GetInstancePtr(), &sDataset); } #endif else if (aArgs[0] == "tlvs") @@ -196,16 +191,15 @@ otError Dataset::ProcessActive(Arg aArgs[]) { otOperationalDataset dataset; - SuccessOrExit(error = otDatasetGetActive(mInterpreter.mInstance, &dataset)); + SuccessOrExit(error = otDatasetGetActive(GetInstancePtr(), &dataset)); error = Print(dataset); } else if (aArgs[0] == "-x") { otOperationalDatasetTlvs dataset; - SuccessOrExit(error = otDatasetGetActiveTlvs(mInterpreter.mInstance, &dataset)); - mInterpreter.OutputBytes(dataset.mTlvs, dataset.mLength); - mInterpreter.OutputLine(""); + SuccessOrExit(error = otDatasetGetActiveTlvs(GetInstancePtr(), &dataset)); + OutputBytesLine(dataset.mTlvs, dataset.mLength); } exit: @@ -220,16 +214,15 @@ otError Dataset::ProcessPending(Arg aArgs[]) { otOperationalDataset dataset; - SuccessOrExit(error = otDatasetGetPending(mInterpreter.mInstance, &dataset)); + SuccessOrExit(error = otDatasetGetPending(GetInstancePtr(), &dataset)); error = Print(dataset); } else if (aArgs[0] == "-x") { otOperationalDatasetTlvs dataset; - SuccessOrExit(error = otDatasetGetPendingTlvs(mInterpreter.mInstance, &dataset)); - mInterpreter.OutputBytes(dataset.mTlvs, dataset.mLength); - mInterpreter.OutputLine(""); + SuccessOrExit(error = otDatasetGetPendingTlvs(GetInstancePtr(), &dataset)); + OutputBytesLine(dataset.mTlvs, dataset.mLength); } exit: @@ -244,7 +237,7 @@ otError Dataset::ProcessActiveTimestamp(Arg aArgs[]) { if (sDataset.mComponents.mIsActiveTimestampPresent) { - mInterpreter.OutputLine("%lu", sDataset.mActiveTimestamp); + OutputLine("%lu", sDataset.mActiveTimestamp); } } else @@ -265,7 +258,7 @@ otError Dataset::ProcessChannel(Arg aArgs[]) { if (sDataset.mComponents.mIsChannelPresent) { - mInterpreter.OutputLine("%d", sDataset.mChannel); + OutputLine("%d", sDataset.mChannel); } } else @@ -286,7 +279,7 @@ otError Dataset::ProcessChannelMask(Arg aArgs[]) { if (sDataset.mComponents.mIsChannelMaskPresent) { - mInterpreter.OutputLine("0x%08x", sDataset.mChannelMask); + OutputLine("0x%08x", sDataset.mChannelMask); } } else @@ -313,11 +306,11 @@ otError Dataset::ProcessCommit(Arg aArgs[]) if (aArgs[0] == "active") { - error = otDatasetSetActive(mInterpreter.mInstance, &sDataset); + error = otDatasetSetActive(GetInstancePtr(), &sDataset); } else if (aArgs[0] == "pending") { - error = otDatasetSetPending(mInterpreter.mInstance, &sDataset); + error = otDatasetSetPending(GetInstancePtr(), &sDataset); } return error; @@ -331,7 +324,7 @@ otError Dataset::ProcessDelay(Arg aArgs[]) { if (sDataset.mComponents.mIsDelayPresent) { - mInterpreter.OutputLine("%d", sDataset.mDelay); + OutputLine("%d", sDataset.mDelay); } } else @@ -352,8 +345,7 @@ otError Dataset::ProcessExtPanId(Arg aArgs[]) { if (sDataset.mComponents.mIsExtendedPanIdPresent) { - mInterpreter.OutputBytes(sDataset.mExtendedPanId.m8); - mInterpreter.OutputLine(""); + OutputBytesLine(sDataset.mExtendedPanId.m8); } } else @@ -374,9 +366,8 @@ otError Dataset::ProcessMeshLocalPrefix(Arg aArgs[]) { if (sDataset.mComponents.mIsMeshLocalPrefixPresent) { - mInterpreter.OutputFormat("Mesh Local Prefix: "); - mInterpreter.OutputPrefix(sDataset.mMeshLocalPrefix); - mInterpreter.OutputLine(""); + OutputFormat("Mesh Local Prefix: "); + OutputIp6PrefixLine(sDataset.mMeshLocalPrefix); } } else @@ -401,8 +392,7 @@ otError Dataset::ProcessNetworkKey(Arg aArgs[]) { if (sDataset.mComponents.mIsNetworkKeyPresent) { - mInterpreter.OutputBytes(sDataset.mNetworkKey.m8); - mInterpreter.OutputLine(""); + OutputBytesLine(sDataset.mNetworkKey.m8); } } else @@ -423,7 +413,7 @@ otError Dataset::ProcessNetworkName(Arg aArgs[]) { if (sDataset.mComponents.mIsNetworkNamePresent) { - mInterpreter.OutputLine("%s", sDataset.mNetworkName.m8); + OutputLine("%s", sDataset.mNetworkName.m8); } } else @@ -444,7 +434,7 @@ otError Dataset::ProcessPanId(Arg aArgs[]) { if (sDataset.mComponents.mIsPanIdPresent) { - mInterpreter.OutputLine("0x%04x", sDataset.mPanId); + OutputLine("0x%04x", sDataset.mPanId); } } else @@ -465,7 +455,7 @@ otError Dataset::ProcessPendingTimestamp(Arg aArgs[]) { if (sDataset.mComponents.mIsPendingTimestampPresent) { - mInterpreter.OutputLine("%lu", sDataset.mPendingTimestamp); + OutputLine("%lu", sDataset.mPendingTimestamp); } } else @@ -576,12 +566,12 @@ otError Dataset::ProcessMgmtSetCommand(Arg aArgs[]) if (aArgs[0] == "active") { - error = otDatasetSendMgmtActiveSet(mInterpreter.mInstance, &dataset, tlvs, tlvsLength, /* aCallback */ nullptr, + error = otDatasetSendMgmtActiveSet(GetInstancePtr(), &dataset, tlvs, tlvsLength, /* aCallback */ nullptr, /* aContext */ nullptr); } else if (aArgs[0] == "pending") { - error = otDatasetSendMgmtPendingSet(mInterpreter.mInstance, &dataset, tlvs, tlvsLength, /* aCallback */ nullptr, + error = otDatasetSendMgmtPendingSet(GetInstancePtr(), &dataset, tlvs, tlvsLength, /* aCallback */ nullptr, /* aContext */ nullptr); } else @@ -669,12 +659,12 @@ otError Dataset::ProcessMgmtGetCommand(Arg aArgs[]) if (aArgs[0] == "active") { - error = otDatasetSendMgmtActiveGet(mInterpreter.mInstance, &datasetComponents, tlvs, tlvsLength, + error = otDatasetSendMgmtActiveGet(GetInstancePtr(), &datasetComponents, tlvs, tlvsLength, destAddrSpecified ? &address : nullptr); } else if (aArgs[0] == "pending") { - error = otDatasetSendMgmtPendingGet(mInterpreter.mInstance, &datasetComponents, tlvs, tlvsLength, + error = otDatasetSendMgmtPendingGet(GetInstancePtr(), &datasetComponents, tlvs, tlvsLength, destAddrSpecified ? &address : nullptr); } else @@ -696,8 +686,7 @@ otError Dataset::ProcessPskc(Arg aArgs[]) // need to export it from PSA ITS. if (sDataset.mComponents.mIsPskcPresent) { - mInterpreter.OutputBytes(sDataset.mPskc.m8); - mInterpreter.OutputLine(""); + OutputBytesLine(sDataset.mPskc.m8); } } else @@ -712,9 +701,9 @@ otError Dataset::ProcessPskc(Arg aArgs[]) aArgs[1].GetCString(), (sDataset.mComponents.mIsNetworkNamePresent ? &sDataset.mNetworkName - : reinterpret_cast(otThreadGetNetworkName(mInterpreter.mInstance))), + : reinterpret_cast(otThreadGetNetworkName(GetInstancePtr()))), (sDataset.mComponents.mIsExtendedPanIdPresent ? &sDataset.mExtendedPanId - : otThreadGetExtendedPanId(mInterpreter.mInstance)), + : otThreadGetExtendedPanId(GetInstancePtr())), &sDataset.mPskc)); } else @@ -732,52 +721,54 @@ exit: void Dataset::OutputSecurityPolicy(const otSecurityPolicy &aSecurityPolicy) { - mInterpreter.OutputFormat("%d ", aSecurityPolicy.mRotationTime); + OutputFormat("%d ", aSecurityPolicy.mRotationTime); if (aSecurityPolicy.mObtainNetworkKeyEnabled) { - mInterpreter.OutputFormat("o"); + OutputFormat("o"); } if (aSecurityPolicy.mNativeCommissioningEnabled) { - mInterpreter.OutputFormat("n"); + OutputFormat("n"); } if (aSecurityPolicy.mRoutersEnabled) { - mInterpreter.OutputFormat("r"); + OutputFormat("r"); } if (aSecurityPolicy.mExternalCommissioningEnabled) { - mInterpreter.OutputFormat("c"); + OutputFormat("c"); } if (aSecurityPolicy.mBeaconsEnabled) { - mInterpreter.OutputFormat("b"); + OutputFormat("b"); } if (aSecurityPolicy.mCommercialCommissioningEnabled) { - mInterpreter.OutputFormat("C"); + OutputFormat("C"); } if (aSecurityPolicy.mAutonomousEnrollmentEnabled) { - mInterpreter.OutputFormat("e"); + OutputFormat("e"); } if (aSecurityPolicy.mNetworkKeyProvisioningEnabled) { - mInterpreter.OutputFormat("p"); + OutputFormat("p"); } if (aSecurityPolicy.mNonCcmRoutersEnabled) { - mInterpreter.OutputFormat("R"); + OutputFormat("R"); } + + OutputLine(""); } otError Dataset::ParseSecurityPolicy(otSecurityPolicy &aSecurityPolicy, Arg *&aArgs) @@ -857,7 +848,6 @@ otError Dataset::ProcessSecurityPolicy(Arg aArgs[]) if (sDataset.mComponents.mIsSecurityPolicyPresent) { OutputSecurityPolicy(sDataset.mSecurityPolicy); - mInterpreter.OutputLine(""); } } else @@ -903,10 +893,10 @@ otError Dataset::ProcessSet(Arg aArgs[]) switch (datasetType) { case MeshCoP::Dataset::Type::kActive: - SuccessOrExit(error = otDatasetSetActive(mInterpreter.mInstance, &datasetInfo)); + SuccessOrExit(error = otDatasetSetActive(GetInstancePtr(), &datasetInfo)); break; case MeshCoP::Dataset::Type::kPending: - SuccessOrExit(error = otDatasetSetPending(mInterpreter.mInstance, &datasetInfo)); + SuccessOrExit(error = otDatasetSetPending(GetInstancePtr(), &datasetInfo)); break; } } @@ -923,15 +913,15 @@ otError Dataset::ProcessUpdater(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputEnabledDisabledStatus(otDatasetUpdaterIsUpdateOngoing(mInterpreter.mInstance)); + OutputEnabledDisabledStatus(otDatasetUpdaterIsUpdateOngoing(GetInstancePtr())); } else if (aArgs[0] == "start") { - error = otDatasetUpdaterRequestUpdate(mInterpreter.mInstance, &sDataset, &Dataset::HandleDatasetUpdater, this); + error = otDatasetUpdaterRequestUpdate(GetInstancePtr(), &sDataset, &Dataset::HandleDatasetUpdater, this); } else if (aArgs[0] == "cancel") { - otDatasetUpdaterCancelUpdate(mInterpreter.mInstance); + otDatasetUpdaterCancelUpdate(GetInstancePtr()); } else { @@ -948,7 +938,7 @@ void Dataset::HandleDatasetUpdater(otError aError, void *aContext) void Dataset::HandleDatasetUpdater(otError aError) { - mInterpreter.OutputLine("Dataset update complete: %s", otThreadErrorToString(aError)); + OutputLine("Dataset update complete: %s", otThreadErrorToString(aError)); } #endif // OPENTHREAD_CONFIG_DATASET_UPDATER_ENABLE && OPENTHREAD_FTD diff --git a/src/cli/cli_dataset.hpp b/src/cli/cli_dataset.hpp index e131336a2..b712c6cf2 100644 --- a/src/cli/cli_dataset.hpp +++ b/src/cli/cli_dataset.hpp @@ -40,25 +40,24 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the Dataset CLI interpreter. * */ -class Dataset +class Dataset : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; - explicit Dataset(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) + explicit Dataset(Output &aOutput) + : OutputWrapper(aOutput) { } @@ -139,8 +138,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - static otOperationalDataset sDataset; }; diff --git a/src/cli/cli_history.cpp b/src/cli/cli_history.cpp index c4e05863f..2292e016b 100644 --- a/src/cli/cli_history.cpp +++ b/src/cli/cli_history.cpp @@ -50,7 +50,7 @@ otError History::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -111,14 +111,14 @@ otError History::ProcessIpAddr(Arg aArgs[]) static const uint8_t kUnicastAddrInfoColumnWidths[] = {22, 9, 45, 8, 5, 3, 3, 3}; - mInterpreter.OutputTableHeader(kUnicastAddrInfoTitles, kUnicastAddrInfoColumnWidths); + OutputTableHeader(kUnicastAddrInfoTitles, kUnicastAddrInfoColumnWidths); } otHistoryTrackerInitIterator(&iterator); for (uint16_t index = 0; (numEntries == 0) || (index < numEntries); index++) { - info = otHistoryTrackerIterateUnicastAddressHistory(mInterpreter.mInstance, &iterator, &entryAge); + info = otHistoryTrackerIterateUnicastAddressHistory(GetInstancePtr(), &iterator, &entryAge); VerifyOrExit(info != nullptr); otHistoryTrackerEntryAgeToString(entryAge, ageString, sizeof(ageString)); @@ -128,18 +128,16 @@ otError History::ProcessIpAddr(Arg aArgs[]) { sprintf(&addressString[strlen(addressString)], "/%d", info->mPrefixLength); - mInterpreter.OutputLine("| %20s | %-7s | %-43s | %-6s | %3d | %c | %c | %c |", ageString, - kEventStrings[info->mEvent], addressString, - AddressOriginToString(info->mAddressOrigin), info->mScope, - info->mPreferred ? 'Y' : 'N', info->mValid ? 'Y' : 'N', info->mRloc ? 'Y' : 'N'); + OutputLine("| %20s | %-7s | %-43s | %-6s | %3d | %c | %c | %c |", ageString, kEventStrings[info->mEvent], + addressString, AddressOriginToString(info->mAddressOrigin), info->mScope, + info->mPreferred ? 'Y' : 'N', info->mValid ? 'Y' : 'N', info->mRloc ? 'Y' : 'N'); } else { - mInterpreter.OutputLine( - "%s -> event:%s address:%s prefixlen:%d origin:%s scope:%d preferred:%s valid:%s rloc:%s", ageString, - kEventStrings[info->mEvent], addressString, info->mPrefixLength, - AddressOriginToString(info->mAddressOrigin), info->mScope, info->mPreferred ? "yes" : "no", - info->mValid ? "yes" : "no", info->mRloc ? "yes" : "no"); + OutputLine("%s -> event:%s address:%s prefixlen:%d origin:%s scope:%d preferred:%s valid:%s rloc:%s", + ageString, kEventStrings[info->mEvent], addressString, info->mPrefixLength, + AddressOriginToString(info->mAddressOrigin), info->mScope, info->mPreferred ? "yes" : "no", + info->mValid ? "yes" : "no", info->mRloc ? "yes" : "no"); } } @@ -182,22 +180,21 @@ otError History::ProcessIpMulticastAddr(Arg aArgs[]) static const uint8_t kMulticastAddrInfoColumnWidths[] = {22, 14, 42, 8}; - mInterpreter.OutputTableHeader(kMulticastAddrInfoTitles, kMulticastAddrInfoColumnWidths); + OutputTableHeader(kMulticastAddrInfoTitles, kMulticastAddrInfoColumnWidths); } otHistoryTrackerInitIterator(&iterator); for (uint16_t index = 0; (numEntries == 0) || (index < numEntries); index++) { - info = otHistoryTrackerIterateMulticastAddressHistory(mInterpreter.mInstance, &iterator, &entryAge); + info = otHistoryTrackerIterateMulticastAddressHistory(GetInstancePtr(), &iterator, &entryAge); VerifyOrExit(info != nullptr); otHistoryTrackerEntryAgeToString(entryAge, ageString, sizeof(ageString)); otIp6AddressToString(&info->mAddress, addressString, sizeof(addressString)); - mInterpreter.OutputLine(isList ? "%s -> event:%s address:%s origin:%s" : "| %20s | %-12s | %-39s | %-6s |", - ageString, kEventStrings[info->mEvent], addressString, - AddressOriginToString(info->mAddressOrigin)); + OutputLine(isList ? "%s -> event:%s address:%s origin:%s" : "| %20s | %-12s | %-39s | %-6s |", ageString, + kEventStrings[info->mEvent], addressString, AddressOriginToString(info->mAddressOrigin)); } exit: @@ -241,14 +238,14 @@ otError History::ProcessNeighbor(Arg aArgs[]) static const uint8_t kNeighborInfoColumnWidths[] = {22, 8, 11, 18, 8, 6, 9}; - mInterpreter.OutputTableHeader(kNeighborInfoTitles, kNeighborInfoColumnWidths); + OutputTableHeader(kNeighborInfoTitles, kNeighborInfoColumnWidths); } otHistoryTrackerInitIterator(&iterator); for (uint16_t index = 0; (numEntries == 0) || (index < numEntries); index++) { - info = otHistoryTrackerIterateNeighborHistory(mInterpreter.mInstance, &iterator, &entryAge); + info = otHistoryTrackerIterateNeighborHistory(GetInstancePtr(), &iterator, &entryAge); VerifyOrExit(info != nullptr); otHistoryTrackerEntryAgeToString(entryAge, ageString, sizeof(ageString)); @@ -258,11 +255,11 @@ otError History::ProcessNeighbor(Arg aArgs[]) mode.mNetworkData = info->mFullNetworkData; Interpreter::LinkModeToString(mode, linkModeString); - mInterpreter.OutputFormat(isList ? "%s -> type:%s event:%s extaddr:" : "| %20s | %-6s | %-9s | ", ageString, - info->mIsChild ? "Child" : "Router", kEventString[info->mEvent]); - mInterpreter.OutputExtAddress(info->mExtAddress); - mInterpreter.OutputLine(isList ? " rloc16:0x%04x mode:%s rss:%d" : " | 0x%04x | %-4s | %7d |", info->mRloc16, - linkModeString, info->mAverageRssi); + OutputFormat(isList ? "%s -> type:%s event:%s extaddr:" : "| %20s | %-6s | %-9s | ", ageString, + info->mIsChild ? "Child" : "Router", kEventString[info->mEvent]); + OutputExtAddress(info->mExtAddress); + OutputLine(isList ? " rloc16:0x%04x mode:%s rss:%d" : " | 0x%04x | %-4s | %7d |", info->mRloc16, linkModeString, + info->mAverageRssi); } exit: @@ -290,22 +287,22 @@ otError History::ProcessNetInfo(Arg aArgs[]) static const char *const kNetInfoTitles[] = {"Age", "Role", "Mode", "RLOC16", "Partition ID"}; static const uint8_t kNetInfoColumnWidths[] = {22, 10, 6, 8, 14}; - mInterpreter.OutputTableHeader(kNetInfoTitles, kNetInfoColumnWidths); + OutputTableHeader(kNetInfoTitles, kNetInfoColumnWidths); } otHistoryTrackerInitIterator(&iterator); for (uint16_t index = 0; (numEntries == 0) || (index < numEntries); index++) { - info = otHistoryTrackerIterateNetInfoHistory(mInterpreter.mInstance, &iterator, &entryAge); + info = otHistoryTrackerIterateNetInfoHistory(GetInstancePtr(), &iterator, &entryAge); VerifyOrExit(info != nullptr); otHistoryTrackerEntryAgeToString(entryAge, ageString, sizeof(ageString)); - mInterpreter.OutputLine( - isList ? "%s -> role:%s mode:%s rloc16:0x%04x partition-id:%u" : "| %20s | %-8s | %-4s | 0x%04x | %12u |", - ageString, otThreadDeviceRoleToString(info->mRole), - Interpreter::LinkModeToString(info->mMode, linkModeString), info->mRloc16, info->mPartitionId); + OutputLine(isList ? "%s -> role:%s mode:%s rloc16:0x%04x partition-id:%u" + : "| %20s | %-8s | %-4s | 0x%04x | %12u |", + ageString, otThreadDeviceRoleToString(info->mRole), + Interpreter::LinkModeToString(info->mMode, linkModeString), info->mRloc16, info->mPartitionId); } exit: @@ -467,7 +464,7 @@ otError History::ProcessRxTxHistory(RxTx aRxTx, Arg aArgs[]) if (!isList) { - mInterpreter.OutputTableHeader(kTableTitles, kTableColumnWidths); + OutputTableHeader(kTableTitles, kTableColumnWidths); } otHistoryTrackerInitIterator(&txIterator); @@ -478,12 +475,12 @@ otError History::ProcessRxTxHistory(RxTx aRxTx, Arg aArgs[]) switch (aRxTx) { case kRx: - info = otHistoryTrackerIterateRxHistory(mInterpreter.mInstance, &rxIterator, &entryAge); + info = otHistoryTrackerIterateRxHistory(GetInstancePtr(), &rxIterator, &entryAge); isRx = true; break; case kTx: - info = otHistoryTrackerIterateTxHistory(mInterpreter.mInstance, &txIterator, &entryAge); + info = otHistoryTrackerIterateTxHistory(GetInstancePtr(), &txIterator, &entryAge); isRx = false; break; @@ -493,12 +490,12 @@ otError History::ProcessRxTxHistory(RxTx aRxTx, Arg aArgs[]) if (rxInfo == nullptr) { - rxInfo = otHistoryTrackerIterateRxHistory(mInterpreter.mInstance, &rxIterator, &rxEntryAge); + rxInfo = otHistoryTrackerIterateRxHistory(GetInstancePtr(), &rxIterator, &rxEntryAge); } if (txInfo == nullptr) { - txInfo = otHistoryTrackerIterateTxHistory(mInterpreter.mInstance, &txIterator, &txEntryAge); + txInfo = otHistoryTrackerIterateTxHistory(GetInstancePtr(), &txIterator, &txEntryAge); } if ((rxInfo != nullptr) && ((txInfo == nullptr) || (rxEntryAge <= txEntryAge))) @@ -529,7 +526,7 @@ otError History::ProcessRxTxHistory(RxTx aRxTx, Arg aArgs[]) { if (index != 0) { - mInterpreter.OutputTableSeperator(kTableColumnWidths); + OutputTableSeparator(kTableColumnWidths); } OutputRxTxEntryTableFormat(*info, entryAge, isRx); @@ -549,27 +546,26 @@ void History::OutputRxTxEntryListFormat(const otHistoryTrackerMessageInfo &aInfo otHistoryTrackerEntryAgeToString(aEntryAge, ageString, sizeof(ageString)); - mInterpreter.OutputLine("%s", ageString); - mInterpreter.OutputFormat(kIndentSize, "type:%s len:%u cheksum:0x%04x sec:%s prio:%s ", MessageTypeToString(aInfo), - aInfo.mPayloadLength, aInfo.mChecksum, aInfo.mLinkSecurity ? "yes" : "no", - MessagePriorityToString(aInfo.mPriority)); + OutputLine("%s", ageString); + OutputFormat(kIndentSize, "type:%s len:%u cheksum:0x%04x sec:%s prio:%s ", MessageTypeToString(aInfo), + aInfo.mPayloadLength, aInfo.mChecksum, aInfo.mLinkSecurity ? "yes" : "no", + MessagePriorityToString(aInfo.mPriority)); if (aIsRx) { - mInterpreter.OutputFormat("rss:%d", aInfo.mAveRxRss); + OutputFormat("rss:%d", aInfo.mAveRxRss); } else { - mInterpreter.OutputFormat("tx-success:%s", aInfo.mTxSuccess ? "yes" : "no"); + OutputFormat("tx-success:%s", aInfo.mTxSuccess ? "yes" : "no"); } - mInterpreter.OutputLine(" %s:0x%04x radio:%s", aIsRx ? "from" : "to", aInfo.mNeighborRloc16, - RadioTypeToString(aInfo)); + OutputLine(" %s:0x%04x radio:%s", aIsRx ? "from" : "to", aInfo.mNeighborRloc16, RadioTypeToString(aInfo)); otIp6SockAddrToString(&aInfo.mSource, addrString, sizeof(addrString)); - mInterpreter.OutputLine(kIndentSize, "src:%s", addrString); + OutputLine(kIndentSize, "src:%s", addrString); otIp6SockAddrToString(&aInfo.mDestination, addrString, sizeof(addrString)); - mInterpreter.OutputLine(kIndentSize, "dst:%s", addrString); + OutputLine(kIndentSize, "dst:%s", addrString); } void History::OutputRxTxEntryTableFormat(const otHistoryTrackerMessageInfo &aInfo, uint32_t aEntryAge, bool aIsRx) @@ -579,40 +575,40 @@ void History::OutputRxTxEntryTableFormat(const otHistoryTrackerMessageInfo &aInf otHistoryTrackerEntryAgeToString(aEntryAge, ageString, sizeof(ageString)); - mInterpreter.OutputFormat("| %20s | %-16.16s | %5u | 0x%04x | %3s | %4s | ", "", MessageTypeToString(aInfo), - aInfo.mPayloadLength, aInfo.mChecksum, aInfo.mLinkSecurity ? "yes" : "no", - MessagePriorityToString(aInfo.mPriority)); + OutputFormat("| %20s | %-16.16s | %5u | 0x%04x | %3s | %4s | ", "", MessageTypeToString(aInfo), + aInfo.mPayloadLength, aInfo.mChecksum, aInfo.mLinkSecurity ? "yes" : "no", + MessagePriorityToString(aInfo.mPriority)); if (aIsRx) { - mInterpreter.OutputFormat("%4d | RX ", aInfo.mAveRxRss); + OutputFormat("%4d | RX ", aInfo.mAveRxRss); } else { - mInterpreter.OutputFormat(" NA |"); - mInterpreter.OutputFormat(aInfo.mTxSuccess ? " TX " : "TX-F"); + OutputFormat(" NA |"); + OutputFormat(aInfo.mTxSuccess ? " TX " : "TX-F"); } if (aInfo.mNeighborRloc16 == kShortAddrBroadcast) { - mInterpreter.OutputFormat("| bcast "); + OutputFormat("| bcast "); } else if (aInfo.mNeighborRloc16 == kShortAddrInvalid) { - mInterpreter.OutputFormat("| unknwn "); + OutputFormat("| unknwn "); } else { - mInterpreter.OutputFormat("| 0x%04x ", aInfo.mNeighborRloc16); + OutputFormat("| 0x%04x ", aInfo.mNeighborRloc16); } - mInterpreter.OutputLine("| %5.5s |", RadioTypeToString(aInfo)); + OutputLine("| %5.5s |", RadioTypeToString(aInfo)); otIp6SockAddrToString(&aInfo.mSource, addrString, sizeof(addrString)); - mInterpreter.OutputLine("| %20s | src: %-70s |", ageString, addrString); + OutputLine("| %20s | src: %-70s |", ageString, addrString); otIp6SockAddrToString(&aInfo.mDestination, addrString, sizeof(addrString)); - mInterpreter.OutputLine("| %20s | dst: %-70s |", "", addrString); + OutputLine("| %20s | dst: %-70s |", "", addrString); } otError History::Process(Arg aArgs[]) diff --git a/src/cli/cli_history.hpp b/src/cli/cli_history.hpp index c7a1bf512..61ea89990 100644 --- a/src/cli/cli_history.hpp +++ b/src/cli/cli_history.hpp @@ -39,6 +39,7 @@ #include #include "cli/cli_config.h" +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -47,13 +48,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the History Tracker CLI interpreter. * */ -class History +class History : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -61,11 +60,11 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit History(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) + explicit History(Output &aOutput) + : OutputWrapper(aOutput) { } @@ -126,8 +125,6 @@ private: }; static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - - Interpreter &mInterpreter; }; } // namespace Cli diff --git a/src/cli/cli_joiner.cpp b/src/cli/cli_joiner.cpp index 435fedc13..231d0433d 100644 --- a/src/cli/cli_joiner.cpp +++ b/src/cli/cli_joiner.cpp @@ -50,11 +50,11 @@ otError Joiner::ProcessDiscerner(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - const otJoinerDiscerner *discerner = otJoinerGetDiscerner(mInterpreter.mInstance); + const otJoinerDiscerner *discerner = otJoinerGetDiscerner(GetInstancePtr()); VerifyOrExit(discerner != nullptr, error = OT_ERROR_NOT_FOUND); - mInterpreter.OutputLine("0x%llx/%u", static_cast(discerner->mValue), discerner->mLength); + OutputLine("0x%llx/%u", static_cast(discerner->mValue), discerner->mLength); error = OT_ERROR_NONE; } else @@ -65,13 +65,13 @@ otError Joiner::ProcessDiscerner(Arg aArgs[]) if (aArgs[0] == "clear") { - error = otJoinerSetDiscerner(mInterpreter.mInstance, nullptr); + error = otJoinerSetDiscerner(GetInstancePtr(), nullptr); } else { VerifyOrExit(aArgs[1].IsEmpty()); SuccessOrExit(Interpreter::ParseJoinerDiscerner(aArgs[0], discerner)); - error = otJoinerSetDiscerner(mInterpreter.mInstance, &discerner); + error = otJoinerSetDiscerner(GetInstancePtr(), &discerner); } } @@ -85,7 +85,7 @@ otError Joiner::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -95,8 +95,7 @@ otError Joiner::ProcessId(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - mInterpreter.OutputExtAddress(*otJoinerGetId(mInterpreter.mInstance)); - mInterpreter.OutputLine(""); + OutputExtAddressLine(*otJoinerGetId(GetInstancePtr())); return OT_ERROR_NONE; } @@ -107,7 +106,7 @@ otError Joiner::ProcessStart(Arg aArgs[]) VerifyOrExit(!aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = otJoinerStart(mInterpreter.mInstance, + error = otJoinerStart(GetInstancePtr(), aArgs[0].GetCString(), // aPskd aArgs[1].GetCString(), // aProvisioningUrl (nullptr if aArgs[1] is empty) PACKAGE_NAME, // aVendorName @@ -124,7 +123,7 @@ otError Joiner::ProcessStop(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otJoinerStop(mInterpreter.mInstance); + otJoinerStop(GetInstancePtr()); return OT_ERROR_NONE; } @@ -159,11 +158,11 @@ void Joiner::HandleCallback(otError aError) switch (aError) { case OT_ERROR_NONE: - mInterpreter.OutputLine("Join success"); + OutputLine("Join success"); break; default: - mInterpreter.OutputLine("Join failed [%s]", otThreadErrorToString(aError)); + OutputLine("Join failed [%s]", otThreadErrorToString(aError)); break; } } diff --git a/src/cli/cli_joiner.hpp b/src/cli/cli_joiner.hpp index 422cff34e..a97f00eeb 100644 --- a/src/cli/cli_joiner.hpp +++ b/src/cli/cli_joiner.hpp @@ -38,6 +38,7 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -46,13 +47,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the Joiner CLI interpreter. * */ -class Joiner +class Joiner : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -60,11 +59,11 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit Joiner(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) + explicit Joiner(Output &aOutput) + : OutputWrapper(aOutput) { } @@ -98,8 +97,6 @@ private: }; static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - - Interpreter &mInterpreter; }; } // namespace Cli diff --git a/src/cli/cli_network_data.cpp b/src/cli/cli_network_data.cpp index 67352f367..9765fb240 100644 --- a/src/cli/cli_network_data.cpp +++ b/src/cli/cli_network_data.cpp @@ -45,11 +45,6 @@ namespace Cli { constexpr NetworkData::Command NetworkData::sCommands[]; -NetworkData::NetworkData(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) -{ -} - void NetworkData::OutputPrefix(const otBorderRouterConfig &aConfig) { enum @@ -63,7 +58,7 @@ void NetworkData::OutputPrefix(const otBorderRouterConfig &aConfig) char flagsString[kMaxFlagStringSize]; char *flagsPtr = &flagsString[0]; - mInterpreter.OutputIp6Prefix(aConfig.mPrefix); + OutputIp6Prefix(aConfig.mPrefix); if (aConfig.mPreferred) { @@ -114,12 +109,12 @@ void NetworkData::OutputPrefix(const otBorderRouterConfig &aConfig) if (flagsPtr != &flagsString[0]) { - mInterpreter.OutputFormat(" %s", flagsString); + OutputFormat(" %s", flagsString); } OutputPreference(aConfig.mPreference); - mInterpreter.OutputLine(" %04x", aConfig.mRloc16); + OutputLine(" %04x", aConfig.mRloc16); } void NetworkData::OutputRoute(const otExternalRouteConfig &aConfig) @@ -135,7 +130,7 @@ void NetworkData::OutputRoute(const otExternalRouteConfig &aConfig) char flagsString[kMaxFlagStringSize]; char *flagsPtr = &flagsString[0]; - mInterpreter.OutputIp6Prefix(aConfig.mPrefix); + OutputIp6Prefix(aConfig.mPrefix); if (aConfig.mStable) { @@ -151,12 +146,12 @@ void NetworkData::OutputRoute(const otExternalRouteConfig &aConfig) if (flagsPtr != &flagsString[0]) { - mInterpreter.OutputFormat(" %s", flagsString); + OutputFormat(" %s", flagsString); } OutputPreference(aConfig.mPreference); - mInterpreter.OutputLine(" %04x", aConfig.mRloc16); + OutputLine(" %04x", aConfig.mRloc16); } void NetworkData::OutputPreference(signed int aPreference) @@ -164,15 +159,15 @@ void NetworkData::OutputPreference(signed int aPreference) switch (aPreference) { case OT_ROUTE_PREFERENCE_LOW: - mInterpreter.OutputFormat(" low"); + OutputFormat(" low"); break; case OT_ROUTE_PREFERENCE_MED: - mInterpreter.OutputFormat(" med"); + OutputFormat(" med"); break; case OT_ROUTE_PREFERENCE_HIGH: - mInterpreter.OutputFormat(" high"); + OutputFormat(" high"); break; default: @@ -182,17 +177,17 @@ void NetworkData::OutputPreference(signed int aPreference) void NetworkData::OutputService(const otServiceConfig &aConfig) { - mInterpreter.OutputFormat("%u ", aConfig.mEnterpriseNumber); - mInterpreter.OutputBytes(aConfig.mServiceData, aConfig.mServiceDataLength); - mInterpreter.OutputFormat(" "); - mInterpreter.OutputBytes(aConfig.mServerConfig.mServerData, aConfig.mServerConfig.mServerDataLength); + OutputFormat("%u ", aConfig.mEnterpriseNumber); + OutputBytes(aConfig.mServiceData, aConfig.mServiceDataLength); + OutputFormat(" "); + OutputBytes(aConfig.mServerConfig.mServerData, aConfig.mServerConfig.mServerDataLength); if (aConfig.mServerConfig.mStable) { - mInterpreter.OutputFormat(" s"); + OutputFormat(" s"); } - mInterpreter.OutputLine(" %04x", aConfig.mServerConfig.mRloc16); + OutputLine(" %04x", aConfig.mServerConfig.mRloc16); } otError NetworkData::ProcessHelp(Arg aArgs[]) @@ -201,7 +196,7 @@ otError NetworkData::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -220,7 +215,7 @@ otError NetworkData::ProcessPublish(Arg aArgs[]) uint8_t sequenceNumber; SuccessOrExit(error = aArgs[2].ParseAsUint8(sequenceNumber)); - otNetDataPublishDnsSrpServiceAnycast(mInterpreter.mInstance, sequenceNumber); + otNetDataPublishDnsSrpServiceAnycast(GetInstancePtr(), sequenceNumber); ExitNow(); } @@ -232,13 +227,13 @@ otError NetworkData::ProcessPublish(Arg aArgs[]) if (aArgs[3].IsEmpty()) { SuccessOrExit(error = aArgs[2].ParseAsUint16(port)); - otNetDataPublishDnsSrpServiceUnicastMeshLocalEid(mInterpreter.mInstance, port); + otNetDataPublishDnsSrpServiceUnicastMeshLocalEid(GetInstancePtr(), port); ExitNow(); } SuccessOrExit(error = aArgs[2].ParseAsIp6Address(address)); SuccessOrExit(error = aArgs[3].ParseAsUint16(port)); - otNetDataPublishDnsSrpServiceUnicast(mInterpreter.mInstance, &address, port); + otNetDataPublishDnsSrpServiceUnicast(GetInstancePtr(), &address, port); ExitNow(); } } @@ -250,7 +245,7 @@ otError NetworkData::ProcessPublish(Arg aArgs[]) otBorderRouterConfig config; SuccessOrExit(error = Interpreter::ParsePrefix(aArgs + 1, config)); - error = otNetDataPublishOnMeshPrefix(mInterpreter.mInstance, &config); + error = otNetDataPublishOnMeshPrefix(GetInstancePtr(), &config); ExitNow(); } @@ -259,7 +254,7 @@ otError NetworkData::ProcessPublish(Arg aArgs[]) otExternalRouteConfig config; SuccessOrExit(error = Interpreter::ParseRoute(aArgs + 1, config)); - error = otNetDataPublishExternalRoute(mInterpreter.mInstance, &config); + error = otNetDataPublishExternalRoute(GetInstancePtr(), &config); ExitNow(); } #endif // OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE @@ -277,7 +272,7 @@ otError NetworkData::ProcessUnpublish(Arg aArgs[]) #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE if (aArgs[0] == "dnssrp") { - otNetDataUnpublishDnsSrpService(mInterpreter.mInstance); + otNetDataUnpublishDnsSrpService(GetInstancePtr()); ExitNow(); } #endif @@ -288,7 +283,7 @@ otError NetworkData::ProcessUnpublish(Arg aArgs[]) if (aArgs[0].ParseAsIp6Prefix(prefix) == OT_ERROR_NONE) { - error = otNetDataUnpublishPrefix(mInterpreter.mInstance, &prefix); + error = otNetDataUnpublishPrefix(GetInstancePtr(), &prefix); ExitNow(); } } @@ -309,9 +304,9 @@ otError NetworkData::ProcessRegister(Arg aArgs[]) otError error = OT_ERROR_NONE; #if OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE - SuccessOrExit(error = otBorderRouterRegister(mInterpreter.mInstance)); + SuccessOrExit(error = otBorderRouterRegister(GetInstancePtr())); #else - SuccessOrExit(error = otServerRegister(mInterpreter.mInstance)); + SuccessOrExit(error = otServerRegister(GetInstancePtr())); #endif exit: @@ -339,11 +334,11 @@ otError NetworkData::ProcessSteeringData(Arg aArgs[]) if (discerner.mLength) { - error = otNetDataSteeringDataCheckJoinerWithDiscerner(mInterpreter.mInstance, &discerner); + error = otNetDataSteeringDataCheckJoinerWithDiscerner(GetInstancePtr(), &discerner); } else { - error = otNetDataSteeringDataCheckJoiner(mInterpreter.mInstance, &addr); + error = otNetDataSteeringDataCheckJoiner(GetInstancePtr(), &addr); } exit: @@ -355,9 +350,9 @@ void NetworkData::OutputPrefixes(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otBorderRouterConfig config; - mInterpreter.OutputLine("Prefixes:"); + OutputLine("Prefixes:"); - while (otNetDataGetNextOnMeshPrefix(mInterpreter.mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otNetDataGetNextOnMeshPrefix(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { OutputPrefix(config); } @@ -368,9 +363,9 @@ void NetworkData::OutputRoutes(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig config; - mInterpreter.OutputLine("Routes:"); + OutputLine("Routes:"); - while (otNetDataGetNextRoute(mInterpreter.mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otNetDataGetNextRoute(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { OutputRoute(config); } @@ -381,9 +376,9 @@ void NetworkData::OutputServices(void) otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT; otServiceConfig config; - mInterpreter.OutputLine("Services:"); + OutputLine("Services:"); - while (otNetDataGetNextService(mInterpreter.mInstance, &iterator, &config) == OT_ERROR_NONE) + while (otNetDataGetNextService(GetInstancePtr(), &iterator, &config) == OT_ERROR_NONE) { OutputService(config); } @@ -395,10 +390,9 @@ otError NetworkData::OutputBinary(void) uint8_t data[255]; uint8_t len = sizeof(data); - SuccessOrExit(error = otNetDataGet(mInterpreter.mInstance, false, data, &len)); + SuccessOrExit(error = otNetDataGet(GetInstancePtr(), false, data, &len)); - mInterpreter.OutputBytes(data, static_cast(len)); - mInterpreter.OutputLine(""); + OutputBytesLine(data, static_cast(len)); exit: return error; diff --git a/src/cli/cli_network_data.hpp b/src/cli/cli_network_data.hpp index 908887618..e8304556c 100644 --- a/src/cli/cli_network_data.hpp +++ b/src/cli/cli_network_data.hpp @@ -38,19 +38,18 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the Network Data CLI. * */ -class NetworkData +class NetworkData : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -58,10 +57,13 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context * */ - explicit NetworkData(Interpreter &aInterpreter); + explicit NetworkData(Output &aOutput) + : OutputWrapper(aOutput) + { + } /** * This method interprets a list of CLI arguments. @@ -127,15 +129,14 @@ private: #if OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE || OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE {"register", &NetworkData::ProcessRegister}, #endif - {"show", &NetworkData::ProcessShow}, {"steeringdata", &NetworkData::ProcessSteeringData}, + {"show", &NetworkData::ProcessShow}, + {"steeringdata", &NetworkData::ProcessSteeringData}, #if OPENTHREAD_CONFIG_NETDATA_PUBLISHER_ENABLE {"unpublish", &NetworkData::ProcessUnpublish}, #endif }; static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - - Interpreter &mInterpreter; }; } // namespace Cli diff --git a/src/cli/cli_output.cpp b/src/cli/cli_output.cpp new file mode 100644 index 000000000..7e65eb00c --- /dev/null +++ b/src/cli/cli_output.cpp @@ -0,0 +1,360 @@ +/* + * Copyright (c) 2021, 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 contains implementation of the CLI output module. + */ + +#include "cli_output.hpp" + +#include +#include +#include + +#if OPENTHREAD_FTD || OPENTHREAD_MTD +#include +#endif + +#include "common/logging.hpp" +#include "common/string.hpp" + +namespace ot { +namespace Cli { + +Output::Output(otInstance *aInstance, otCliOutputCallback aCallback, void *aCallbackContext) + : mInstance(aInstance) + , mCallback(aCallback) + , mCallbackContext(aCallbackContext) +#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE + , mOutputLength(0) + , mIsLogging(false) +#endif +{ +} + +void Output::OutputFormat(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + OutputFormatV(aFormat, args); + va_end(args); +} + +void Output::OutputFormat(uint8_t aIndentSize, const char *aFormat, ...) +{ + va_list args; + + OutputSpaces(aIndentSize); + + va_start(args, aFormat); + OutputFormatV(aFormat, args); + va_end(args); +} + +void Output::OutputLine(const char *aFormat, ...) +{ + va_list args; + + va_start(args, aFormat); + OutputFormatV(aFormat, args); + va_end(args); + + OutputFormat("\r\n"); +} + +void Output::OutputLine(uint8_t aIndentSize, const char *aFormat, ...) +{ + va_list args; + + OutputSpaces(aIndentSize); + + va_start(args, aFormat); + OutputFormatV(aFormat, args); + va_end(args); + + OutputFormat("\r\n"); +} + +void Output::OutputSpaces(uint8_t aCount) +{ + char format[sizeof("%256s")]; + + snprintf(format, sizeof(format), "%%%us", aCount); + + OutputFormat(format, ""); +} + +void Output::OutputBytes(const uint8_t *aBytes, uint16_t aLength) +{ + for (uint16_t i = 0; i < aLength; i++) + { + OutputFormat("%02x", aBytes[i]); + } +} + +void Output::OutputBytesLine(const uint8_t *aBytes, uint16_t aLength) +{ + OutputBytes(aBytes, aLength); + OutputLine(""); +} + +void Output::OutputEnabledDisabledStatus(bool aEnabled) +{ + OutputLine(aEnabled ? "Enabled" : "Disabled"); +} + +#if OPENTHREAD_FTD || OPENTHREAD_MTD + +void Output::OutputIp6Address(const otIp6Address &aAddress) +{ + char string[OT_IP6_ADDRESS_STRING_SIZE]; + + otIp6AddressToString(&aAddress, string, sizeof(string)); + + return OutputFormat("%s", string); +} + +void Output::OutputIp6AddressLine(const otIp6Address &aAddress) +{ + OutputIp6Address(aAddress); + OutputLine(""); +} + +void Output::OutputIp6Prefix(const otIp6Prefix &aPrefix) +{ + char string[OT_IP6_PREFIX_STRING_SIZE]; + + otIp6PrefixToString(&aPrefix, string, sizeof(string)); + + OutputFormat("%s", string); +} + +void Output::OutputIp6PrefixLine(const otIp6Prefix &aPrefix) +{ + OutputIp6Prefix(aPrefix); + OutputLine(""); +} + +void Output::OutputIp6Prefix(const otIp6NetworkPrefix &aPrefix) +{ + OutputFormat("%x:%x:%x:%x::/64", (aPrefix.m8[0] << 8) | aPrefix.m8[1], (aPrefix.m8[2] << 8) | aPrefix.m8[3], + (aPrefix.m8[4] << 8) | aPrefix.m8[5], (aPrefix.m8[6] << 8) | aPrefix.m8[7]); +} + +void Output::OutputIp6PrefixLine(const otIp6NetworkPrefix &aPrefix) +{ + OutputIp6Prefix(aPrefix); + OutputLine(""); +} + +void Output::OutputDnsTxtData(const uint8_t *aTxtData, uint16_t aTxtDataLength) +{ + otDnsTxtEntry entry; + otDnsTxtEntryIterator iterator; + bool isFirst = true; + + otDnsInitTxtEntryIterator(&iterator, aTxtData, aTxtDataLength); + + OutputFormat("["); + + while (otDnsGetNextTxtEntry(&iterator, &entry) == OT_ERROR_NONE) + { + if (!isFirst) + { + OutputFormat(", "); + } + + if (entry.mKey == nullptr) + { + // A null `mKey` indicates that the key in the entry is + // longer than the recommended max key length, so the entry + // could not be parsed. In this case, the whole entry is + // returned encoded in `mValue`. + + OutputFormat("["); + OutputBytes(entry.mValue, entry.mValueLength); + OutputFormat("]"); + } + else + { + OutputFormat("%s", entry.mKey); + + if (entry.mValue != nullptr) + { + OutputFormat("="); + OutputBytes(entry.mValue, entry.mValueLength); + } + } + + isFirst = false; + } + + OutputFormat("]"); +} +#endif // OPENTHREAD_FTD || OPENTHREAD_MTD + +void Output::OutputFormatV(const char *aFormat, va_list aArguments) +{ +#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE + va_list args; + int charsWritten; + bool truncated = false; + + va_copy(args, aArguments); +#endif + + mCallback(mCallbackContext, aFormat, aArguments); + +#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE + VerifyOrExit(!IsLogging()); + + charsWritten = vsnprintf(&mOutputString[mOutputLength], sizeof(mOutputString) - mOutputLength, aFormat, args); + + VerifyOrExit(charsWritten >= 0, mOutputLength = 0); + + if (static_cast(charsWritten) >= sizeof(mOutputString) - mOutputLength) + { + truncated = true; + mOutputLength = sizeof(mOutputString) - 1; + } + else + { + mOutputLength += charsWritten; + } + + while (true) + { + char *lineEnd = strchr(mOutputString, '\r'); + + if (lineEnd == nullptr) + { + break; + } + + *lineEnd = '\0'; + + if (lineEnd > mOutputString) + { + otLogNoteCli("Output: %s", mOutputString); + } + + lineEnd++; + + while ((*lineEnd == '\n') || (*lineEnd == '\r')) + { + lineEnd++; + } + + // Example of the pointers and lengths. + // + // - mOutputString = "hi\r\nmore" + // - mOutputLength = 8 + // - lineEnd = &mOutputString[4] + // + // + // 0 1 2 3 4 5 6 7 8 9 + // +----+----+----+----+----+----+----+----+----+--- + // | h | i | \r | \n | m | o | r | e | \0 | + // +----+----+----+----+----+----+----+----+----+--- + // ^ ^ + // | | + // lineEnd mOutputString[mOutputLength] + // + // + // New length is `&mOutputString[8] - &mOutputString[4] -> 4`. + // + // We move (newLen + 1 = 5) chars from `lineEnd` to start of + // `mOutputString` which will include the `\0` char. + // + // If `lineEnd` and `mOutputString[mOutputLength]` are the same + // the code works correctly as well (new length set to zero and + // the `\0` is copied). + + mOutputLength = static_cast(&mOutputString[mOutputLength] - lineEnd); + memmove(mOutputString, lineEnd, mOutputLength + 1); + } + + if (truncated) + { + otLogNoteCli("Output: %s ...", mOutputString); + mOutputLength = 0; + } + +exit: + va_end(args); +#endif // OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE +} + +void Output::OutputTableHeader(uint8_t aNumColumns, const char *const aTitles[], const uint8_t aWidths[]) +{ + for (uint8_t index = 0; index < aNumColumns; index++) + { + const char *title = aTitles[index]; + uint8_t width = aWidths[index]; + size_t titleLength = strlen(title); + + if (titleLength + 2 <= width) + { + // `title` fits in column width so we write it with extra space + // at beginning and end ("| Title |"). + + OutputFormat("| %*s", -static_cast(width - 1), title); + } + else + { + // Use narrow style (no space at beginning) and write as many + // chars from `title` as it can fit in the given column width + // ("|Title|"). + + OutputFormat("|%*.*s", -static_cast(width), width, title); + } + } + + OutputLine("|"); + OutputTableSeparator(aNumColumns, aWidths); +} + +void Output::OutputTableSeparator(uint8_t aNumColumns, const uint8_t aWidths[]) +{ + for (uint8_t index = 0; index < aNumColumns; index++) + { + OutputFormat("+"); + + for (uint8_t width = aWidths[index]; width != 0; width--) + { + OutputFormat("-"); + } + } + + OutputLine("+"); +} + +} // namespace Cli +} // namespace ot diff --git a/src/cli/cli_output.hpp b/src/cli/cli_output.hpp new file mode 100644 index 000000000..b501bbadf --- /dev/null +++ b/src/cli/cli_output.hpp @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2021, 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 contains definitions for the CLI output. + */ + +#ifndef CLI_OUTPUT_HPP_ +#define CLI_OUTPUT_HPP_ + +#include "openthread-core-config.h" + +#include + +#include + +#include "cli_config.h" + +namespace ot { +namespace Cli { + +/** + * This class provides CLI output helper methods. + * + */ +class Output +{ +public: + /** + * This constructor initializes the `Output` object. + * + * @param[in] aInstance A pointer to OpenThread instance. + * @param[in] aCallback A pointer to an `otCliOutputCallback` to deliver strings to the CLI console. + * @param[in] aCallbackContext An arbitrary context to pass in when invoking @p aCallback. + * + */ + Output(otInstance *aInstance, otCliOutputCallback aCallback, void *aCallbackContext); + + /** + * This method returns the pointer to OpenThread instance. + * + * @returns The pointer to the OpenThread instance. + * + */ + otInstance *GetInstancePtr(void) { return mInstance; } + + /** + * This method delivers a formatted output string to the CLI console. + * + * @param[in] aFormat A pointer to the format string. + * @param[in] ... A variable list of arguments to format. + * + */ + void OutputFormat(const char *aFormat, ...); + + /** + * This method delivers a formatted output string to the CLI console (to which it prepends a given number + * indentation space chars). + * + * @param[in] aIndentSize Number of indentation space chars to prepend to the string. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... A variable list of arguments to format. + * + */ + void OutputFormat(uint8_t aIndentSize, const char *aFormat, ...); + + /** + * This method delivers a formatted output string to the CLI console (to which it also appends newline "\r\n"). + * + * @param[in] aFormat A pointer to the format string. + * @param[in] ... A variable list of arguments to format. + * + */ + void OutputLine(const char *aFormat, ...); + + /** + * This method delivers a formatted output string to the CLI console (to which it prepends a given number + * indentation space chars and appends newline "\r\n"). + * + * @param[in] aIndentSize Number of indentation space chars to prepend to the string. + * @param[in] aFormat A pointer to the format string. + * @param[in] ... A variable list of arguments to format. + * + */ + void OutputLine(uint8_t aIndentSize, const char *aFormat, ...); + + /** + * This method outputs a given number of space chars to the CLI console. + * + * @param[in] aCount Number of space chars to output. + * + */ + void OutputSpaces(uint8_t aCount); + + /** + * This method outputs a number of bytes to the CLI console as a hex string. + * + * @param[in] aBytes A pointer to data which should be printed. + * @param[in] aLength @p aBytes length. + * + */ + void OutputBytes(const uint8_t *aBytes, uint16_t aLength); + + /** + * This method outputs a number of bytes to the CLI console as a hex string and at the end it also outputs newline + * "\r\n". + * + * @param[in] aBytes A pointer to data which should be printed. + * @param[in] aLength @p aBytes length. + * + */ + void OutputBytesLine(const uint8_t *aBytes, uint16_t aLength); + + /** + * This method outputs a number of bytes to the CLI console as a hex string. + * + * @tparam kBytesLength The length of @p aBytes array. + * + * @param[in] aBytes A array of @p kBytesLength bytes which should be printed. + * + */ + template void OutputBytes(const uint8_t (&aBytes)[kBytesLength]) + { + OutputBytes(aBytes, kBytesLength); + } + + /** + * This method outputs a number of bytes to the CLI console as a hex string and at the end it also outputs newline + * "\r\n". + * + * @tparam kBytesLength The length of @p aBytes array. + * + * @param[in] aBytes A array of @p kBytesLength bytes which should be printed. + * + */ + template void OutputBytesLine(const uint8_t (&aBytes)[kBytesLength]) + { + OutputBytesLine(aBytes, kBytesLength); + } + + /** + * This method outputs an Extended MAC Address to the CLI console. + * + * param[in] aExtAddress The Extended MAC Address to output. + * + */ + void OutputExtAddress(const otExtAddress &aExtAddress) { OutputBytes(aExtAddress.m8); } + + /** + * This method outputs an Extended MAC Address to the CLI console and at the end it also outputs newline "\r\n". + * + * param[in] aExtAddress The Extended MAC Address to output. + * + */ + void OutputExtAddressLine(const otExtAddress &aExtAddress) { OutputBytesLine(aExtAddress.m8); } + + /** + * This method outputs "Enabled" or "Disabled" status to the CLI console (it also appends newline "\r\n"). + * + * @param[in] aEnabled A boolean indicating the status. TRUE outputs "Enabled", FALSE outputs "Disabled". + * + */ + void OutputEnabledDisabledStatus(bool aEnabled); + +#if OPENTHREAD_FTD || OPENTHREAD_MTD + + /** + * This method outputs an IPv6 address to the CLI console. + * + * @param[in] aAddress A reference to the IPv6 address. + * + */ + void OutputIp6Address(const otIp6Address &aAddress); + + /** + * This method outputs an IPv6 address to the CLI console and at the end it also outputs newline "\r\n". + * + * @param[in] aAddress A reference to the IPv6 address. + * + */ + void OutputIp6AddressLine(const otIp6Address &aAddress); + + /** + * This method outputs an IPv6 prefix to the CLI console. + * + * @param[in] aPrefix A reference to the IPv6 prefix. + * + */ + void OutputIp6Prefix(const otIp6Prefix &aPrefix); + + /** + * This method outputs an IPv6 prefix to the CLI console and at the end it also outputs newline "\r\n". + * + * @param[in] aPrefix A reference to the IPv6 prefix. + * + */ + void OutputIp6PrefixLine(const otIp6Prefix &aPrefix); + + /** + * This method outputs an IPv6 network prefix to the CLI console. + * + * @param[in] aPrefix A reference to the IPv6 network prefix. + * + */ + void OutputIp6Prefix(const otIp6NetworkPrefix &aPrefix); + + /** + * This method outputs an IPv6 network prefix to the CLI console and at the end it also outputs newline "\r\n". + * + * @param[in] aPrefix A reference to the IPv6 network prefix. + * + */ + void OutputIp6PrefixLine(const otIp6NetworkPrefix &aPrefix); + + /** + * This method outputs DNS TXT data to the CLI console. + * + * @param[in] aTxtData A pointer to a buffer containing the DNS TXT data. + * @param[in] aTxtDataLength The length of @p aTxtData (in bytes). + * + */ + void OutputDnsTxtData(const uint8_t *aTxtData, uint16_t aTxtDataLength); + +#endif // OPENTHREAD_FTD || OPENTHREAD_MTD + + /** + * This method outputs a table header to the CLI console. + * + * An example of the table header format: + * + * | Title1 | Title2 |Title3| Title4 | + * +-----------+--------+------+----------------------+ + * + * The titles are left adjusted (extra white space is added at beginning if the column is width enough). The widths + * are specified as the number chars between two `|` chars (excluding the char `|` itself). + * + * @tparam kTableNumColumns The number columns in the table. + * + * @param[in] aTitles An array specifying the table column titles. + * @param[in] aWidth An array specifying the table column widths (in number of chars). + * + */ + template + void OutputTableHeader(const char *const (&aTitles)[kTableNumColumns], const uint8_t (&aWidths)[kTableNumColumns]) + { + OutputTableHeader(kTableNumColumns, &aTitles[0], &aWidths[0]); + } + + /** + * This method outputs a table separator to the CLI console. + * + * An example of the table separator: + * + * +-----------+--------+------+----------------------+ + * + * The widths are specified as number chars between two `+` chars (excluding the char `+` itself). + * + * @tparam kTableNumColumns The number columns in the table. + * + * @param[in] aWidth An array specifying the table column widths (in number of chars). + * + */ + template void OutputTableSeparator(const uint8_t (&aWidths)[kTableNumColumns]) + { + OutputTableSeparator(kTableNumColumns, &aWidths[0]); + } + +protected: + void OutputFormatV(const char *aFormat, va_list aArguments); + +#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE + bool IsLogging(void) const { return mIsLogging; } + void SetIsLogging(bool aIsLogging) { mIsLogging = aIsLogging; } +#endif + +private: + void OutputTableHeader(uint8_t aNumColumns, const char *const aTitles[], const uint8_t aWidths[]); + void OutputTableSeparator(uint8_t aNumColumns, const uint8_t aWidths[]); + + otInstance * mInstance; + otCliOutputCallback mCallback; + void * mCallbackContext; +#if OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_ENABLE + char mOutputString[OPENTHREAD_CONFIG_CLI_LOG_INPUT_OUTPUT_LOG_STRING_SIZE]; + uint16_t mOutputLength; + bool mIsLogging; +#endif +}; + +class OutputWrapper +{ +protected: + explicit OutputWrapper(Output &aOutput) + : mOutput(aOutput) + { + } + + otInstance *GetInstancePtr(void) { return mOutput.GetInstancePtr(); } + + template void OutputFormat(const char *aFormat, Args... aArgs) + { + mOutput.OutputFormat(aFormat, aArgs...); + } + + template void OutputFormat(uint8_t aIndentSize, const char *aFormat, Args... aArgs) + { + mOutput.OutputFormat(aIndentSize, aFormat, aArgs...); + } + + template void OutputLine(const char *aFormat, Args... aArgs) + { + return mOutput.OutputLine(aFormat, aArgs...); + } + + template void OutputLine(uint8_t aIndentSize, const char *aFormat, Args... aArgs) + { + return mOutput.OutputLine(aIndentSize, aFormat, aArgs...); + } + + template void OutputBytes(const uint8_t (&aBytes)[kBytesLength]) + { + mOutput.OutputBytes(aBytes, kBytesLength); + } + + template void OutputBytesLine(const uint8_t (&aBytes)[kBytesLength]) + { + mOutput.OutputBytesLine(aBytes, kBytesLength); + } + + void OutputSpaces(uint8_t aCount) { return mOutput.OutputSpaces(aCount); } + void OutputBytes(const uint8_t *aBytes, uint16_t aLength) { return mOutput.OutputBytes(aBytes, aLength); } + void OutputBytesLine(const uint8_t *aBytes, uint16_t aLength) { return mOutput.OutputBytesLine(aBytes, aLength); } + void OutputExtAddress(const otExtAddress &aExtAddress) { mOutput.OutputExtAddress(aExtAddress); } + void OutputExtAddressLine(const otExtAddress &aExtAddress) { mOutput.OutputExtAddressLine(aExtAddress); } + void OutputEnabledDisabledStatus(bool aEnabled) { mOutput.OutputEnabledDisabledStatus(aEnabled); } + +#if OPENTHREAD_FTD || OPENTHREAD_MTD + void OutputIp6Address(const otIp6Address &aAddress) { mOutput.OutputIp6Address(aAddress); } + void OutputIp6AddressLine(const otIp6Address &aAddress) { mOutput.OutputIp6AddressLine(aAddress); } + void OutputIp6Prefix(const otIp6Prefix &aPrefix) { mOutput.OutputIp6Prefix(aPrefix); } + void OutputIp6PrefixLine(const otIp6Prefix &aPrefix) { mOutput.OutputIp6PrefixLine(aPrefix); } + void OutputIp6Prefix(const otIp6NetworkPrefix &aPrefix) { mOutput.OutputIp6Prefix(aPrefix); } + void OutputIp6PrefixLine(const otIp6NetworkPrefix &aPrefix) { mOutput.OutputIp6PrefixLine(aPrefix); } + void OutputDnsTxtData(const uint8_t *aTxtData, uint16_t aTxtDataLength) + { + mOutput.OutputDnsTxtData(aTxtData, aTxtDataLength); + } +#endif + + template + void OutputTableHeader(const char *const (&aTitles)[kTableNumColumns], const uint8_t (&aWidths)[kTableNumColumns]) + { + mOutput.OutputTableHeader(aTitles, aWidths); + } + + template void OutputTableSeparator(const uint8_t (&aWidths)[kTableNumColumns]) + { + mOutput.OutputTableSeparator(aWidths); + } + +private: + Output &mOutput; +}; + +} // namespace Cli +} // namespace ot + +#endif // CLI_OUTPUT_HPP_ diff --git a/src/cli/cli_srp_client.cpp b/src/cli/cli_srp_client.cpp index 7703d3b31..980e743ca 100644 --- a/src/cli/cli_srp_client.cpp +++ b/src/cli/cli_srp_client.cpp @@ -59,11 +59,11 @@ exit: return error; } -SrpClient::SrpClient(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) +SrpClient::SrpClient(Output &aOutput) + : OutputWrapper(aOutput) , mCallbackEnabled(false) { - otSrpClientSetCallback(mInterpreter.mInstance, SrpClient::HandleCallback, this); + otSrpClientSetCallback(GetInstancePtr(), SrpClient::HandleCallback, this); } otError SrpClient::Process(Arg aArgs[]) @@ -95,7 +95,7 @@ otError SrpClient::ProcessAutoStart(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputEnabledDisabledStatus(otSrpClientIsAutoStartModeEnabled(mInterpreter.mInstance)); + OutputEnabledDisabledStatus(otSrpClientIsAutoStartModeEnabled(GetInstancePtr())); ExitNow(); } @@ -103,11 +103,11 @@ otError SrpClient::ProcessAutoStart(Arg aArgs[]) if (enable) { - otSrpClientEnableAutoStartMode(mInterpreter.mInstance, /* aCallback */ nullptr, /* aContext */ nullptr); + otSrpClientEnableAutoStartMode(GetInstancePtr(), /* aCallback */ nullptr, /* aContext */ nullptr); } else { - otSrpClientDisableAutoStartMode(mInterpreter.mInstance); + otSrpClientDisableAutoStartMode(GetInstancePtr()); } exit: @@ -122,7 +122,7 @@ otError SrpClient::ProcessCallback(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputEnabledDisabledStatus(mCallbackEnabled); + OutputEnabledDisabledStatus(mCallbackEnabled); ExitNow(); } @@ -138,7 +138,7 @@ otError SrpClient::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -150,7 +150,7 @@ otError SrpClient::ProcessHost(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputHostInfo(0, *otSrpClientGetHostInfo(mInterpreter.mInstance)); + OutputHostInfo(0, *otSrpClientGetHostInfo(GetInstancePtr())); ExitNow(); } @@ -158,8 +158,8 @@ otError SrpClient::ProcessHost(Arg aArgs[]) { if (aArgs[1].IsEmpty()) { - const char *name = otSrpClientGetHostInfo(mInterpreter.mInstance)->mName; - mInterpreter.OutputLine("%s", (name != nullptr) ? name : "(null)"); + const char *name = otSrpClientGetHostInfo(GetInstancePtr())->mName; + OutputLine("%s", (name != nullptr) ? name : "(null)"); } else { @@ -168,7 +168,7 @@ otError SrpClient::ProcessHost(Arg aArgs[]) char * hostName; VerifyOrExit(aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - hostName = otSrpClientBuffersGetHostNameString(mInterpreter.mInstance, &size); + hostName = otSrpClientBuffersGetHostNameString(GetInstancePtr(), &size); len = aArgs[1].GetLength(); VerifyOrExit(len + 1 <= size, error = OT_ERROR_INVALID_ARGS); @@ -179,28 +179,26 @@ otError SrpClient::ProcessHost(Arg aArgs[]) // This ensures that we do not overwrite a previous // buffer with a host name that cannot be set. - SuccessOrExit(error = otSrpClientSetHostName(mInterpreter.mInstance, aArgs[1].GetCString())); + SuccessOrExit(error = otSrpClientSetHostName(GetInstancePtr(), aArgs[1].GetCString())); memcpy(hostName, aArgs[1].GetCString(), len + 1); - IgnoreError(otSrpClientSetHostName(mInterpreter.mInstance, hostName)); + IgnoreError(otSrpClientSetHostName(GetInstancePtr(), hostName)); } } else if (aArgs[0] == "state") { VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - mInterpreter.OutputLine("%s", - otSrpClientItemStateToString(otSrpClientGetHostInfo(mInterpreter.mInstance)->mState)); + OutputLine("%s", otSrpClientItemStateToString(otSrpClientGetHostInfo(GetInstancePtr())->mState)); } else if (aArgs[0] == "address") { if (aArgs[1].IsEmpty()) { - const otSrpClientHostInfo *hostInfo = otSrpClientGetHostInfo(mInterpreter.mInstance); + const otSrpClientHostInfo *hostInfo = otSrpClientGetHostInfo(GetInstancePtr()); for (uint8_t index = 0; index < hostInfo->mNumAddresses; index++) { - mInterpreter.OutputIp6Address(hostInfo->mAddresses[index]); - mInterpreter.OutputLine(""); + OutputIp6AddressLine(hostInfo->mAddresses[index]); } } else @@ -210,7 +208,7 @@ otError SrpClient::ProcessHost(Arg aArgs[]) uint8_t arrayLength; otIp6Address *hostAddressArray; - hostAddressArray = otSrpClientBuffersGetHostAddressesArray(mInterpreter.mInstance, &arrayLength); + hostAddressArray = otSrpClientBuffersGetHostAddressesArray(GetInstancePtr(), &arrayLength); // We first make sure we can set the addresses, and if so // we copy the address list into the persisted address array @@ -230,10 +228,10 @@ otError SrpClient::ProcessHost(Arg aArgs[]) numAddresses++; } - SuccessOrExit(error = otSrpClientSetHostAddresses(mInterpreter.mInstance, addresses, numAddresses)); + SuccessOrExit(error = otSrpClientSetHostAddresses(GetInstancePtr(), addresses, numAddresses)); memcpy(hostAddressArray, addresses, numAddresses * sizeof(hostAddressArray[0])); - IgnoreError(otSrpClientSetHostAddresses(mInterpreter.mInstance, hostAddressArray, numAddresses)); + IgnoreError(otSrpClientSetHostAddresses(GetInstancePtr(), hostAddressArray, numAddresses)); } } else if (aArgs[0] == "remove") @@ -252,13 +250,13 @@ otError SrpClient::ProcessHost(Arg aArgs[]) } } - error = otSrpClientRemoveHostAndServices(mInterpreter.mInstance, removeKeyLease, sendUnregToServer); + error = otSrpClientRemoveHostAndServices(GetInstancePtr(), removeKeyLease, sendUnregToServer); } else if (aArgs[0] == "clear") { VerifyOrExit(aArgs[1].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otSrpClientClearHostAndServices(mInterpreter.mInstance); - otSrpClientBuffersFreeAllServices(mInterpreter.mInstance); + otSrpClientClearHostAndServices(GetInstancePtr()); + otSrpClientBuffersFreeAllServices(GetInstancePtr()); } else { @@ -271,25 +269,26 @@ exit: otError SrpClient::ProcessLeaseInterval(Arg aArgs[]) { - return mInterpreter.ProcessGetSet(aArgs, otSrpClientGetLeaseInterval, otSrpClientSetLeaseInterval); + return Interpreter::GetInterpreter().ProcessGetSet(aArgs, otSrpClientGetLeaseInterval, otSrpClientSetLeaseInterval); } otError SrpClient::ProcessKeyLeaseInterval(Arg aArgs[]) { - return mInterpreter.ProcessGetSet(aArgs, otSrpClientGetKeyLeaseInterval, otSrpClientSetKeyLeaseInterval); + return Interpreter::GetInterpreter().ProcessGetSet(aArgs, otSrpClientGetKeyLeaseInterval, + otSrpClientSetKeyLeaseInterval); } otError SrpClient::ProcessServer(Arg aArgs[]) { otError error = OT_ERROR_NONE; - const otSockAddr *serverSockAddr = otSrpClientGetServerAddress(mInterpreter.mInstance); + const otSockAddr *serverSockAddr = otSrpClientGetServerAddress(GetInstancePtr()); if (aArgs[0].IsEmpty()) { char string[OT_IP6_SOCK_ADDR_STRING_SIZE]; otIp6SockAddrToString(serverSockAddr, string, sizeof(string)); - mInterpreter.OutputLine(string); + OutputLine(string); ExitNow(); } @@ -297,12 +296,11 @@ otError SrpClient::ProcessServer(Arg aArgs[]) if (aArgs[0] == "address") { - mInterpreter.OutputIp6Address(serverSockAddr->mAddress); - mInterpreter.OutputLine(""); + OutputIp6AddressLine(serverSockAddr->mAddress); } else if (aArgs[0] == "port") { - mInterpreter.OutputLine("%u", serverSockAddr->mPort); + OutputLine("%u", serverSockAddr->mPort); } else { @@ -320,7 +318,7 @@ otError SrpClient::ProcessService(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - OutputServiceList(0, otSrpClientGetServices(mInterpreter.mInstance)); + OutputServiceList(0, otSrpClientGetServices(GetInstancePtr())); ExitNow(); } @@ -336,7 +334,7 @@ otError SrpClient::ProcessService(Arg aArgs[]) VerifyOrExit(!aArgs[2].IsEmpty() && aArgs[3].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - for (service = otSrpClientGetServices(mInterpreter.mInstance); service != nullptr; service = service->mNext) + for (service = otSrpClientGetServices(GetInstancePtr()); service != nullptr; service = service->mNext) { if ((aArgs[1] == service->mInstanceName) && (aArgs[2] == service->mName)) { @@ -348,15 +346,14 @@ otError SrpClient::ProcessService(Arg aArgs[]) if (isRemove) { - error = otSrpClientRemoveService(mInterpreter.mInstance, const_cast(service)); + error = otSrpClientRemoveService(GetInstancePtr(), const_cast(service)); } else { - SuccessOrExit( - error = otSrpClientClearService(mInterpreter.mInstance, const_cast(service))); + SuccessOrExit(error = otSrpClientClearService(GetInstancePtr(), const_cast(service))); - otSrpClientBuffersFreeService(mInterpreter.mInstance, reinterpret_cast( - const_cast(service))); + otSrpClientBuffersFreeService(GetInstancePtr(), reinterpret_cast( + const_cast(service))); } } #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE @@ -368,13 +365,13 @@ otError SrpClient::ProcessService(Arg aArgs[]) if (aArgs[1].IsEmpty()) { - mInterpreter.OutputEnabledDisabledStatus(otSrpClientIsServiceKeyRecordEnabled(mInterpreter.mInstance)); + OutputEnabledDisabledStatus(otSrpClientIsServiceKeyRecordEnabled(GetInstancePtr())); ExitNow(); } SuccessOrExit(error = Interpreter::ParseEnableOrDisable(aArgs[1], enable)); VerifyOrExit(aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otSrpClientSetServiceKeyRecordEnabled(mInterpreter.mInstance, enable); + otSrpClientSetServiceKeyRecordEnabled(GetInstancePtr(), enable); } #endif // OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE else @@ -396,7 +393,7 @@ otError SrpClient::ProcessServiceAdd(Arg aArgs[]) otError error; char * label; - entry = otSrpClientBuffersAllocateService(mInterpreter.mInstance); + entry = otSrpClientBuffersAllocateService(GetInstancePtr()); VerifyOrExit(entry != nullptr, error = OT_ERROR_NO_BUFS); @@ -465,14 +462,14 @@ otError SrpClient::ProcessServiceAdd(Arg aArgs[]) entry->mService.mNumTxtEntries = 0; } - SuccessOrExit(error = otSrpClientAddService(mInterpreter.mInstance, &entry->mService)); + SuccessOrExit(error = otSrpClientAddService(GetInstancePtr(), &entry->mService)); entry = nullptr; exit: if (entry != nullptr) { - otSrpClientBuffersFreeService(mInterpreter.mInstance, entry); + otSrpClientBuffersFreeService(GetInstancePtr(), entry); } return error; @@ -480,30 +477,30 @@ exit: void SrpClient::OutputHostInfo(uint8_t aIndentSize, const otSrpClientHostInfo &aHostInfo) { - mInterpreter.OutputFormat(aIndentSize, "name:"); + OutputFormat(aIndentSize, "name:"); if (aHostInfo.mName != nullptr) { - mInterpreter.OutputFormat("\"%s\"", aHostInfo.mName); + OutputFormat("\"%s\"", aHostInfo.mName); } else { - mInterpreter.OutputFormat("(null)"); + OutputFormat("(null)"); } - mInterpreter.OutputFormat(", state:%s, addrs:[", otSrpClientItemStateToString(aHostInfo.mState)); + OutputFormat(", state:%s, addrs:[", otSrpClientItemStateToString(aHostInfo.mState)); for (uint8_t index = 0; index < aHostInfo.mNumAddresses; index++) { if (index > 0) { - mInterpreter.OutputFormat(", "); + OutputFormat(", "); } - mInterpreter.OutputIp6Address(aHostInfo.mAddresses[index]); + OutputIp6Address(aHostInfo.mAddresses[index]); } - mInterpreter.OutputLine("]"); + OutputLine("]"); } void SrpClient::OutputServiceList(uint8_t aIndentSize, const otSrpClientService *aServices) @@ -517,19 +514,18 @@ void SrpClient::OutputServiceList(uint8_t aIndentSize, const otSrpClientService void SrpClient::OutputService(uint8_t aIndentSize, const otSrpClientService &aService) { - mInterpreter.OutputFormat(aIndentSize, "instance:\"%s\", name:\"%s", aService.mInstanceName, aService.mName); + OutputFormat(aIndentSize, "instance:\"%s\", name:\"%s", aService.mInstanceName, aService.mName); if (aService.mSubTypeLabels != nullptr) { for (uint16_t index = 0; aService.mSubTypeLabels[index] != nullptr; index++) { - mInterpreter.OutputFormat(",%s", aService.mSubTypeLabels[index]); + OutputFormat(",%s", aService.mSubTypeLabels[index]); } } - mInterpreter.OutputLine("\", state:%s, port:%d, priority:%d, weight:%d", - otSrpClientItemStateToString(aService.mState), aService.mPort, aService.mPriority, - aService.mWeight); + OutputLine("\", state:%s, port:%d, priority:%d, weight:%d", otSrpClientItemStateToString(aService.mState), + aService.mPort, aService.mPriority, aService.mWeight); } otError SrpClient::ProcessStart(Arg aArgs[]) @@ -541,7 +537,7 @@ otError SrpClient::ProcessStart(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint16(serverSockAddr.mPort)); VerifyOrExit(aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = otSrpClientStart(mInterpreter.mInstance, &serverSockAddr); + error = otSrpClientStart(GetInstancePtr(), &serverSockAddr); exit: return error; @@ -553,7 +549,7 @@ otError SrpClient::ProcessState(Arg aArgs[]) VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - mInterpreter.OutputEnabledDisabledStatus(otSrpClientIsRunning(mInterpreter.mInstance)); + OutputEnabledDisabledStatus(otSrpClientIsRunning(GetInstancePtr())); exit: return error; @@ -564,7 +560,7 @@ otError SrpClient::ProcessStop(Arg aArgs[]) otError error = OT_ERROR_NONE; VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - otSrpClientStop(mInterpreter.mInstance); + otSrpClientStop(GetInstancePtr()); exit: return error; @@ -588,16 +584,16 @@ void SrpClient::HandleCallback(otError aError, if (mCallbackEnabled) { - mInterpreter.OutputLine("SRP client callback - error:%s", otThreadErrorToString(aError)); - mInterpreter.OutputLine("Host info:"); + OutputLine("SRP client callback - error:%s", otThreadErrorToString(aError)); + OutputLine("Host info:"); OutputHostInfo(kIndentSize, *aHostInfo); - mInterpreter.OutputLine("Service list:"); + OutputLine("Service list:"); OutputServiceList(kIndentSize, aServices); if (aRemovedServices != nullptr) { - mInterpreter.OutputLine("Removed service list:"); + OutputLine("Removed service list:"); OutputServiceList(kIndentSize, aRemovedServices); } } @@ -608,8 +604,8 @@ void SrpClient::HandleCallback(otError aError, { next = service->mNext; - otSrpClientBuffersFreeService(mInterpreter.mInstance, reinterpret_cast( - const_cast(service))); + otSrpClientBuffersFreeService(GetInstancePtr(), reinterpret_cast( + const_cast(service))); } } diff --git a/src/cli/cli_srp_client.hpp b/src/cli/cli_srp_client.hpp index 335fb35bd..deafedd34 100644 --- a/src/cli/cli_srp_client.hpp +++ b/src/cli/cli_srp_client.hpp @@ -40,6 +40,7 @@ #include #include "cli/cli_config.h" +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -48,13 +49,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the SRP Client CLI interpreter. * */ -class SrpClient +class SrpClient : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -62,10 +61,10 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context. * */ - explicit SrpClient(Interpreter &aInterpreter); + explicit SrpClient(Output &aOutput); /** * This method interprets a list of CLI arguments. @@ -131,8 +130,7 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - bool mCallbackEnabled; + bool mCallbackEnabled; }; } // namespace Cli diff --git a/src/cli/cli_srp_server.cpp b/src/cli/cli_srp_server.cpp index 8809e845d..88a097278 100644 --- a/src/cli/cli_srp_server.cpp +++ b/src/cli/cli_srp_server.cpp @@ -71,14 +71,14 @@ otError SrpServer::ProcessAddrMode(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - switch (otSrpServerGetAddressMode(mInterpreter.mInstance)) + switch (otSrpServerGetAddressMode(GetInstancePtr())) { case OT_SRP_SREVER_ADDRESS_MODE_UNICAST: - mInterpreter.OutputLine("unicast"); + OutputLine("unicast"); break; case OT_SRP_SERVER_ADDRESS_MODE_ANYCAST: - mInterpreter.OutputLine("anycast"); + OutputLine("anycast"); break; } @@ -86,11 +86,11 @@ otError SrpServer::ProcessAddrMode(Arg aArgs[]) } else if (aArgs[0] == "unicast") { - error = otSrpServerSetAddressMode(mInterpreter.mInstance, OT_SRP_SREVER_ADDRESS_MODE_UNICAST); + error = otSrpServerSetAddressMode(GetInstancePtr(), OT_SRP_SREVER_ADDRESS_MODE_UNICAST); } else if (aArgs[0] == "anycast") { - error = otSrpServerSetAddressMode(mInterpreter.mInstance, OT_SRP_SERVER_ADDRESS_MODE_ANYCAST); + error = otSrpServerSetAddressMode(GetInstancePtr(), OT_SRP_SERVER_ADDRESS_MODE_ANYCAST); } return error; @@ -102,11 +102,11 @@ otError SrpServer::ProcessDomain(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputLine("%s", otSrpServerGetDomain(mInterpreter.mInstance)); + OutputLine("%s", otSrpServerGetDomain(GetInstancePtr())); } else { - error = otSrpServerSetDomain(mInterpreter.mInstance, aArgs[0].GetCString()); + error = otSrpServerSetDomain(GetInstancePtr(), aArgs[0].GetCString()); } return error; @@ -116,19 +116,19 @@ otError SrpServer::ProcessState(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - switch (otSrpServerGetState(mInterpreter.mInstance)) + switch (otSrpServerGetState(GetInstancePtr())) { case OT_SRP_SERVER_STATE_DISABLED: - mInterpreter.OutputLine("disabled"); + OutputLine("disabled"); break; case OT_SRP_SERVER_STATE_RUNNING: - mInterpreter.OutputLine("running"); + OutputLine("running"); break; case OT_SRP_SERVER_STATE_STOPPED: - mInterpreter.OutputLine("stopped"); + OutputLine("stopped"); break; default: - mInterpreter.OutputLine("invalid state"); + OutputLine("invalid state"); break; } @@ -139,7 +139,7 @@ otError SrpServer::ProcessEnable(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otSrpServerSetEnabled(mInterpreter.mInstance, /* aEnabled */ true); + otSrpServerSetEnabled(GetInstancePtr(), /* aEnabled */ true); return OT_ERROR_NONE; } @@ -148,7 +148,7 @@ otError SrpServer::ProcessDisable(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - otSrpServerSetEnabled(mInterpreter.mInstance, /* aEnabled */ false); + otSrpServerSetEnabled(GetInstancePtr(), /* aEnabled */ false); return OT_ERROR_NONE; } @@ -160,11 +160,11 @@ otError SrpServer::ProcessLease(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - otSrpServerGetLeaseConfig(mInterpreter.mInstance, &leaseConfig); - mInterpreter.OutputLine("min lease: %u", leaseConfig.mMinLease); - mInterpreter.OutputLine("max lease: %u", leaseConfig.mMaxLease); - mInterpreter.OutputLine("min key-lease: %u", leaseConfig.mMinKeyLease); - mInterpreter.OutputLine("max key-lease: %u", leaseConfig.mMaxKeyLease); + otSrpServerGetLeaseConfig(GetInstancePtr(), &leaseConfig); + OutputLine("min lease: %u", leaseConfig.mMinLease); + OutputLine("max lease: %u", leaseConfig.mMaxLease); + OutputLine("min key-lease: %u", leaseConfig.mMinKeyLease); + OutputLine("max key-lease: %u", leaseConfig.mMaxKeyLease); } else { @@ -174,7 +174,7 @@ otError SrpServer::ProcessLease(Arg aArgs[]) SuccessOrExit(error = aArgs[3].ParseAsUint32(leaseConfig.mMaxKeyLease)); VerifyOrExit(aArgs[4].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = otSrpServerSetLeaseConfig(mInterpreter.mInstance, &leaseConfig); + error = otSrpServerSetLeaseConfig(GetInstancePtr(), &leaseConfig); } exit: @@ -189,34 +189,34 @@ otError SrpServer::ProcessHost(Arg aArgs[]) VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); host = nullptr; - while ((host = otSrpServerGetNextHost(mInterpreter.mInstance, host)) != nullptr) + while ((host = otSrpServerGetNextHost(GetInstancePtr(), host)) != nullptr) { const otIp6Address *addresses; uint8_t addressesNum; bool isDeleted = otSrpServerHostIsDeleted(host); - mInterpreter.OutputLine("%s", otSrpServerHostGetFullName(host)); - mInterpreter.OutputLine(Interpreter::kIndentSize, "deleted: %s", isDeleted ? "true" : "false"); + OutputLine("%s", otSrpServerHostGetFullName(host)); + OutputLine(kIndentSize, "deleted: %s", isDeleted ? "true" : "false"); if (isDeleted) { continue; } - mInterpreter.OutputSpaces(Interpreter::kIndentSize); - mInterpreter.OutputFormat("addresses: ["); + OutputSpaces(kIndentSize); + OutputFormat("addresses: ["); addresses = otSrpServerHostGetAddresses(host, &addressesNum); for (uint8_t i = 0; i < addressesNum; ++i) { - mInterpreter.OutputIp6Address(addresses[i]); + OutputIp6Address(addresses[i]); if (i < addressesNum - 1) { - mInterpreter.OutputFormat(", "); + OutputFormat(", "); } } - mInterpreter.OutputFormat("]\r\n"); + OutputFormat("]\r\n"); } exit: @@ -230,17 +230,17 @@ void SrpServer::OutputHostAddresses(const otSrpServerHost *aHost) addresses = otSrpServerHostGetAddresses(aHost, &addressesNum); - mInterpreter.OutputFormat("["); + OutputFormat("["); for (uint8_t i = 0; i < addressesNum; ++i) { if (i != 0) { - mInterpreter.OutputFormat(", "); + OutputFormat(", "); } - mInterpreter.OutputIp6Address(addresses[i]); + OutputIp6Address(addresses[i]); } - mInterpreter.OutputFormat("]"); + OutputFormat("]"); } otError SrpServer::ProcessService(Arg aArgs[]) @@ -253,7 +253,7 @@ otError SrpServer::ProcessService(Arg aArgs[]) VerifyOrExit(aArgs[0].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - while ((host = otSrpServerGetNextHost(mInterpreter.mInstance, host)) != nullptr) + while ((host = otSrpServerGetNextHost(GetInstancePtr(), host)) != nullptr) { const otSrpServerService *service = nullptr; @@ -267,15 +267,15 @@ otError SrpServer::ProcessService(Arg aArgs[]) uint16_t txtDataLength; bool hasSubType = false; - mInterpreter.OutputLine("%s", instanceName); - mInterpreter.OutputLine(Interpreter::kIndentSize, "deleted: %s", isDeleted ? "true" : "false"); + OutputLine("%s", instanceName); + OutputLine(kIndentSize, "deleted: %s", isDeleted ? "true" : "false"); if (isDeleted) { continue; } - mInterpreter.OutputFormat(Interpreter::kIndentSize, "subtypes: "); + OutputFormat(kIndentSize, "subtypes: "); while ((subService = otSrpServerHostFindNextService( host, subService, (OT_SRP_SERVER_SERVICE_FLAG_SUB_TYPE | OT_SRP_SERVER_SERVICE_FLAG_ACTIVE), @@ -284,26 +284,26 @@ otError SrpServer::ProcessService(Arg aArgs[]) char subLabel[OT_DNS_MAX_LABEL_SIZE]; IgnoreError(otSrpServerServiceGetServiceSubTypeLabel(subService, subLabel, sizeof(subLabel))); - mInterpreter.OutputFormat("%s%s", hasSubType ? "," : "", subLabel); + OutputFormat("%s%s", hasSubType ? "," : "", subLabel); hasSubType = true; } - mInterpreter.OutputLine(hasSubType ? "" : "(null)"); + OutputLine(hasSubType ? "" : "(null)"); - mInterpreter.OutputLine(Interpreter::kIndentSize, "port: %hu", otSrpServerServiceGetPort(service)); - mInterpreter.OutputLine(Interpreter::kIndentSize, "priority: %hu", otSrpServerServiceGetPriority(service)); - mInterpreter.OutputLine(Interpreter::kIndentSize, "weight: %hu", otSrpServerServiceGetWeight(service)); + OutputLine(kIndentSize, "port: %hu", otSrpServerServiceGetPort(service)); + OutputLine(kIndentSize, "priority: %hu", otSrpServerServiceGetPriority(service)); + OutputLine(kIndentSize, "weight: %hu", otSrpServerServiceGetWeight(service)); txtData = otSrpServerServiceGetTxtData(service, &txtDataLength); - mInterpreter.OutputFormat(Interpreter::kIndentSize, "TXT: "); - mInterpreter.OutputDnsTxtData(txtData, txtDataLength); - mInterpreter.OutputLine(""); + OutputFormat(kIndentSize, "TXT: "); + OutputDnsTxtData(txtData, txtDataLength); + OutputLine(""); - mInterpreter.OutputLine(Interpreter::kIndentSize, "host: %s", otSrpServerHostGetFullName(host)); + OutputLine(kIndentSize, "host: %s", otSrpServerHostGetFullName(host)); - mInterpreter.OutputFormat(Interpreter::kIndentSize, "addresses: "); + OutputFormat(kIndentSize, "addresses: "); OutputHostAddresses(host); - mInterpreter.OutputLine(""); + OutputLine(""); } } @@ -317,14 +317,14 @@ otError SrpServer::ProcessSeqNum(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputLine("%u", otSrpServerGetAnycastModeSequenceNumber(mInterpreter.mInstance)); + OutputLine("%u", otSrpServerGetAnycastModeSequenceNumber(GetInstancePtr())); } else { uint8_t sequenceNumber; SuccessOrExit(error = aArgs[0].ParseAsUint8(sequenceNumber)); - error = otSrpServerSetAnycastModeSequenceNumber(mInterpreter.mInstance, sequenceNumber); + error = otSrpServerSetAnycastModeSequenceNumber(GetInstancePtr(), sequenceNumber); } exit: @@ -337,7 +337,7 @@ otError SrpServer::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; diff --git a/src/cli/cli_srp_server.hpp b/src/cli/cli_srp_server.hpp index 11cf5b442..60e9f9b08 100644 --- a/src/cli/cli_srp_server.hpp +++ b/src/cli/cli_srp_server.hpp @@ -38,6 +38,7 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -46,13 +47,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements the SRP Server CLI interpreter. * */ -class SrpServer +class SrpServer : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -60,11 +59,11 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context. * */ - explicit SrpServer(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) + explicit SrpServer(Output &aOutput) + : OutputWrapper(aOutput) { } @@ -80,6 +79,8 @@ public: otError Process(Arg aArgs[]); private: + static constexpr uint8_t kIndentSize = 4; + struct Command { const char *mName; @@ -108,8 +109,6 @@ private: }; static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - - Interpreter &mInterpreter; }; } // namespace Cli diff --git a/src/cli/cli_tcp.cpp b/src/cli/cli_tcp.cpp index dafa1892f..d16e63aca 100644 --- a/src/cli/cli_tcp.cpp +++ b/src/cli/cli_tcp.cpp @@ -50,8 +50,8 @@ namespace Cli { constexpr TcpExample::Command TcpExample::sCommands[]; -TcpExample::TcpExample(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) +TcpExample::TcpExample(Output &aOutput) + : OutputWrapper(aOutput) , mInitialized(false) , mEndpointConnected(false) , mSendBusy(false) @@ -66,7 +66,7 @@ otError TcpExample::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -107,7 +107,7 @@ otError TcpExample::ProcessInit(Arg aArgs[]) endpointArgs.mReceiveBuffer = mReceiveBuffer; endpointArgs.mReceiveBufferSize = receiveBufferSize; - SuccessOrExit(error = otTcpEndpointInitialize(mInterpreter.mInstance, &mEndpoint, &endpointArgs)); + SuccessOrExit(error = otTcpEndpointInitialize(GetInstancePtr(), &mEndpoint, &endpointArgs)); } { @@ -118,7 +118,7 @@ otError TcpExample::ProcessInit(Arg aArgs[]) listenerArgs.mAcceptDoneCallback = HandleTcpAcceptDoneCallback; listenerArgs.mContext = this; - error = otTcpListenerInitialize(mInterpreter.mInstance, &mListener, &listenerArgs); + error = otTcpListenerInitialize(GetInstancePtr(), &mListener, &listenerArgs); if (error != OT_ERROR_NONE) { IgnoreReturnValue(otTcpEndpointDeinitialize(&mEndpoint)); @@ -373,7 +373,7 @@ void TcpExample::HandleTcpAcceptDoneCallback(otTcpListener * aListener, void TcpExample::HandleTcpEstablished(otTcpEndpoint *aEndpoint) { OT_UNUSED_VARIABLE(aEndpoint); - mInterpreter.OutputLine("TCP: Connection established"); + OutputLine("TCP: Connection established"); } void TcpExample::HandleTcpSendDone(otTcpEndpoint *aEndpoint, otLinkedBuffer *aData) @@ -399,7 +399,7 @@ void TcpExample::HandleTcpSendDone(otTcpEndpoint *aEndpoint, otLinkedBuffer *aDa aData->mLength = sizeof(mSendBuffer); if (otTcpSendByReference(&mEndpoint, aData, 0) != OT_ERROR_NONE) { - mInterpreter.OutputLine("TCP Benchmark Failed"); + OutputLine("TCP Benchmark Failed"); mBenchmarkBytesTotal = 0; } } @@ -408,11 +408,9 @@ void TcpExample::HandleTcpSendDone(otTcpEndpoint *aEndpoint, otLinkedBuffer *aDa uint32_t milliseconds = TimerMilli::GetNow() - mBenchmarkStart; uint32_t thousandTimesGoodput = (1000 * (mBenchmarkBytesTotal << 3) + (milliseconds >> 1)) / milliseconds; - mInterpreter.OutputLine("TCP Benchmark Complete: Transferred %u bytes in %u milliseconds", - static_cast(mBenchmarkBytesTotal), - static_cast(milliseconds)); - mInterpreter.OutputLine("TCP Goodput: %u.%03u kb/s", thousandTimesGoodput / 1000, - thousandTimesGoodput % 1000); + OutputLine("TCP Benchmark Complete: Transferred %u bytes in %u milliseconds", + static_cast(mBenchmarkBytesTotal), static_cast(milliseconds)); + OutputLine("TCP Goodput: %u.%03u kb/s", thousandTimesGoodput / 1000, thousandTimesGoodput % 1000); mBenchmarkBytesTotal = 0; } } @@ -434,8 +432,8 @@ void TcpExample::HandleTcpReceiveAvailable(otTcpEndpoint *aEndpoint, IgnoreError(otTcpReceiveByReference(aEndpoint, &data)); for (; data != nullptr; data = data->mNext) { - mInterpreter.OutputLine("TCP: Received %u bytes: %.*s", static_cast(data->mLength), - data->mLength, reinterpret_cast(data->mData)); + OutputLine("TCP: Received %u bytes: %.*s", static_cast(data->mLength), data->mLength, + reinterpret_cast(data->mData)); totalReceived += data->mLength; } OT_ASSERT(aBytesAvailable == totalReceived); @@ -444,7 +442,7 @@ void TcpExample::HandleTcpReceiveAvailable(otTcpEndpoint *aEndpoint, if (aEndOfStream) { - mInterpreter.OutputLine("TCP: Reached end of stream"); + OutputLine("TCP: Reached end of stream"); } } @@ -455,19 +453,19 @@ void TcpExample::HandleTcpDisconnected(otTcpEndpoint *aEndpoint, otTcpDisconnect switch (aReason) { case OT_TCP_DISCONNECTED_REASON_NORMAL: - mInterpreter.OutputLine("TCP: Disconnected"); + OutputLine("TCP: Disconnected"); break; case OT_TCP_DISCONNECTED_REASON_TIME_WAIT: - mInterpreter.OutputLine("TCP: Entered TIME-WAIT state"); + OutputLine("TCP: Entered TIME-WAIT state"); break; case OT_TCP_DISCONNECTED_REASON_TIMED_OUT: - mInterpreter.OutputLine("TCP: Connection timed out"); + OutputLine("TCP: Connection timed out"); break; case OT_TCP_DISCONNECTED_REASON_REFUSED: - mInterpreter.OutputLine("TCP: Connection refused"); + OutputLine("TCP: Connection refused"); break; case OT_TCP_DISCONNECTED_REASON_RESET: - mInterpreter.OutputLine("TCP: Connection reset"); + OutputLine("TCP: Connection reset"); break; } @@ -493,9 +491,9 @@ otTcpIncomingConnectionAction TcpExample::HandleTcpAcceptReady(otTcpListener * if (mEndpointConnected) { - mInterpreter.OutputFormat("TCP: Ignoring incoming connection request from ["); - mInterpreter.OutputIp6Address(aPeer->mAddress); - mInterpreter.OutputLine("]:%u (active socket is busy)", static_cast(aPeer->mPort)); + OutputFormat("TCP: Ignoring incoming connection request from ["); + OutputIp6Address(aPeer->mAddress); + OutputLine("]:%u (active socket is busy)", static_cast(aPeer->mPort)); return OT_TCP_INCOMING_CONNECTION_ACTION_DEFER; } @@ -509,9 +507,9 @@ void TcpExample::HandleTcpAcceptDone(otTcpListener *aListener, otTcpEndpoint *aE OT_UNUSED_VARIABLE(aListener); OT_UNUSED_VARIABLE(aEndpoint); - mInterpreter.OutputFormat("Accepted connection from ["); - mInterpreter.OutputIp6Address(aPeer->mAddress); - mInterpreter.OutputLine("]:%u", static_cast(aPeer->mPort)); + OutputFormat("Accepted connection from ["); + OutputIp6Address(aPeer->mAddress); + OutputLine("]:%u", static_cast(aPeer->mPort)); } } // namespace Cli diff --git a/src/cli/cli_tcp.hpp b/src/cli/cli_tcp.hpp index b30926dcb..7972b6147 100644 --- a/src/cli/cli_tcp.hpp +++ b/src/cli/cli_tcp.hpp @@ -39,6 +39,7 @@ #include #include "cli/cli_config.h" +#include "cli/cli_output.hpp" #include "common/time.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" @@ -46,13 +47,11 @@ namespace ot { namespace Cli { -class Interpreter; - /** * This class implements a CLI-based TCP example. * */ -class TcpExample +class TcpExample : private OutputWrapper { public: using Arg = Utils::CmdLineParser::Arg; @@ -60,13 +59,13 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutput The CLI console output context. * */ - explicit TcpExample(Interpreter &aInterpreter); + explicit TcpExample(Output &aOutput); /** - * This mehtod interprets a list of CLI arguments. + * This method interprets a list of CLI arguments. * * @param[in] aArgs An array of command line arguments. * @@ -134,8 +133,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - otTcpEndpoint mEndpoint; otTcpListener mListener; diff --git a/src/cli/cli_udp.cpp b/src/cli/cli_udp.cpp index a53d5b498..06ae9614f 100644 --- a/src/cli/cli_udp.cpp +++ b/src/cli/cli_udp.cpp @@ -44,8 +44,8 @@ namespace Cli { constexpr UdpExample::Command UdpExample::sCommands[]; -UdpExample::UdpExample(Interpreter &aInterpreter) - : mInterpreter(aInterpreter) +UdpExample::UdpExample(Output &aOutput) + : OutputWrapper(aOutput) , mLinkSecurityEnabled(true) { memset(&mSocket, 0, sizeof(mSocket)); @@ -57,7 +57,7 @@ otError UdpExample::ProcessHelp(Arg aArgs[]) for (const Command &command : sCommands) { - mInterpreter.OutputLine(command.mName); + OutputLine(command.mName); } return OT_ERROR_NONE; @@ -84,7 +84,7 @@ otError UdpExample::ProcessBind(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint16(sockaddr.mPort)); VerifyOrExit(aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = otUdpBind(mInterpreter.mInstance, &mSocket, &sockaddr, netif); + error = otUdpBind(GetInstancePtr(), &mSocket, &sockaddr, netif); exit: return error; @@ -99,7 +99,7 @@ otError UdpExample::ProcessConnect(Arg aArgs[]) SuccessOrExit(error = aArgs[1].ParseAsUint16(sockaddr.mPort)); VerifyOrExit(aArgs[2].IsEmpty(), error = OT_ERROR_INVALID_ARGS); - error = otUdpConnect(mInterpreter.mInstance, &mSocket, &sockaddr); + error = otUdpConnect(GetInstancePtr(), &mSocket, &sockaddr); exit: return error; @@ -109,7 +109,7 @@ otError UdpExample::ProcessClose(Arg aArgs[]) { OT_UNUSED_VARIABLE(aArgs); - return otUdpClose(mInterpreter.mInstance, &mSocket); + return otUdpClose(GetInstancePtr(), &mSocket); } otError UdpExample::ProcessOpen(Arg aArgs[]) @@ -118,8 +118,8 @@ otError UdpExample::ProcessOpen(Arg aArgs[]) otError error; - VerifyOrExit(!otUdpIsOpen(mInterpreter.mInstance, &mSocket), error = OT_ERROR_ALREADY); - error = otUdpOpen(mInterpreter.mInstance, &mSocket, HandleUdpReceive, this); + VerifyOrExit(!otUdpIsOpen(GetInstancePtr(), &mSocket), error = OT_ERROR_ALREADY); + error = otUdpOpen(GetInstancePtr(), &mSocket, HandleUdpReceive, this); exit: return error; @@ -148,7 +148,7 @@ otError UdpExample::ProcessSend(Arg aArgs[]) aArgs += 2; } - message = otUdpNewMessage(mInterpreter.mInstance, &messageSettings); + message = otUdpNewMessage(GetInstancePtr(), &messageSettings); VerifyOrExit(message != nullptr, error = OT_ERROR_NO_BUFS); if (aArgs[0] == "-s") @@ -180,7 +180,7 @@ otError UdpExample::ProcessSend(Arg aArgs[]) SuccessOrExit(error = otMessageAppend(message, aArgs[0].GetCString(), aArgs[0].GetLength())); } - SuccessOrExit(error = otUdpSend(mInterpreter.mInstance, &mSocket, message, &messageInfo)); + SuccessOrExit(error = otUdpSend(GetInstancePtr(), &mSocket, message, &messageInfo)); message = nullptr; @@ -199,7 +199,7 @@ otError UdpExample::ProcessLinkSecurity(Arg aArgs[]) if (aArgs[0].IsEmpty()) { - mInterpreter.OutputEnabledDisabledStatus(mLinkSecurityEnabled); + OutputEnabledDisabledStatus(mLinkSecurityEnabled); } else { @@ -296,14 +296,14 @@ void UdpExample::HandleUdpReceive(otMessage *aMessage, const otMessageInfo *aMes char buf[1500]; int length; - mInterpreter.OutputFormat("%d bytes from ", otMessageGetLength(aMessage) - otMessageGetOffset(aMessage)); - mInterpreter.OutputIp6Address(aMessageInfo->mPeerAddr); - mInterpreter.OutputFormat(" %d ", aMessageInfo->mPeerPort); + OutputFormat("%d bytes from ", otMessageGetLength(aMessage) - otMessageGetOffset(aMessage)); + OutputIp6Address(aMessageInfo->mPeerAddr); + OutputFormat(" %d ", aMessageInfo->mPeerPort); length = otMessageRead(aMessage, otMessageGetOffset(aMessage), buf, sizeof(buf) - 1); buf[length] = '\0'; - mInterpreter.OutputLine("%s", buf); + OutputLine("%s", buf); } } // namespace Cli diff --git a/src/cli/cli_udp.hpp b/src/cli/cli_udp.hpp index 9b8d590d7..85a4ba17c 100644 --- a/src/cli/cli_udp.hpp +++ b/src/cli/cli_udp.hpp @@ -38,19 +38,18 @@ #include +#include "cli/cli_output.hpp" #include "utils/lookup_table.hpp" #include "utils/parse_cmdline.hpp" namespace ot { namespace Cli { -class Interpreter; - /** * This class implements a CLI-based UDP example. * */ -class UdpExample +class UdpExample : private OutputWrapper { public: typedef Utils::CmdLineParser::Arg Arg; @@ -58,10 +57,10 @@ public: /** * Constructor * - * @param[in] aInterpreter The CLI interpreter. + * @param[in] aOutputContext The CLI console output context. * */ - explicit UdpExample(Interpreter &aInterpreter); + explicit UdpExample(Output &aOutput); /** * This method interprets a list of CLI arguments. @@ -104,8 +103,6 @@ private: static_assert(Utils::LookupTable::IsSorted(sCommands), "Command Table is not sorted"); - Interpreter &mInterpreter; - bool mLinkSecurityEnabled; otUdpSocket mSocket; }; diff --git a/src/cli/radio.cmake b/src/cli/radio.cmake index fb2958402..9b69a9e6b 100644 --- a/src/cli/radio.cmake +++ b/src/cli/radio.cmake @@ -43,6 +43,7 @@ target_include_directories(openthread-cli-radio PUBLIC ${OT_PUBLIC_INCLUDES} PRI target_sources(openthread-cli-radio PRIVATE cli.cpp + cli_output.cpp ) target_link_libraries(openthread-cli-radio