[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).
This commit is contained in:
Abtin Keshavarzian
2021-09-21 13:28:19 -07:00
committed by GitHub
parent 5b8ee97450
commit 6153855ae0
31 changed files with 1543 additions and 1299 deletions
+1
View File
@@ -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 \
+2
View File
@@ -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",
+1
View File
@@ -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
+3
View File
@@ -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 \
+250 -552
View File
File diff suppressed because it is too large Load Diff
+13 -164
View File
@@ -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 <uint8_t kBytesLength> 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<ValueType>(), aGetHandler(mInstance));
OutputLine(FormatStringFor<ValueType>(), aGetHandler(GetInstancePtr()));
exit:
return error;
@@ -380,7 +257,7 @@ private:
SuccessOrExit(error = aArgs[0].ParseAs<ValueType>(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<ValueType>(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 <uint8_t kTableNumColumns>
void OutputTableHeader(const char *const (&aTitles)[kTableNumColumns], const uint8_t (&aWidths)[kTableNumColumns])
{
OutputTableHeader(kTableNumColumns, &aTitles[0], aWidths);
}
template <uint8_t kTableNumColumns> 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
+58 -64
View File
@@ -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<uint8_t>(bytesToPrint));
OutputBytes(buf, static_cast<uint8_t>(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<uint16_t>(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<uint32_t>(observe));
OutputFormat(" OBS=%lu", static_cast<uint32_t>(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)
+6 -10
View File
@@ -40,19 +40,18 @@
#include <openthread/coap.h>
#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;
+56 -58
View File
@@ -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<uint8_t>(bytesToPrint));
OutputBytes(buf, static_cast<uint8_t>(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<uint8_t>(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<const uint8_t *>(OT_CLI_COAPS_X509_CERT),
otCoapSecureSetCertificate(GetInstancePtr(), reinterpret_cast<const uint8_t *>(OT_CLI_COAPS_X509_CERT),
sizeof(OT_CLI_COAPS_X509_CERT), reinterpret_cast<const uint8_t *>(OT_CLI_COAPS_PRIV_KEY),
sizeof(OT_CLI_COAPS_PRIV_KEY));
otCoapSecureSetCaCertificateChain(mInterpreter.mInstance,
otCoapSecureSetCaCertificateChain(GetInstancePtr(),
reinterpret_cast<const uint8_t *>(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)
+6 -10
View File
@@ -42,6 +42,7 @@
#include <openthread/coap_secure.h>
#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
+29 -31
View File
@@ -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<uint8_t>(length));
error = otCommissionerSendMgmtGet(GetInstancePtr(), tlvs, static_cast<uint8_t>(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<int8_t>(aEnergyList[i]));
OutputFormat("%d ", static_cast<int8_t>(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
+5 -8
View File
@@ -38,6 +38,7 @@
#include <openthread/commissioner.h>
#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
+65 -75
View File
@@ -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<const otNetworkName *>(otThreadGetNetworkName(mInterpreter.mInstance))),
: reinterpret_cast<const otNetworkName *>(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
+4 -7
View File
@@ -40,25 +40,24 @@
#include <openthread/dataset.h>
#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;
};
+54 -58
View File
@@ -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[])
+5 -8
View File
@@ -39,6 +39,7 @@
#include <openthread/history_tracker.h>
#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
+10 -11
View File
@@ -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<unsigned long long>(discerner->mValue), discerner->mLength);
OutputLine("0x%llx/%u", static_cast<unsigned long long>(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;
}
}
+5 -8
View File
@@ -38,6 +38,7 @@
#include <openthread/joiner.h>
#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
+35 -41
View File
@@ -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<uint8_t>(len));
mInterpreter.OutputLine("");
OutputBytesLine(data, static_cast<uint8_t>(len));
exit:
return error;
+9 -8
View File
@@ -38,19 +38,18 @@
#include <openthread/netdata.h>
#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
+360
View File
@@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#if OPENTHREAD_FTD || OPENTHREAD_MTD
#include <openthread/dns.h>
#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<uint32_t>(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<uint16_t>(&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<int>(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<int>(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
+394
View File
@@ -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 <stdarg.h>
#include <openthread/cli.h>
#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 <uint8_t kBytesLength> 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 <uint8_t kBytesLength> 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 <uint8_t kTableNumColumns>
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 <uint8_t kTableNumColumns> 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 <typename... Args> void OutputFormat(const char *aFormat, Args... aArgs)
{
mOutput.OutputFormat(aFormat, aArgs...);
}
template <typename... Args> void OutputFormat(uint8_t aIndentSize, const char *aFormat, Args... aArgs)
{
mOutput.OutputFormat(aIndentSize, aFormat, aArgs...);
}
template <typename... Args> void OutputLine(const char *aFormat, Args... aArgs)
{
return mOutput.OutputLine(aFormat, aArgs...);
}
template <typename... Args> void OutputLine(uint8_t aIndentSize, const char *aFormat, Args... aArgs)
{
return mOutput.OutputLine(aIndentSize, aFormat, aArgs...);
}
template <uint8_t kBytesLength> void OutputBytes(const uint8_t (&aBytes)[kBytesLength])
{
mOutput.OutputBytes(aBytes, kBytesLength);
}
template <uint8_t kBytesLength> 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 <uint8_t kTableNumColumns>
void OutputTableHeader(const char *const (&aTitles)[kTableNumColumns], const uint8_t (&aWidths)[kTableNumColumns])
{
mOutput.OutputTableHeader(aTitles, aWidths);
}
template <uint8_t kTableNumColumns> void OutputTableSeparator(const uint8_t (&aWidths)[kTableNumColumns])
{
mOutput.OutputTableSeparator(aWidths);
}
private:
Output &mOutput;
};
} // namespace Cli
} // namespace ot
#endif // CLI_OUTPUT_HPP_
+61 -65
View File
@@ -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<otSrpClientService *>(service));
error = otSrpClientRemoveService(GetInstancePtr(), const_cast<otSrpClientService *>(service));
}
else
{
SuccessOrExit(
error = otSrpClientClearService(mInterpreter.mInstance, const_cast<otSrpClientService *>(service)));
SuccessOrExit(error = otSrpClientClearService(GetInstancePtr(), const_cast<otSrpClientService *>(service)));
otSrpClientBuffersFreeService(mInterpreter.mInstance, reinterpret_cast<otSrpClientBuffersServiceEntry *>(
const_cast<otSrpClientService *>(service)));
otSrpClientBuffersFreeService(GetInstancePtr(), reinterpret_cast<otSrpClientBuffersServiceEntry *>(
const_cast<otSrpClientService *>(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<otSrpClientBuffersServiceEntry *>(
const_cast<otSrpClientService *>(service)));
otSrpClientBuffersFreeService(GetInstancePtr(), reinterpret_cast<otSrpClientBuffersServiceEntry *>(
const_cast<otSrpClientService *>(service)));
}
}
+5 -7
View File
@@ -40,6 +40,7 @@
#include <openthread/srp_client_buffers.h>
#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
+50 -50
View File
@@ -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;
+7 -8
View File
@@ -38,6 +38,7 @@
#include <openthread/srp_server.h>
#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
+24 -26
View File
@@ -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<unsigned int>(mBenchmarkBytesTotal),
static_cast<unsigned int>(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<unsigned int>(mBenchmarkBytesTotal), static_cast<unsigned int>(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<unsigned int>(data->mLength),
data->mLength, reinterpret_cast<const char *>(data->mData));
OutputLine("TCP: Received %u bytes: %.*s", static_cast<unsigned int>(data->mLength), data->mLength,
reinterpret_cast<const char *>(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<unsigned int>(aPeer->mPort));
OutputFormat("TCP: Ignoring incoming connection request from [");
OutputIp6Address(aPeer->mAddress);
OutputLine("]:%u (active socket is busy)", static_cast<unsigned int>(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<unsigned int>(aPeer->mPort));
OutputFormat("Accepted connection from [");
OutputIp6Address(aPeer->mAddress);
OutputLine("]:%u", static_cast<unsigned int>(aPeer->mPort));
}
} // namespace Cli
+5 -8
View File
@@ -39,6 +39,7 @@
#include <openthread/tcp.h>
#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;
+15 -15
View File
@@ -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
+4 -7
View File
@@ -38,19 +38,18 @@
#include <openthread/udp.h>
#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;
};
+1
View File
@@ -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