1 /*
2 * Copyright (c) 2016-2017, The OpenThread Authors.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. Neither the name of the copyright holder nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 /**
29 * @file
30 * This file implements general thread device required Spinel interface to the OpenThread stack.
31 */
32
33 #include "ncp_base.hpp"
34
35 #include <stdarg.h>
36 #include <stdlib.h>
37
38 #include <openthread/diag.h>
39 #include <openthread/icmp6.h>
40 #include <openthread/link.h>
41 #include <openthread/logging.h>
42 #include <openthread/ncp.h>
43 #include <openthread/network_time.h>
44 #include <openthread/platform/misc.h>
45 #include <openthread/platform/radio.h>
46
47 #include "common/code_utils.hpp"
48 #include "common/debug.hpp"
49 #include "radio/radio.hpp"
50
51 namespace ot {
52 namespace Ncp {
53
54 // ----------------------------------------------------------------------------
55 // MARK: Utility Functions
56 // ----------------------------------------------------------------------------
57
InstanceToIid(Instance * aInstance)58 uint8_t NcpBase::InstanceToIid(Instance *aInstance)
59 {
60 uint8_t index = 0;
61
62 OT_UNUSED_VARIABLE(aInstance);
63
64 #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
65 index = SPINEL_HEADER_GET_IID(SPINEL_HEADER_IID_BROADCAST); // use broadcast if no match
66
67 for (int i = 0; i < kSpinelInterfaceCount; i++)
68 {
69 if (aInstance == mInstances[i])
70 {
71 index = i;
72 break;
73 }
74 }
75 #endif // OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
76
77 return index;
78 }
79
IidToInstance(uint8_t aIid)80 Instance *NcpBase::IidToInstance(uint8_t aIid)
81 {
82 Instance *instance;
83 OT_ASSERT(aIid < kSpinelInterfaceCount);
84
85 #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
86 instance = mInstances[aIid];
87 #else
88 OT_UNUSED_VARIABLE(aIid);
89 instance = mInstance;
90 #endif // OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
91
92 return instance;
93 }
94
95 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
HasOnly1BitSet(uint32_t aValue)96 static bool HasOnly1BitSet(uint32_t aValue) { return aValue != 0 && ((aValue & (aValue - 1)) == 0); }
97
IndexOfMSB(uint32_t aValue)98 static uint8_t IndexOfMSB(uint32_t aValue)
99 {
100 uint8_t index = 0;
101
102 while (aValue >>= 1)
103 {
104 index++;
105 }
106
107 return index;
108 }
109 #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
110
ThreadErrorToSpinelStatus(otError aError)111 spinel_status_t NcpBase::ThreadErrorToSpinelStatus(otError aError)
112 {
113 spinel_status_t ret;
114
115 switch (aError)
116 {
117 case OT_ERROR_NONE:
118 ret = SPINEL_STATUS_OK;
119 break;
120
121 case OT_ERROR_FAILED:
122 ret = SPINEL_STATUS_FAILURE;
123 break;
124
125 case OT_ERROR_DROP:
126 ret = SPINEL_STATUS_DROPPED;
127 break;
128
129 case OT_ERROR_NO_BUFS:
130 ret = SPINEL_STATUS_NOMEM;
131 break;
132
133 case OT_ERROR_BUSY:
134 ret = SPINEL_STATUS_BUSY;
135 break;
136
137 case OT_ERROR_PARSE:
138 ret = SPINEL_STATUS_PARSE_ERROR;
139 break;
140
141 case OT_ERROR_INVALID_ARGS:
142 ret = SPINEL_STATUS_INVALID_ARGUMENT;
143 break;
144
145 case OT_ERROR_NOT_IMPLEMENTED:
146 ret = SPINEL_STATUS_UNIMPLEMENTED;
147 break;
148
149 case OT_ERROR_INVALID_STATE:
150 ret = SPINEL_STATUS_INVALID_STATE;
151 break;
152
153 case OT_ERROR_NO_ACK:
154 ret = SPINEL_STATUS_NO_ACK;
155 break;
156
157 case OT_ERROR_CHANNEL_ACCESS_FAILURE:
158 ret = SPINEL_STATUS_CCA_FAILURE;
159 break;
160
161 case OT_ERROR_ALREADY:
162 ret = SPINEL_STATUS_ALREADY;
163 break;
164
165 case OT_ERROR_NOT_FOUND:
166 ret = SPINEL_STATUS_ITEM_NOT_FOUND;
167 break;
168
169 case OT_ERROR_UNKNOWN_NEIGHBOR:
170 ret = SPINEL_STATUS_UNKNOWN_NEIGHBOR;
171 break;
172
173 case OT_ERROR_NOT_CAPABLE:
174 ret = SPINEL_STATUS_NOT_CAPABLE;
175 break;
176
177 case OT_ERROR_RESPONSE_TIMEOUT:
178 ret = SPINEL_STATUS_RESPONSE_TIMEOUT;
179 break;
180
181 default:
182 // Unknown error code. Wrap it as a Spinel status and return that.
183 ret = static_cast<spinel_status_t>(SPINEL_STATUS_STACK_NATIVE__BEGIN + static_cast<uint32_t>(aError));
184 break;
185 }
186
187 return ret;
188 }
189
ResetReasonToSpinelStatus(otPlatResetReason aReason)190 static spinel_status_t ResetReasonToSpinelStatus(otPlatResetReason aReason)
191 {
192 spinel_status_t ret;
193
194 switch (aReason)
195 {
196 case OT_PLAT_RESET_REASON_POWER_ON:
197 ret = SPINEL_STATUS_RESET_POWER_ON;
198 break;
199
200 case OT_PLAT_RESET_REASON_EXTERNAL:
201 ret = SPINEL_STATUS_RESET_EXTERNAL;
202 break;
203
204 case OT_PLAT_RESET_REASON_SOFTWARE:
205 ret = SPINEL_STATUS_RESET_SOFTWARE;
206 break;
207
208 case OT_PLAT_RESET_REASON_FAULT:
209 ret = SPINEL_STATUS_RESET_FAULT;
210 break;
211
212 case OT_PLAT_RESET_REASON_CRASH:
213 ret = SPINEL_STATUS_RESET_CRASH;
214 break;
215
216 case OT_PLAT_RESET_REASON_ASSERT:
217 ret = SPINEL_STATUS_RESET_ASSERT;
218 break;
219
220 case OT_PLAT_RESET_REASON_WATCHDOG:
221 ret = SPINEL_STATUS_RESET_WATCHDOG;
222 break;
223
224 case OT_PLAT_RESET_REASON_OTHER:
225 ret = SPINEL_STATUS_RESET_OTHER;
226 break;
227
228 default:
229 ret = SPINEL_STATUS_RESET_UNKNOWN;
230 break;
231 }
232
233 return ret;
234 }
235
236 // ----------------------------------------------------------------------------
237 // MARK: Class Boilerplate
238 // ----------------------------------------------------------------------------
239
240 NcpBase *NcpBase::sNcpInstance = nullptr;
241
242 #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
NcpBase(Instance ** aInstances,uint8_t aCount)243 NcpBase::NcpBase(Instance **aInstances, uint8_t aCount)
244 : NcpBase(aInstances[0])
245 {
246 OT_ASSERT(aCount > 0);
247 OT_ASSERT(aCount < SPINEL_HEADER_IID_MAX); // One IID reserved for broadcast
248
249 uint8_t skipped = 0;
250
251 for (int i = 0; i < aCount; i++)
252 {
253 if ((i + skipped) == SPINEL_HEADER_GET_IID(SPINEL_HEADER_IID_BROADCAST))
254 {
255 mInstances[i + skipped] = nullptr;
256 skipped++;
257 }
258
259 OT_ASSERT(i + skipped <= SPINEL_HEADER_IID_MAX);
260 mInstances[i + skipped] = aInstances[i];
261 }
262 }
263 #endif // OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
264
NcpBase(Instance * aInstance)265 NcpBase::NcpBase(Instance *aInstance)
266 : mInstance(aInstance)
267 , mTxFrameBuffer(mTxBuffer, sizeof(mTxBuffer))
268 , mEncoder(mTxFrameBuffer)
269 , mHostPowerStateInProgress(false)
270 , mLastStatus(SPINEL_STATUS_OK)
271 , mScanChannelMask(Radio::kSupportedChannels)
272 , mScanPeriod(200)
273 , mDiscoveryScanJoinerFlag(false)
274 , mDiscoveryScanEnableFiltering(false)
275 , mDiscoveryScanPanId(0xffff)
276 , mUpdateChangedPropsTask(*aInstance, NcpBase::UpdateChangedProps)
277 , mThreadChangedFlags(0)
278 , mHostPowerState(SPINEL_HOST_POWER_STATE_ONLINE)
279 , mHostPowerReplyFrameTag(Spinel::Buffer::kInvalidTag)
280 , mHostPowerStateHeader(0)
281 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
282 , mAllowPeekDelegate(nullptr)
283 , mAllowPokeDelegate(nullptr)
284 #endif
285 , mResponseQueueHead(0)
286 , mResponseQueueTail(0)
287 , mAllowLocalNetworkDataChange(false)
288 , mRequireJoinExistingNetwork(false)
289 , mPcapEnabled(false)
290 , mDisableStreamWrite(false)
291 , mShouldEmitChildTableUpdate(false)
292 #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE
293 , mAllowLocalServerDataChange(false)
294 #endif
295 #if OPENTHREAD_FTD
296 , mPreferredRouteId(0)
297 #endif
298 , mCurCommandIid(0)
299 #if OPENTHREAD_MTD || OPENTHREAD_FTD
300 , mInboundSecureIpFrameCounter(0)
301 , mInboundInsecureIpFrameCounter(0)
302 , mOutboundSecureIpFrameCounter(0)
303 , mOutboundInsecureIpFrameCounter(0)
304 , mDroppedOutboundIpFrameCounter(0)
305 , mDroppedInboundIpFrameCounter(0)
306 #if OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE
307 , mSrpClientCallbackEnabled(false)
308 #endif
309 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
310 , mFramingErrorCounter(0)
311 , mRxSpinelFrameCounter(0)
312 , mRxSpinelOutOfOrderTidCounter(0)
313 , mTxSpinelFrameCounter(0)
314 , mDidInitialUpdates(false)
315 , mLogTimestampBase(0)
316 {
317 OT_ASSERT(mInstance != nullptr);
318
319 sNcpInstance = this;
320
321 mTxFrameBuffer.SetFrameRemovedCallback(&NcpBase::HandleFrameRemovedFromNcpBuffer, this);
322
323 memset(&mResponseQueue, 0, sizeof(mResponseQueue));
324 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
325 memset(mCurTransmitTID, 0, sizeof(mCurTransmitTID));
326 memset(mSrcMatchEnabled, 0, sizeof(mSrcMatchEnabled));
327 memset(mCurScanChannel, kInvalidScanChannel, sizeof(mCurScanChannel));
328 #endif
329 memset(mIsRawStreamEnabled, 0, sizeof(mIsRawStreamEnabled));
330 memset(mNextExpectedTid, 0, sizeof(mNextExpectedTid));
331
332 #if OPENTHREAD_MTD || OPENTHREAD_FTD
333 otMessageQueueInit(&mMessageQueue);
334 IgnoreError(otSetStateChangedCallback(mInstance, &NcpBase::HandleStateChanged, this));
335 otIp6SetReceiveCallback(mInstance, &NcpBase::HandleDatagramFromStack, this);
336 otIp6SetReceiveFilterEnabled(mInstance, true);
337 #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
338 otNetworkTimeSyncSetCallback(mInstance, &NcpBase::HandleTimeSyncUpdate, this);
339 #endif // OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
340 #if OPENTHREAD_CONFIG_UDP_FORWARD_ENABLE
341 otUdpForwardSetForwarder(mInstance, &NcpBase::HandleUdpForwardStream, this);
342 #endif
343 otIcmp6SetEchoMode(mInstance, OT_ICMP6_ECHO_HANDLER_DISABLED);
344 #if OPENTHREAD_FTD
345 otThreadRegisterNeighborTableCallback(mInstance, &NcpBase::HandleNeighborTableChanged);
346 #if OPENTHREAD_CONFIG_MLE_STEERING_DATA_SET_OOB_ENABLE
347 memset(&mSteeringDataAddress, 0, sizeof(mSteeringDataAddress));
348 #endif
349 #if OPENTHREAD_CONFIG_MLE_PARENT_RESPONSE_CALLBACK_API_ENABLE
350 otThreadRegisterParentResponseCallback(mInstance, &NcpBase::HandleParentResponseInfo, static_cast<void *>(this));
351 #endif
352 #endif // OPENTHREAD_FTD
353 #if OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE
354 otSrpClientSetCallback(mInstance, HandleSrpClientCallback, this);
355 #endif
356 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
357 mChangedPropsSet.AddLastStatus(SPINEL_STATUS_RESET_UNKNOWN);
358 mUpdateChangedPropsTask.Post();
359
360 #if OPENTHREAD_ENABLE_VENDOR_EXTENSION
361 aInstance->Get<Extension::ExtensionBase>().SignalNcpInit(*this);
362 #endif
363 }
364
GetNcpInstance(void)365 NcpBase *NcpBase::GetNcpInstance(void) { return sNcpInstance; }
366
GetCurCommandIid(void) const367 spinel_iid_t NcpBase::GetCurCommandIid(void) const { return mCurCommandIid; }
368
ResetCounters(void)369 void NcpBase::ResetCounters(void)
370 {
371 mFramingErrorCounter = 0;
372 mRxSpinelFrameCounter = 0;
373 mRxSpinelOutOfOrderTidCounter = 0;
374 mTxSpinelFrameCounter = 0;
375
376 #if OPENTHREAD_MTD || OPENTHREAD_FTD
377 mInboundSecureIpFrameCounter = 0;
378 mInboundInsecureIpFrameCounter = 0;
379 mOutboundSecureIpFrameCounter = 0;
380 mOutboundInsecureIpFrameCounter = 0;
381 mDroppedOutboundIpFrameCounter = 0;
382 mDroppedInboundIpFrameCounter = 0;
383 #endif
384 }
385
386 // ----------------------------------------------------------------------------
387 // MARK: Serial Traffic Glue
388 // ----------------------------------------------------------------------------
389
GetLastOutboundFrameTag(void)390 Spinel::Buffer::FrameTag NcpBase::GetLastOutboundFrameTag(void) { return mTxFrameBuffer.InFrameGetLastTag(); }
391
HandleReceive(const uint8_t * aBuf,uint16_t aBufLength)392 void NcpBase::HandleReceive(const uint8_t *aBuf, uint16_t aBufLength)
393 {
394 otError error = OT_ERROR_NONE;
395 uint8_t header = 0;
396 spinel_tid_t tid = 0;
397
398 mDisableStreamWrite = true;
399
400 // Initialize the decoder with the newly received spinel frame.
401 mDecoder.Init(aBuf, aBufLength);
402
403 // Receiving any message from the host has the side effect of transitioning the host power state to online.
404 mHostPowerState = SPINEL_HOST_POWER_STATE_ONLINE;
405 mHostPowerStateInProgress = false;
406
407 // Skip if there is no header byte to read or this isn't a spinel frame.
408
409 SuccessOrExit(mDecoder.ReadUint8(header));
410 VerifyOrExit((SPINEL_HEADER_FLAG & header) == SPINEL_HEADER_FLAG);
411
412 mRxSpinelFrameCounter++;
413
414 mCurCommandIid = SPINEL_HEADER_GET_IID(header);
415
416 #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE
417 if (mCurCommandIid > SPINEL_HEADER_IID_MAX)
418 #else
419 if (mCurCommandIid != 0)
420 #endif
421 {
422 IgnoreError(WriteLastStatusFrame(header, SPINEL_STATUS_INVALID_INTERFACE));
423 ExitNow();
424 }
425
426 mInstance = IidToInstance(mCurCommandIid);
427 if (mInstance == nullptr)
428 {
429 IgnoreError(WriteLastStatusFrame(header, SPINEL_STATUS_INVALID_INTERFACE));
430 ExitNow();
431 }
432
433 error = HandleCommand(header);
434
435 if (error != OT_ERROR_NONE)
436 {
437 IgnoreError(PrepareLastStatusResponse(header, ThreadErrorToSpinelStatus(error)));
438 }
439
440 if (!IsResponseQueueEmpty())
441 {
442 // A response may have been prepared and queued for this command,
443 // so we attempt to send/write any queued responses. Note that
444 // if the response was prepared but cannot be sent now (not
445 // enough buffer space available), it will be attempted again
446 // from `HandleFrameRemovedFromNcpBuffer()` when buffer space
447 // becomes available.
448
449 IgnoreError(SendQueuedResponses());
450 }
451
452 // Check for out of sequence TIDs and update `mNextExpectedTid`,
453
454 tid = SPINEL_HEADER_GET_TID(header);
455
456 if ((mNextExpectedTid[mCurCommandIid] != 0) && (tid != mNextExpectedTid[mCurCommandIid]))
457 {
458 mRxSpinelOutOfOrderTidCounter++;
459 }
460
461 mNextExpectedTid[mCurCommandIid] = SPINEL_GET_NEXT_TID(tid);
462
463 exit:
464 mDisableStreamWrite = false;
465 }
466
HandleFrameRemovedFromNcpBuffer(void * aContext,Spinel::Buffer::FrameTag aFrameTag,Spinel::Buffer::Priority aPriority,Spinel::Buffer * aNcpBuffer)467 void NcpBase::HandleFrameRemovedFromNcpBuffer(void *aContext,
468 Spinel::Buffer::FrameTag aFrameTag,
469 Spinel::Buffer::Priority aPriority,
470 Spinel::Buffer *aNcpBuffer)
471 {
472 OT_UNUSED_VARIABLE(aNcpBuffer);
473 OT_UNUSED_VARIABLE(aPriority);
474
475 static_cast<NcpBase *>(aContext)->HandleFrameRemovedFromNcpBuffer(aFrameTag);
476 }
477
HandleFrameRemovedFromNcpBuffer(Spinel::Buffer::FrameTag aFrameTag)478 void NcpBase::HandleFrameRemovedFromNcpBuffer(Spinel::Buffer::FrameTag aFrameTag)
479 {
480 if (mHostPowerStateInProgress)
481 {
482 if (aFrameTag == mHostPowerReplyFrameTag)
483 {
484 mHostPowerStateInProgress = false;
485 }
486 }
487
488 // A frame was removed from NCP TX buffer, so more space is now available.
489 // We attempt to write/send any pending frames. Order of the checks
490 // below is important: First any queued command responses, then
491 // any queued IPv6 datagram messages, then any asynchronous property updates.
492 // If a frame still can not fit in the available buffer, we exit immediately
493 // and wait for next time this callback is invoked (when another frame is
494 // removed and more buffer space becomes available).
495
496 SuccessOrExit(SendQueuedResponses());
497
498 #if OPENTHREAD_ENABLE_NCP_VENDOR_HOOK
499 VendorHandleFrameRemovedFromNcpBuffer(aFrameTag);
500 #endif
501
502 // Check if `HOST_POWER_STATE` property update is required.
503
504 if (mHostPowerStateHeader)
505 {
506 SuccessOrExit(WritePropertyValueIsFrame(mHostPowerStateHeader, SPINEL_PROP_HOST_POWER_STATE));
507
508 mHostPowerStateHeader = 0;
509
510 if (mHostPowerState != SPINEL_HOST_POWER_STATE_ONLINE)
511 {
512 mHostPowerReplyFrameTag = GetLastOutboundFrameTag();
513 mHostPowerStateInProgress = true;
514 }
515 }
516
517 #if OPENTHREAD_MTD || OPENTHREAD_FTD
518
519 // Send any queued IPv6 datagram message.
520
521 SuccessOrExit(SendQueuedDatagramMessages());
522 #endif
523
524 // Send any unsolicited event-triggered property updates.
525
526 UpdateChangedProps();
527
528 exit:
529 return;
530 }
531
ShouldWakeHost(void)532 bool NcpBase::ShouldWakeHost(void)
533 {
534 return (mHostPowerState != SPINEL_HOST_POWER_STATE_ONLINE && !mHostPowerStateInProgress);
535 }
536
ShouldDeferHostSend(void)537 bool NcpBase::ShouldDeferHostSend(void)
538 {
539 return (mHostPowerState == SPINEL_HOST_POWER_STATE_DEEP_SLEEP && !mHostPowerStateInProgress);
540 }
541
IncrementFrameErrorCounter(void)542 void NcpBase::IncrementFrameErrorCounter(void) { mFramingErrorCounter++; }
543
StreamWrite(int aStreamId,const uint8_t * aDataPtr,int aDataLen)544 otError NcpBase::StreamWrite(int aStreamId, const uint8_t *aDataPtr, int aDataLen)
545 {
546 otError error = OT_ERROR_NONE;
547 uint8_t header = SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID;
548 spinel_prop_key_t streamPropKey;
549
550 if (aStreamId == 0)
551 {
552 streamPropKey = SPINEL_PROP_STREAM_DEBUG;
553 }
554 else
555 {
556 streamPropKey = static_cast<spinel_prop_key_t>(aStreamId);
557 }
558
559 VerifyOrExit(!mDisableStreamWrite, error = OT_ERROR_INVALID_STATE);
560 VerifyOrExit(!mChangedPropsSet.IsPropertyFiltered(streamPropKey), error = OT_ERROR_INVALID_STATE);
561
562 // If there is a pending queued response we do not allow any new log
563 // stream writes. This is to ensure that log messages can not continue
564 // to use the NCP buffer space and block other spinel frames.
565
566 VerifyOrExit(IsResponseQueueEmpty(), error = OT_ERROR_NO_BUFS);
567
568 SuccessOrExit(error = mEncoder.BeginFrame(header, SPINEL_CMD_PROP_VALUE_IS, streamPropKey));
569 SuccessOrExit(error = mEncoder.WriteData(aDataPtr, static_cast<uint16_t>(aDataLen)));
570 SuccessOrExit(error = mEncoder.EndFrame());
571
572 exit:
573
574 if (error == OT_ERROR_NO_BUFS)
575 {
576 mChangedPropsSet.AddLastStatus(SPINEL_STATUS_NOMEM);
577 mUpdateChangedPropsTask.Post();
578 }
579
580 return error;
581 }
582
ConvertLogLevel(otLogLevel aLogLevel)583 uint8_t NcpBase::ConvertLogLevel(otLogLevel aLogLevel)
584 {
585 uint8_t spinelLogLevel = SPINEL_NCP_LOG_LEVEL_EMERG;
586
587 switch (aLogLevel)
588 {
589 case OT_LOG_LEVEL_NONE:
590 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_EMERG;
591 break;
592
593 case OT_LOG_LEVEL_CRIT:
594 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_CRIT;
595 break;
596
597 case OT_LOG_LEVEL_WARN:
598 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_WARN;
599 break;
600
601 case OT_LOG_LEVEL_NOTE:
602 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_NOTICE;
603 break;
604
605 case OT_LOG_LEVEL_INFO:
606 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_INFO;
607 break;
608
609 case OT_LOG_LEVEL_DEBG:
610 spinelLogLevel = SPINEL_NCP_LOG_LEVEL_DEBUG;
611 break;
612 }
613
614 return spinelLogLevel;
615 }
616
ConvertLogRegion(otLogRegion aLogRegion)617 unsigned int NcpBase::ConvertLogRegion(otLogRegion aLogRegion)
618 {
619 unsigned int spinelLogRegion = SPINEL_NCP_LOG_REGION_NONE;
620
621 switch (aLogRegion)
622 {
623 case OT_LOG_REGION_API:
624 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_API;
625 break;
626
627 case OT_LOG_REGION_MLE:
628 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_MLE;
629 break;
630
631 case OT_LOG_REGION_ARP:
632 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_ARP;
633 break;
634
635 case OT_LOG_REGION_NET_DATA:
636 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_NET_DATA;
637 break;
638
639 case OT_LOG_REGION_ICMP:
640 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_ICMP;
641 break;
642
643 case OT_LOG_REGION_IP6:
644 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_IP6;
645 break;
646
647 case OT_LOG_REGION_TCP:
648 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_TCP;
649 break;
650
651 case OT_LOG_REGION_MAC:
652 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_MAC;
653 break;
654
655 case OT_LOG_REGION_MEM:
656 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_MEM;
657 break;
658
659 case OT_LOG_REGION_NCP:
660 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_NCP;
661 break;
662
663 case OT_LOG_REGION_MESH_COP:
664 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_MESH_COP;
665 break;
666
667 case OT_LOG_REGION_NET_DIAG:
668 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_NET_DIAG;
669 break;
670
671 case OT_LOG_REGION_PLATFORM:
672 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_PLATFORM;
673 break;
674
675 case OT_LOG_REGION_COAP:
676 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_COAP;
677 break;
678
679 case OT_LOG_REGION_CLI:
680 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_CLI;
681 break;
682
683 case OT_LOG_REGION_CORE:
684 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_CORE;
685 break;
686
687 case OT_LOG_REGION_UTIL:
688 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_UTIL;
689 break;
690
691 case OT_LOG_REGION_BBR:
692 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_BBR;
693 break;
694
695 case OT_LOG_REGION_MLR:
696 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_MLR;
697 break;
698
699 case OT_LOG_REGION_DUA:
700 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_DUA;
701 break;
702
703 case OT_LOG_REGION_BR:
704 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_BR;
705 break;
706
707 case OT_LOG_REGION_SRP:
708 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_SRP;
709 break;
710
711 case OT_LOG_REGION_DNS:
712 spinelLogRegion = SPINEL_NCP_LOG_REGION_OT_DNS;
713 break;
714 }
715
716 return spinelLogRegion;
717 }
718
Log(otLogLevel aLogLevel,otLogRegion aLogRegion,const char * aLogString)719 void NcpBase::Log(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aLogString)
720 {
721 otError error = OT_ERROR_NONE;
722 uint8_t header = SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID;
723
724 VerifyOrExit(!mDisableStreamWrite, error = OT_ERROR_INVALID_STATE);
725 VerifyOrExit(!mChangedPropsSet.IsPropertyFiltered(SPINEL_PROP_STREAM_LOG));
726
727 // If there is a pending queued response we do not allow any new log
728 // stream writes. This is to ensure that log messages can not continue
729 // to use the NCP buffer space and block other spinel frames.
730
731 VerifyOrExit(IsResponseQueueEmpty(), error = OT_ERROR_NO_BUFS);
732
733 SuccessOrExit(error = mEncoder.BeginFrame(header, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_STREAM_LOG));
734 SuccessOrExit(error = mEncoder.WriteUtf8(aLogString));
735 SuccessOrExit(error = mEncoder.WriteUint8(ConvertLogLevel(aLogLevel)));
736 SuccessOrExit(error = mEncoder.WriteUintPacked(ConvertLogRegion(aLogRegion)));
737 SuccessOrExit(error = mEncoder.WriteUint64(mLogTimestampBase + otPlatAlarmMilliGetNow()));
738 SuccessOrExit(error = mEncoder.EndFrame());
739
740 exit:
741
742 if (error == OT_ERROR_NO_BUFS)
743 {
744 mChangedPropsSet.AddLastStatus(SPINEL_STATUS_NOMEM);
745 mUpdateChangedPropsTask.Post();
746 }
747 }
748
749 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
750
RegisterPeekPokeDelegates(otNcpDelegateAllowPeekPoke aAllowPeekDelegate,otNcpDelegateAllowPeekPoke aAllowPokeDelegate)751 void NcpBase::RegisterPeekPokeDelegates(otNcpDelegateAllowPeekPoke aAllowPeekDelegate,
752 otNcpDelegateAllowPeekPoke aAllowPokeDelegate)
753 {
754 mAllowPeekDelegate = aAllowPeekDelegate;
755 mAllowPokeDelegate = aAllowPokeDelegate;
756 }
757
758 #endif // OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
759
760 // ----------------------------------------------------------------------------
761 // MARK: Spinel Response Handling
762 // ----------------------------------------------------------------------------
763
GetWrappedResponseQueueIndex(uint8_t aPosition)764 uint8_t NcpBase::GetWrappedResponseQueueIndex(uint8_t aPosition)
765 {
766 while (aPosition >= kResponseQueueSize)
767 {
768 aPosition -= kResponseQueueSize;
769 }
770
771 return aPosition;
772 }
773
EnqueueResponse(uint8_t aHeader,ResponseType aType,unsigned int aPropKeyOrStatus)774 otError NcpBase::EnqueueResponse(uint8_t aHeader, ResponseType aType, unsigned int aPropKeyOrStatus)
775 {
776 otError error = OT_ERROR_NONE;
777 spinel_iid_t iid = SPINEL_HEADER_GET_IID(aHeader);
778 spinel_tid_t tid = SPINEL_HEADER_GET_TID(aHeader);
779 ResponseEntry *entry;
780
781 if (tid == 0)
782 {
783 // No response is required for TID zero. But we may emit a
784 // `LAST_STATUS` error status (if not filtered) for TID
785 // zero (e.g., for a dropped `STREAM_NET` set command).
786
787 if (aType == kResponseTypeLastStatus)
788 {
789 mChangedPropsSet.AddLastStatus(static_cast<spinel_status_t>(aPropKeyOrStatus));
790 }
791
792 ExitNow();
793 }
794
795 if ((mResponseQueueTail - mResponseQueueHead) >= kResponseQueueSize)
796 {
797 // If there is no room a for a response, emit an unsolicited
798 // `DROPPED` error status to indicate a spinel response was
799 // dropped.
800
801 mChangedPropsSet.AddLastStatus(SPINEL_STATUS_DROPPED);
802
803 ExitNow(error = OT_ERROR_NO_BUFS);
804 }
805
806 // Transaction IDs are expected to come in sequence, if however, we
807 // get an out of sequence TID, check if we already have a response
808 // queued for this TID and if so mark the old entry as deleted.
809
810 if (tid != mNextExpectedTid[iid])
811 {
812 for (uint8_t cur = mResponseQueueHead; cur < mResponseQueueTail; cur++)
813 {
814 entry = &mResponseQueue[GetWrappedResponseQueueIndex(cur)];
815
816 if (entry->mIsInUse && (entry->mIid == iid) && (entry->mTid == tid))
817 {
818 // Entry is just marked here and will be removed
819 // from `SendQueuedResponses()`.
820
821 entry->mIsInUse = false;
822 break;
823 }
824 }
825 }
826
827 // Add the new entry in the queue at tail.
828
829 entry = &mResponseQueue[GetWrappedResponseQueueIndex(mResponseQueueTail)];
830
831 entry->mIid = iid;
832 entry->mTid = tid;
833 entry->mIsInUse = true;
834 entry->mType = aType;
835 entry->mPropKeyOrStatus = aPropKeyOrStatus;
836
837 mResponseQueueTail++;
838
839 exit:
840 return error;
841 }
842
SendQueuedResponses(void)843 otError NcpBase::SendQueuedResponses(void)
844 {
845 otError error = OT_ERROR_NONE;
846
847 while (mResponseQueueHead != mResponseQueueTail)
848 {
849 ResponseEntry &entry = mResponseQueue[mResponseQueueHead];
850
851 if (entry.mIsInUse)
852 {
853 uint8_t header = SPINEL_HEADER_FLAG;
854 header |= SPINEL_HEADER_IID(entry.mIid);
855 header |= static_cast<uint8_t>(entry.mTid << SPINEL_HEADER_TID_SHIFT);
856
857 if (entry.mType == kResponseTypeLastStatus)
858 {
859 spinel_status_t status = static_cast<spinel_status_t>(entry.mPropKeyOrStatus);
860
861 SuccessOrExit(error = WriteLastStatusFrame(header, status));
862 }
863 else
864 {
865 spinel_prop_key_t propKey = static_cast<spinel_prop_key_t>(entry.mPropKeyOrStatus);
866 bool isGetResponse = (entry.mType == kResponseTypeGet);
867
868 SuccessOrExit(error = WritePropertyValueIsFrame(header, propKey, isGetResponse));
869 }
870 }
871
872 // Remove the response entry.
873
874 entry.mIsInUse = false;
875
876 mResponseQueueHead++;
877
878 if (mResponseQueueHead == kResponseQueueSize)
879 {
880 // Only when `head` wraps, the `tail` will be wrapped as well.
881 //
882 // This ensures that `tail` is always bigger than `head` and
883 // `(tail - head)` to correctly give the number of items in
884 // the queue.
885
886 mResponseQueueHead = 0;
887 mResponseQueueTail = GetWrappedResponseQueueIndex(mResponseQueueTail);
888 }
889 }
890
891 exit:
892 return error;
893 }
894
895 // ----------------------------------------------------------------------------
896 // MARK: Property/Status Changed
897 // ----------------------------------------------------------------------------
898
UpdateChangedProps(Tasklet & aTasklet)899 void NcpBase::UpdateChangedProps(Tasklet &aTasklet)
900 {
901 OT_UNUSED_VARIABLE(aTasklet);
902 GetNcpInstance()->UpdateChangedProps();
903 }
904
UpdateChangedProps(void)905 void NcpBase::UpdateChangedProps(void)
906 {
907 uint8_t numEntries;
908 spinel_prop_key_t propKey;
909 const ChangedPropsSet::Entry *entry;
910
911 #if OPENTHREAD_MTD || OPENTHREAD_FTD
912 ProcessThreadChangedFlags();
913 #endif
914
915 VerifyOrExit(!mChangedPropsSet.IsEmpty());
916
917 entry = mChangedPropsSet.GetSupportedEntries(numEntries);
918
919 for (uint8_t index = 0; index < numEntries; index++, entry++)
920 {
921 if (!mChangedPropsSet.IsEntryChanged(index))
922 {
923 continue;
924 }
925
926 propKey = entry->mPropKey;
927
928 if (propKey == SPINEL_PROP_LAST_STATUS)
929 {
930 spinel_status_t status = entry->mStatus;
931
932 if (status == SPINEL_STATUS_RESET_UNKNOWN)
933 {
934 status = ResetReasonToSpinelStatus(otPlatGetResetReason(mInstance));
935 }
936
937 SuccessOrExit(WriteLastStatusFrame(SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID, status));
938 }
939 else if (mDidInitialUpdates)
940 {
941 SuccessOrExit(WritePropertyValueIsFrame(SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID, propKey));
942 }
943
944 mChangedPropsSet.RemoveEntry(index);
945 VerifyOrExit(!mChangedPropsSet.IsEmpty());
946 }
947
948 exit:
949 mDidInitialUpdates = true;
950 }
951
952 // ----------------------------------------------------------------------------
953 // MARK: Inbound Command Handler
954 // ----------------------------------------------------------------------------
955
HandleCommand(uint8_t aHeader)956 otError NcpBase::HandleCommand(uint8_t aHeader)
957 {
958 otError error = OT_ERROR_NONE;
959 unsigned int command;
960
961 SuccessOrExit(error = mDecoder.ReadUintPacked(command));
962
963 switch (command)
964 {
965 case SPINEL_CMD_NOOP:
966 error = CommandHandler_NOOP(aHeader);
967 break;
968
969 case SPINEL_CMD_RESET:
970 error = CommandHandler_RESET(aHeader);
971 break;
972
973 case SPINEL_CMD_PROP_VALUE_GET:
974 case SPINEL_CMD_PROP_VALUE_SET:
975 case SPINEL_CMD_PROP_VALUE_INSERT:
976 case SPINEL_CMD_PROP_VALUE_REMOVE:
977 error = CommandHandler_PROP_VALUE_update(aHeader, command);
978 break;
979
980 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
981 case SPINEL_CMD_PEEK:
982 error = CommandHandler_PEEK(aHeader);
983 break;
984
985 case SPINEL_CMD_POKE:
986 error = CommandHandler_POKE(aHeader);
987 break;
988 #endif
989
990 #if OPENTHREAD_MTD || OPENTHREAD_FTD
991 case SPINEL_CMD_NET_SAVE:
992 case SPINEL_CMD_NET_RECALL:
993 error = OT_ERROR_NOT_IMPLEMENTED;
994 break;
995
996 case SPINEL_CMD_NET_CLEAR:
997 error = CommandHandler_NET_CLEAR(aHeader);
998 break;
999 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
1000
1001 default:
1002
1003 #if OPENTHREAD_ENABLE_NCP_VENDOR_HOOK
1004 if (command >= SPINEL_CMD_VENDOR__BEGIN && command < SPINEL_CMD_VENDOR__END)
1005 {
1006 error = VendorCommandHandler(aHeader, command);
1007 break;
1008 }
1009 #endif
1010
1011 error = PrepareLastStatusResponse(aHeader, SPINEL_STATUS_INVALID_COMMAND);
1012 break;
1013 }
1014
1015 exit:
1016 return error;
1017 }
1018
1019 // ----------------------------------------------------------------------------
1020 // MARK: Property Get/Set/Insert/Remove Commands
1021 // ----------------------------------------------------------------------------
1022
1023 // Returns `true` and updates the `aError` on success.
HandlePropertySetForSpecialProperties(uint8_t aHeader,spinel_prop_key_t aKey,otError & aError)1024 bool NcpBase::HandlePropertySetForSpecialProperties(uint8_t aHeader, spinel_prop_key_t aKey, otError &aError)
1025 {
1026 bool didHandle = true;
1027
1028 // Here the properties that require special treatment are handled.
1029 // These properties are expected to form/write the response from
1030 // their set handler directly.
1031
1032 switch (aKey)
1033 {
1034 case SPINEL_PROP_HOST_POWER_STATE:
1035 ExitNow(aError = HandlePropertySet_SPINEL_PROP_HOST_POWER_STATE(aHeader));
1036
1037 #if OPENTHREAD_CONFIG_DIAG_ENABLE
1038 case SPINEL_PROP_NEST_STREAM_MFG:
1039 ExitNow(aError = HandlePropertySet_SPINEL_PROP_NEST_STREAM_MFG(aHeader));
1040 #endif
1041
1042 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE
1043 case SPINEL_PROP_MESHCOP_COMMISSIONER_GENERATE_PSKC:
1044 ExitNow(aError = HandlePropertySet_SPINEL_PROP_MESHCOP_COMMISSIONER_GENERATE_PSKC(aHeader));
1045
1046 case SPINEL_PROP_THREAD_COMMISSIONER_ENABLED:
1047 ExitNow(aError = HandlePropertySet_SPINEL_PROP_THREAD_COMMISSIONER_ENABLED(aHeader));
1048 #endif
1049
1050 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1051 case SPINEL_PROP_STREAM_RAW:
1052 ExitNow(aError = HandlePropertySet_SPINEL_PROP_STREAM_RAW(aHeader));
1053 #endif
1054
1055 default:
1056 didHandle = false;
1057 break;
1058 }
1059
1060 exit:
1061 return didHandle;
1062 }
1063
HandleCommandPropertySet(uint8_t aHeader,spinel_prop_key_t aKey)1064 otError NcpBase::HandleCommandPropertySet(uint8_t aHeader, spinel_prop_key_t aKey)
1065 {
1066 otError error = OT_ERROR_NONE;
1067 PropertyHandler handler = FindSetPropertyHandler(aKey);
1068
1069 if (handler != nullptr)
1070 {
1071 mDisableStreamWrite = false;
1072 error = (this->*handler)();
1073 mDisableStreamWrite = true;
1074 }
1075 else
1076 {
1077 // If there is no "set" handler, check if this property is one of the
1078 // ones that require different treatment.
1079
1080 bool didHandle = HandlePropertySetForSpecialProperties(aHeader, aKey, error);
1081
1082 VerifyOrExit(!didHandle);
1083
1084 #if OPENTHREAD_ENABLE_NCP_VENDOR_HOOK
1085 if (aKey >= SPINEL_PROP_VENDOR__BEGIN && aKey < SPINEL_PROP_VENDOR__END)
1086 {
1087 mDisableStreamWrite = false;
1088 error = VendorSetPropertyHandler(aKey);
1089 mDisableStreamWrite = true;
1090
1091 // An `OT_ERROR_NOT_FOUND` status from vendor handler indicates
1092 // that it does not support the given property key. In that
1093 // case, `didHandle` is set to `false` so a `LAST_STATUS` with
1094 // `PROP_NOT_FOUND` is emitted. Otherwise, we fall through to
1095 // prepare the response.
1096
1097 didHandle = (error != OT_ERROR_NOT_FOUND);
1098 }
1099 #endif
1100
1101 VerifyOrExit(didHandle, error = PrepareLastStatusResponse(aHeader, SPINEL_STATUS_PROP_NOT_FOUND));
1102 }
1103
1104 if (error == OT_ERROR_NONE)
1105 {
1106 error = PrepareSetResponse(aHeader, aKey);
1107 }
1108 else
1109 {
1110 error = PrepareLastStatusResponse(aHeader, ThreadErrorToSpinelStatus(error));
1111 }
1112
1113 exit:
1114 return error;
1115 }
1116
HandleCommandPropertyInsertRemove(uint8_t aHeader,spinel_prop_key_t aKey,unsigned int aCommand)1117 otError NcpBase::HandleCommandPropertyInsertRemove(uint8_t aHeader, spinel_prop_key_t aKey, unsigned int aCommand)
1118 {
1119 otError error = OT_ERROR_NONE;
1120 PropertyHandler handler = nullptr;
1121 unsigned int responseCommand = 0;
1122 const uint8_t *valuePtr;
1123 uint16_t valueLen;
1124
1125 switch (aCommand)
1126 {
1127 case SPINEL_CMD_PROP_VALUE_INSERT:
1128 handler = FindInsertPropertyHandler(aKey);
1129 responseCommand = SPINEL_CMD_PROP_VALUE_INSERTED;
1130 break;
1131
1132 case SPINEL_CMD_PROP_VALUE_REMOVE:
1133 handler = FindRemovePropertyHandler(aKey);
1134 responseCommand = SPINEL_CMD_PROP_VALUE_REMOVED;
1135 break;
1136
1137 default:
1138 OT_ASSERT(false);
1139 }
1140
1141 VerifyOrExit(handler != nullptr, error = PrepareLastStatusResponse(aHeader, SPINEL_STATUS_PROP_NOT_FOUND));
1142
1143 // Save current read position in the decoder. Read the entire
1144 // content as a data blob (which is used in forming the response
1145 // in case of success), then reset the read position back so
1146 // that the `PropertyHandler` method can parse the content.
1147
1148 mDecoder.SavePosition();
1149 IgnoreError(mDecoder.ReadData(valuePtr, valueLen));
1150 IgnoreError(mDecoder.ResetToSaved());
1151
1152 mDisableStreamWrite = false;
1153
1154 error = (this->*handler)();
1155
1156 mDisableStreamWrite = true;
1157
1158 VerifyOrExit(error == OT_ERROR_NONE, error = PrepareLastStatusResponse(aHeader, ThreadErrorToSpinelStatus(error)));
1159
1160 error = WritePropertyValueInsertedRemovedFrame(aHeader, responseCommand, aKey, valuePtr, valueLen);
1161
1162 // If the full response cannot be written now, instead prepare
1163 // a `LAST_STATUS(STATUS_OK)` update as response.
1164
1165 if (error != OT_ERROR_NONE)
1166 {
1167 error = PrepareLastStatusResponse(aHeader, SPINEL_STATUS_OK);
1168 }
1169
1170 exit:
1171 return error;
1172 }
1173
1174 // ----------------------------------------------------------------------------
1175 // MARK: Outbound Frame Methods
1176 // ----------------------------------------------------------------------------
1177
WriteLastStatusFrame(uint8_t aHeader,spinel_status_t aLastStatus)1178 otError NcpBase::WriteLastStatusFrame(uint8_t aHeader, spinel_status_t aLastStatus)
1179 {
1180 otError error = OT_ERROR_NONE;
1181
1182 if (SPINEL_HEADER_GET_IID(aHeader) == SPINEL_HEADER_GET_IID(SPINEL_HEADER_TX_NOTIFICATION_IID))
1183 {
1184 mLastStatus = aLastStatus;
1185 }
1186
1187 SuccessOrExit(error = mEncoder.BeginFrame(aHeader, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_LAST_STATUS));
1188 SuccessOrExit(error = mEncoder.WriteUintPacked(aLastStatus));
1189 SuccessOrExit(error = mEncoder.EndFrame());
1190
1191 exit:
1192 return error;
1193 }
1194
WritePropertyValueIsFrame(uint8_t aHeader,spinel_prop_key_t aPropKey,bool aIsGetResponse)1195 otError NcpBase::WritePropertyValueIsFrame(uint8_t aHeader, spinel_prop_key_t aPropKey, bool aIsGetResponse)
1196 {
1197 otError error = OT_ERROR_NONE;
1198 PropertyHandler handler = FindGetPropertyHandler(aPropKey);
1199
1200 if (handler != nullptr)
1201 {
1202 SuccessOrExit(error = mEncoder.BeginFrame(aHeader, SPINEL_CMD_PROP_VALUE_IS, aPropKey));
1203 SuccessOrExit(error = (this->*handler)());
1204 ExitNow(error = mEncoder.EndFrame());
1205 }
1206
1207 #if OPENTHREAD_ENABLE_NCP_VENDOR_HOOK
1208 if (aPropKey >= SPINEL_PROP_VENDOR__BEGIN && aPropKey < SPINEL_PROP_VENDOR__END)
1209 {
1210 SuccessOrExit(error = mEncoder.BeginFrame(aHeader, SPINEL_CMD_PROP_VALUE_IS, aPropKey));
1211
1212 error = VendorGetPropertyHandler(aPropKey);
1213
1214 // An `OT_ERROR_NOT_FOUND` status from vendor handler indicates that
1215 // it did not support the given property key. In that case, we fall
1216 // through to prepare a `LAST_STATUS` response.
1217
1218 if (error != OT_ERROR_NOT_FOUND)
1219 {
1220 SuccessOrExit(error);
1221 ExitNow(error = mEncoder.EndFrame());
1222 }
1223 }
1224 #endif
1225
1226 if (aIsGetResponse)
1227 {
1228 SuccessOrExit(error = WriteLastStatusFrame(aHeader, SPINEL_STATUS_PROP_NOT_FOUND));
1229 }
1230 else
1231 {
1232 // Send a STATUS_OK for "set" response to a property that
1233 // has no corresponding get handler.
1234
1235 SuccessOrExit(error = WriteLastStatusFrame(aHeader, SPINEL_STATUS_OK));
1236 }
1237
1238 exit:
1239 return error;
1240 }
1241
WritePropertyValueInsertedRemovedFrame(uint8_t aHeader,unsigned int aResponseCommand,spinel_prop_key_t aPropKey,const uint8_t * aValuePtr,uint16_t aValueLen)1242 otError NcpBase::WritePropertyValueInsertedRemovedFrame(uint8_t aHeader,
1243 unsigned int aResponseCommand,
1244 spinel_prop_key_t aPropKey,
1245 const uint8_t *aValuePtr,
1246 uint16_t aValueLen)
1247 {
1248 otError error = OT_ERROR_NONE;
1249
1250 SuccessOrExit(error = mEncoder.BeginFrame(aHeader, aResponseCommand, aPropKey));
1251 SuccessOrExit(error = mEncoder.WriteData(aValuePtr, aValueLen));
1252 SuccessOrExit(error = mEncoder.EndFrame());
1253
1254 exit:
1255 return error;
1256 }
1257
1258 // ----------------------------------------------------------------------------
1259 // MARK: Individual Command Handlers
1260 // ----------------------------------------------------------------------------
1261
CommandHandler_NOOP(uint8_t aHeader)1262 otError NcpBase::CommandHandler_NOOP(uint8_t aHeader) { return PrepareLastStatusResponse(aHeader, SPINEL_STATUS_OK); }
1263
CommandHandler_RESET(uint8_t aHeader)1264 otError NcpBase::CommandHandler_RESET(uint8_t aHeader)
1265 {
1266 OT_UNUSED_VARIABLE(aHeader);
1267
1268 otError error = OT_ERROR_NONE;
1269 uint8_t reset_type = SPINEL_RESET_STACK;
1270
1271 if (mDecoder.GetRemainingLengthInStruct() > 0)
1272 {
1273 SuccessOrAssert(error = mDecoder.ReadUint8(reset_type));
1274 }
1275
1276 #if OPENTHREAD_RADIO
1277 if (reset_type == SPINEL_RESET_STACK)
1278 {
1279 otInstanceResetRadioStack(mInstance);
1280
1281 mIsRawStreamEnabled[mCurCommandIid] = false;
1282 mCurTransmitTID[mCurCommandIid] = 0;
1283 mCurScanChannel[mCurCommandIid] = kInvalidScanChannel;
1284 mSrcMatchEnabled[mCurCommandIid] = false;
1285
1286 ResetCounters();
1287
1288 SuccessOrAssert(error = WriteLastStatusFrame(SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID,
1289 SPINEL_STATUS_RESET_POWER_ON));
1290 }
1291 #if OPENTHREAD_CONFIG_PLATFORM_BOOTLOADER_MODE_ENABLE
1292 else if (reset_type == SPINEL_RESET_BOOTLOADER)
1293 {
1294 // Signal a platform reset to bootloader mode.
1295 // If implemented, this function shouldn't return.
1296 error = otInstanceResetToBootloader(mInstance);
1297 }
1298 #endif
1299 else
1300 #endif
1301 {
1302 // Signal a platform reset. If implemented, this function
1303 // shouldn't return.
1304 otInstanceReset(mInstance);
1305
1306 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1307 // We only get to this point if the
1308 // platform doesn't support resetting.
1309 // In such a case we fake it.
1310 IgnoreError(otThreadSetEnabled(mInstance, false));
1311 IgnoreError(otIp6SetEnabled(mInstance, false));
1312 #endif
1313
1314 sNcpInstance = nullptr;
1315 }
1316
1317 return error;
1318 }
1319
CommandHandler_PROP_VALUE_update(uint8_t aHeader,unsigned int aCommand)1320 otError NcpBase::CommandHandler_PROP_VALUE_update(uint8_t aHeader, unsigned int aCommand)
1321 {
1322 otError error = OT_ERROR_NONE;
1323 unsigned int propKey = 0;
1324
1325 error = mDecoder.ReadUintPacked(propKey);
1326
1327 VerifyOrExit(error == OT_ERROR_NONE, error = PrepareLastStatusResponse(aHeader, ThreadErrorToSpinelStatus(error)));
1328
1329 switch (aCommand)
1330 {
1331 case SPINEL_CMD_PROP_VALUE_GET:
1332 error = PrepareGetResponse(aHeader, static_cast<spinel_prop_key_t>(propKey));
1333 break;
1334
1335 case SPINEL_CMD_PROP_VALUE_SET:
1336 error = HandleCommandPropertySet(aHeader, static_cast<spinel_prop_key_t>(propKey));
1337 break;
1338
1339 case SPINEL_CMD_PROP_VALUE_INSERT:
1340 case SPINEL_CMD_PROP_VALUE_REMOVE:
1341 error = HandleCommandPropertyInsertRemove(aHeader, static_cast<spinel_prop_key_t>(propKey), aCommand);
1342 break;
1343
1344 default:
1345 break;
1346 }
1347
1348 exit:
1349 return error;
1350 }
1351
1352 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
1353
CommandHandler_PEEK(uint8_t aHeader)1354 otError NcpBase::CommandHandler_PEEK(uint8_t aHeader)
1355 {
1356 otError parseError = OT_ERROR_NONE;
1357 otError responseError = OT_ERROR_NONE;
1358 uint32_t address;
1359 uint16_t count;
1360
1361 SuccessOrExit(parseError = mDecoder.ReadUint32(address));
1362 SuccessOrExit(parseError = mDecoder.ReadUint16(count));
1363
1364 VerifyOrExit(count != 0, parseError = OT_ERROR_INVALID_ARGS);
1365
1366 if (mAllowPeekDelegate != nullptr)
1367 {
1368 VerifyOrExit(mAllowPeekDelegate(address, count), parseError = OT_ERROR_INVALID_ARGS);
1369 }
1370
1371 SuccessOrExit(responseError = mEncoder.BeginFrame(aHeader, SPINEL_CMD_PEEK_RET));
1372 SuccessOrExit(responseError = mEncoder.WriteUint32(address));
1373 SuccessOrExit(responseError = mEncoder.WriteUint16(count));
1374 SuccessOrExit(responseError = mEncoder.WriteData(reinterpret_cast<const uint8_t *>(address), count));
1375 SuccessOrExit(responseError = mEncoder.EndFrame());
1376
1377 exit:
1378 if (parseError != OT_ERROR_NONE)
1379 {
1380 responseError = PrepareLastStatusResponse(aHeader, ThreadErrorToSpinelStatus(parseError));
1381 }
1382
1383 return responseError;
1384 }
1385
CommandHandler_POKE(uint8_t aHeader)1386 otError NcpBase::CommandHandler_POKE(uint8_t aHeader)
1387 {
1388 otError parseError = OT_ERROR_NONE;
1389 uint32_t address;
1390 uint16_t count;
1391 const uint8_t *dataPtr = nullptr;
1392 uint16_t dataLen;
1393
1394 SuccessOrExit(parseError = mDecoder.ReadUint32(address));
1395 SuccessOrExit(parseError = mDecoder.ReadUint16(count));
1396 SuccessOrExit(parseError = mDecoder.ReadData(dataPtr, dataLen));
1397
1398 VerifyOrExit(count != 0, parseError = OT_ERROR_INVALID_ARGS);
1399 VerifyOrExit(count <= dataLen, parseError = OT_ERROR_INVALID_ARGS);
1400
1401 if (mAllowPokeDelegate != nullptr)
1402 {
1403 VerifyOrExit(mAllowPokeDelegate(address, count), parseError = OT_ERROR_INVALID_ARGS);
1404 }
1405
1406 memcpy(reinterpret_cast<uint8_t *>(address), dataPtr, count);
1407
1408 exit:
1409 return PrepareLastStatusResponse(aHeader, ThreadErrorToSpinelStatus(parseError));
1410 }
1411
1412 #endif // OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
1413
1414 // ----------------------------------------------------------------------------
1415 // MARK: Individual Property Getters and Setters
1416 // ----------------------------------------------------------------------------
1417
1418 #if OPENTHREAD_CONFIG_DIAG_ENABLE
1419
HandlePropertySet_SPINEL_PROP_NEST_STREAM_MFG(uint8_t aHeader)1420 otError NcpBase::HandlePropertySet_SPINEL_PROP_NEST_STREAM_MFG(uint8_t aHeader)
1421 {
1422 const char *string = nullptr;
1423 char output[OPENTHREAD_CONFIG_DIAG_OUTPUT_BUFFER_SIZE];
1424 otError error = OT_ERROR_NONE;
1425
1426 error = mDecoder.ReadUtf8(string);
1427
1428 VerifyOrExit(error == OT_ERROR_NONE, error = WriteLastStatusFrame(aHeader, ThreadErrorToSpinelStatus(error)));
1429
1430 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1431 // TODO do not pass mfg prefix
1432 // skip mfg prefix from wpantund
1433 if (memcmp(string, "mfg ", 4) == 0)
1434 {
1435 string += 4;
1436 }
1437 #endif
1438
1439 SuccessOrExit(error = otDiagProcessCmdLine(mInstance, string, output, sizeof(output)));
1440
1441 // Prepare the response
1442 SuccessOrExit(error = mEncoder.BeginFrame(aHeader, SPINEL_CMD_PROP_VALUE_IS, SPINEL_PROP_NEST_STREAM_MFG));
1443 SuccessOrExit(error = mEncoder.WriteUtf8(output));
1444 SuccessOrExit(error = mEncoder.EndFrame());
1445
1446 exit:
1447 return error;
1448 }
1449
1450 #endif // OPENTHREAD_CONFIG_DIAG_ENABLE
1451
HandlePropertyGet(void)1452 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_ENABLED>(void)
1453 {
1454 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1455 return mEncoder.WriteBool(otLinkRawIsEnabled(mInstance));
1456 #else
1457 return mEncoder.WriteBool(false);
1458 #endif
1459 }
1460
HandlePropertyGet(void)1461 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_CHAN>(void)
1462 {
1463 return mEncoder.WriteUint8(otLinkGetChannel(mInstance));
1464 }
1465
HandlePropertySet(void)1466 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_CHAN>(void)
1467 {
1468 unsigned int channel = 0;
1469 otError error = OT_ERROR_NONE;
1470
1471 SuccessOrExit(error = mDecoder.ReadUintPacked(channel));
1472
1473 error = otLinkSetChannel(mInstance, static_cast<uint8_t>(channel));
1474
1475 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1476
1477 SuccessOrExit(error);
1478
1479 // Make sure we are update the receiving channel if raw link is enabled and we have raw
1480 // stream enabled already
1481 if (otLinkRawIsEnabled(mInstance) && mIsRawStreamEnabled[mCurCommandIid])
1482 {
1483 error = otLinkRawReceive(mInstance);
1484 }
1485
1486 #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1487
1488 exit:
1489 return error;
1490 }
1491
HandlePropertyGet(void)1492 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_PROMISCUOUS_MODE>(void)
1493 {
1494 bool isPromiscuous;
1495
1496 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1497 isPromiscuous = otLinkRawGetPromiscuous(mInstance);
1498 #else
1499 isPromiscuous = otLinkIsPromiscuous(mInstance);
1500 #endif
1501
1502 return mEncoder.WriteUint8(isPromiscuous ? SPINEL_MAC_PROMISCUOUS_MODE_FULL : SPINEL_MAC_PROMISCUOUS_MODE_OFF);
1503 }
1504
HandlePropertySet(void)1505 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_PROMISCUOUS_MODE>(void)
1506 {
1507 uint8_t mode = 0;
1508 otError error = OT_ERROR_NONE;
1509
1510 SuccessOrExit(error = mDecoder.ReadUint8(mode));
1511
1512 switch (mode)
1513 {
1514 case SPINEL_MAC_PROMISCUOUS_MODE_OFF:
1515 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1516 error = otLinkRawSetPromiscuous(mInstance, false);
1517 #else
1518 error = otLinkSetPromiscuous(mInstance, false);
1519 #endif
1520 break;
1521
1522 case SPINEL_MAC_PROMISCUOUS_MODE_NETWORK:
1523 case SPINEL_MAC_PROMISCUOUS_MODE_FULL:
1524 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1525 error = otLinkRawSetPromiscuous(mInstance, true);
1526 #else
1527 error = otLinkSetPromiscuous(mInstance, true);
1528 #endif
1529 break;
1530
1531 default:
1532 error = OT_ERROR_INVALID_ARGS;
1533 break;
1534 }
1535
1536 exit:
1537 return error;
1538 }
1539
HandlePropertySet(void)1540 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_RX_ON_WHEN_IDLE_MODE>(void)
1541 {
1542 bool enabled;
1543 otError error = OT_ERROR_NONE;
1544
1545 SuccessOrExit(error = mDecoder.ReadBool(enabled));
1546 otPlatRadioSetRxOnWhenIdle(mInstance, enabled);
1547
1548 exit:
1549 return error;
1550 }
1551
HandlePropertyGet(void)1552 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_15_4_PANID>(void)
1553 {
1554 return mEncoder.WriteUint16(otLinkGetPanId(mInstance));
1555 }
1556
HandlePropertySet(void)1557 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_15_4_PANID>(void)
1558 {
1559 uint16_t panid;
1560 otError error = OT_ERROR_NONE;
1561
1562 SuccessOrExit(error = mDecoder.ReadUint16(panid));
1563
1564 error = otLinkSetPanId(mInstance, panid);
1565
1566 exit:
1567 return error;
1568 }
1569
HandlePropertyGet(void)1570 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_15_4_LADDR>(void)
1571 {
1572 return mEncoder.WriteEui64(*otLinkGetExtendedAddress(mInstance));
1573 }
1574
HandlePropertySet(void)1575 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_15_4_LADDR>(void)
1576 {
1577 const otExtAddress *extAddress;
1578 otError error = OT_ERROR_NONE;
1579
1580 SuccessOrExit(error = mDecoder.ReadEui64(extAddress));
1581
1582 error = otLinkSetExtendedAddress(mInstance, extAddress);
1583
1584 exit:
1585 return error;
1586 }
1587
HandlePropertyGet(void)1588 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_15_4_SADDR>(void)
1589 {
1590 return mEncoder.WriteUint16(otLinkGetShortAddress(mInstance));
1591 }
1592
HandlePropertyGet(void)1593 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_RAW_STREAM_ENABLED>(void)
1594 {
1595 return mEncoder.WriteBool(mIsRawStreamEnabled[mCurCommandIid]);
1596 }
1597
HandlePropertySet(void)1598 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_RAW_STREAM_ENABLED>(void)
1599 {
1600 bool enabled = false;
1601 otError error = OT_ERROR_NONE;
1602
1603 SuccessOrExit(error = mDecoder.ReadBool(enabled));
1604
1605 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1606
1607 if (otLinkRawIsEnabled(mInstance))
1608 {
1609 if (enabled)
1610 {
1611 error = otLinkRawReceive(mInstance);
1612 }
1613 else
1614 {
1615 error = otLinkRawSleep(mInstance);
1616 }
1617 }
1618
1619 #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1620
1621 mIsRawStreamEnabled[mCurCommandIid] = enabled;
1622
1623 exit:
1624 return error;
1625 }
1626
1627 #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE || OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE
HandlePropertyGet(void)1628 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_RCP_CSL_ACCURACY>(void)
1629 {
1630 return mEncoder.WriteUint8(otPlatRadioGetCslAccuracy(mInstance));
1631 }
1632 #endif
1633
1634 #if OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE
HandlePropertyGet(void)1635 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_RCP_CSL_UNCERTAINTY>(void)
1636 {
1637 return mEncoder.WriteUint8(otPlatRadioGetCslUncertainty(mInstance));
1638 }
1639 #endif
1640
EncodeChannelMask(uint32_t aChannelMask)1641 otError NcpBase::EncodeChannelMask(uint32_t aChannelMask)
1642 {
1643 otError error = OT_ERROR_NONE;
1644
1645 for (uint8_t i = 0; i < 32; i++)
1646 {
1647 if (0 != (aChannelMask & (1 << i)))
1648 {
1649 SuccessOrExit(error = mEncoder.WriteUint8(i));
1650 }
1651 }
1652
1653 exit:
1654 return error;
1655 }
1656
DecodeChannelMask(uint32_t & aChannelMask)1657 otError NcpBase::DecodeChannelMask(uint32_t &aChannelMask)
1658 {
1659 otError error = OT_ERROR_NONE;
1660 uint8_t channel;
1661
1662 aChannelMask = 0;
1663
1664 while (!mDecoder.IsAllReadInStruct())
1665 {
1666 SuccessOrExit(error = mDecoder.ReadUint8(channel));
1667 VerifyOrExit(channel <= 31, error = OT_ERROR_INVALID_ARGS);
1668 aChannelMask |= (1UL << channel);
1669 }
1670
1671 exit:
1672 return error;
1673 }
1674
HandlePropertyGet(void)1675 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_SCAN_MASK>(void)
1676 {
1677 return EncodeChannelMask(mScanChannelMask);
1678 }
1679
HandlePropertySet(void)1680 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_SCAN_MASK>(void)
1681 {
1682 uint32_t newMask = 0;
1683 otError error = OT_ERROR_NONE;
1684
1685 SuccessOrExit(error = DecodeChannelMask(newMask));
1686 mScanChannelMask = newMask;
1687
1688 exit:
1689 return error;
1690 }
1691
HandlePropertyGet(void)1692 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_SCAN_PERIOD>(void)
1693 {
1694 return mEncoder.WriteUint16(mScanPeriod);
1695 }
1696
HandlePropertySet(void)1697 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_SCAN_PERIOD>(void)
1698 {
1699 return mDecoder.ReadUint16(mScanPeriod);
1700 }
1701
HandlePropertyGet(void)1702 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MAC_SCAN_STATE>(void)
1703 {
1704 uint8_t scanState = SPINEL_SCAN_STATE_IDLE;
1705
1706 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1707
1708 if (otLinkRawIsEnabled(mInstance))
1709 {
1710 scanState = (mCurScanChannel[mCurCommandIid] == kInvalidScanChannel) ? SPINEL_SCAN_STATE_IDLE
1711 : SPINEL_SCAN_STATE_ENERGY;
1712 }
1713 else
1714
1715 #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1716
1717 {
1718 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1719 if (otLinkIsActiveScanInProgress(mInstance))
1720 {
1721 scanState = SPINEL_SCAN_STATE_BEACON;
1722 }
1723 else if (otLinkIsEnergyScanInProgress(mInstance))
1724 {
1725 scanState = SPINEL_SCAN_STATE_ENERGY;
1726 }
1727 else if (otThreadIsDiscoverInProgress(mInstance))
1728 {
1729 scanState = SPINEL_SCAN_STATE_DISCOVER;
1730 }
1731 else
1732 {
1733 scanState = SPINEL_SCAN_STATE_IDLE;
1734 }
1735 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
1736 }
1737
1738 return mEncoder.WriteUint8(scanState);
1739 }
1740
HandlePropertySet(void)1741 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MAC_SCAN_STATE>(void)
1742 {
1743 uint8_t state = 0;
1744 otError error = OT_ERROR_NONE;
1745
1746 SuccessOrExit(error = mDecoder.ReadUint8(state));
1747
1748 switch (state)
1749 {
1750 case SPINEL_SCAN_STATE_IDLE:
1751 error = OT_ERROR_NONE;
1752 break;
1753
1754 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1755 case SPINEL_SCAN_STATE_BEACON:
1756 error = otLinkActiveScan(mInstance, mScanChannelMask, mScanPeriod, &HandleActiveScanResult_Jump, this);
1757 SuccessOrExit(error);
1758 break;
1759 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
1760
1761 case SPINEL_SCAN_STATE_ENERGY:
1762 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1763 if (otLinkRawIsEnabled(mInstance))
1764 {
1765 uint8_t scanChannel;
1766
1767 // Make sure we aren't already scanning and that we have
1768 // only 1 bit set for the channel mask.
1769 VerifyOrExit(mCurScanChannel[mCurCommandIid] == kInvalidScanChannel, error = OT_ERROR_INVALID_STATE);
1770 VerifyOrExit(HasOnly1BitSet(mScanChannelMask), error = OT_ERROR_INVALID_ARGS);
1771
1772 scanChannel = IndexOfMSB(mScanChannelMask);
1773 mCurScanChannel[mCurCommandIid] = static_cast<int8_t>(scanChannel);
1774
1775 error = otLinkRawEnergyScan(mInstance, scanChannel, mScanPeriod, LinkRawEnergyScanDone);
1776 }
1777 else
1778 #endif // OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1779 {
1780 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1781 error = otLinkEnergyScan(mInstance, mScanChannelMask, mScanPeriod, &HandleEnergyScanResult_Jump, this);
1782 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
1783 }
1784
1785 SuccessOrExit(error);
1786 break;
1787
1788 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1789 case SPINEL_SCAN_STATE_DISCOVER:
1790 error = otThreadDiscover(mInstance, mScanChannelMask, mDiscoveryScanPanId, mDiscoveryScanJoinerFlag,
1791 mDiscoveryScanEnableFiltering, &HandleActiveScanResult_Jump, this);
1792
1793 SuccessOrExit(error);
1794 break;
1795 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
1796
1797 default:
1798 error = OT_ERROR_NOT_IMPLEMENTED;
1799 break;
1800 }
1801
1802 exit:
1803 return error;
1804 }
1805
HandlePropertyGet(void)1806 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_UNSOL_UPDATE_FILTER>(void)
1807 {
1808 otError error = OT_ERROR_NONE;
1809 uint8_t numEntries;
1810 const ChangedPropsSet::Entry *entry;
1811
1812 entry = mChangedPropsSet.GetSupportedEntries(numEntries);
1813
1814 for (uint8_t index = 0; index < numEntries; index++, entry++)
1815 {
1816 if (mChangedPropsSet.IsEntryFiltered(index))
1817 {
1818 SuccessOrExit(error = mEncoder.WriteUintPacked(entry->mPropKey));
1819 }
1820 }
1821
1822 exit:
1823 return error;
1824 }
1825
HandlePropertySet(void)1826 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_UNSOL_UPDATE_FILTER>(void)
1827 {
1828 unsigned int propKey;
1829 otError error = OT_ERROR_NONE;
1830
1831 // First clear the current filter.
1832 mChangedPropsSet.ClearFilter();
1833
1834 while (mDecoder.GetRemainingLengthInStruct() > 0)
1835 {
1836 SuccessOrExit(error = mDecoder.ReadUintPacked(propKey));
1837
1838 IgnoreError(mChangedPropsSet.EnablePropertyFilter(static_cast<spinel_prop_key_t>(propKey), true));
1839 }
1840
1841 exit:
1842 // If we had an error, we may have actually changed
1843 // the state of the filter, So we need to report
1844 // those incomplete changes via an asynchronous
1845 // change event.
1846
1847 if (error != OT_ERROR_NONE)
1848 {
1849 IgnoreError(WritePropertyValueIsFrame(SPINEL_HEADER_FLAG | SPINEL_HEADER_TX_NOTIFICATION_IID,
1850 SPINEL_PROP_UNSOL_UPDATE_FILTER));
1851 }
1852
1853 return error;
1854 }
1855
HandlePropertyInsert(void)1856 template <> otError NcpBase::HandlePropertyInsert<SPINEL_PROP_UNSOL_UPDATE_FILTER>(void)
1857 {
1858 otError error = OT_ERROR_NONE;
1859 unsigned int propKey;
1860
1861 SuccessOrExit(error = mDecoder.ReadUintPacked(propKey));
1862
1863 error = mChangedPropsSet.EnablePropertyFilter(static_cast<spinel_prop_key_t>(propKey), true);
1864
1865 exit:
1866 return error;
1867 }
1868
HandlePropertyRemove(void)1869 template <> otError NcpBase::HandlePropertyRemove<SPINEL_PROP_UNSOL_UPDATE_FILTER>(void)
1870 {
1871 otError error = OT_ERROR_NONE;
1872 unsigned int propKey;
1873
1874 SuccessOrExit(error = mDecoder.ReadUintPacked(propKey));
1875
1876 error = mChangedPropsSet.EnablePropertyFilter(static_cast<spinel_prop_key_t>(propKey), false);
1877
1878 exit:
1879 return error;
1880 }
1881
HandlePropertyGet(void)1882 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_LAST_STATUS>(void)
1883 {
1884 return mEncoder.WriteUintPacked(mLastStatus);
1885 }
1886
HandlePropertyGet(void)1887 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PROTOCOL_VERSION>(void)
1888 {
1889 otError error = OT_ERROR_NONE;
1890
1891 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_PROTOCOL_VERSION_THREAD_MAJOR));
1892 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_PROTOCOL_VERSION_THREAD_MINOR));
1893
1894 exit:
1895 return error;
1896 }
1897
HandlePropertyGet(void)1898 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_INTERFACE_TYPE>(void)
1899 {
1900 return mEncoder.WriteUintPacked(SPINEL_PROTOCOL_TYPE_THREAD);
1901 }
1902
HandlePropertyGet(void)1903 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_VENDOR_ID>(void)
1904 {
1905 return mEncoder.WriteUintPacked(0); // Vendor ID. Zero for unknown.
1906 }
1907
HandlePropertyGet(void)1908 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_CAPS>(void)
1909 {
1910 otError error = OT_ERROR_NONE;
1911
1912 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_COUNTERS));
1913 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_UNSOL_UPDATE_FILTER));
1914
1915 #if OPENTHREAD_CONFIG_NCP_ENABLE_MCU_POWER_STATE_CONTROL
1916 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_MCU_POWER_STATE));
1917 #endif
1918
1919 #if OPENTHREAD_CONFIG_RADIO_2P4GHZ_OQPSK_SUPPORT
1920 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_802_15_4_2450MHZ_OQPSK));
1921 #endif
1922
1923 #if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT
1924 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_802_15_4_915MHZ_OQPSK));
1925 #endif
1926
1927 #if OPENTHREAD_FTD
1928 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CONFIG_FTD));
1929 #elif OPENTHREAD_MTD
1930 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CONFIG_MTD));
1931 #elif OPENTHREAD_RADIO
1932 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CONFIG_RADIO));
1933 #endif
1934
1935 #if OPENTHREAD_RADIO || OPENTHREAD_CONFIG_LINK_RAW_ENABLE
1936 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_MAC_RAW));
1937 #endif
1938
1939 #if OPENTHREAD_RADIO
1940 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_RCP_API_VERSION));
1941 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_RCP_MIN_HOST_API_VERSION));
1942 #endif
1943
1944 #if OPENTHREAD_CONFIG_PLATFORM_BOOTLOADER_MODE_ENABLE
1945 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_RCP_RESET_TO_BOOTLOADER));
1946 #endif
1947
1948 #if OPENTHREAD_PLATFORM_POSIX
1949 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_POSIX));
1950 #endif
1951
1952 #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP)
1953 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_OPENTHREAD_LOG_METADATA));
1954 #endif
1955
1956 #if OPENTHREAD_MTD || OPENTHREAD_FTD
1957
1958 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_NET_THREAD_1_1));
1959
1960 #if (OPENTHREAD_CONFIG_THREAD_VERSION >= OT_THREAD_VERSION_1_2)
1961 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_NET_THREAD_1_2));
1962 #endif
1963
1964 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_PCAP));
1965
1966 #if OPENTHREAD_CONFIG_MAC_FILTER_ENABLE
1967 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_MAC_ALLOWLIST));
1968 #endif
1969
1970 #if OPENTHREAD_CONFIG_JAM_DETECTION_ENABLE
1971 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_JAM_DETECT));
1972 #endif
1973
1974 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CHILD_SUPERVISION));
1975
1976 #if OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE
1977 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CHANNEL_MONITOR));
1978 #endif
1979
1980 #if OPENTHREAD_CONFIG_CHANNEL_MANAGER_ENABLE && OPENTHREAD_FTD
1981 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_CHANNEL_MANAGER));
1982 #endif
1983
1984 #if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
1985 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_TIME_SYNC));
1986 #endif
1987
1988 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_ERROR_RATE_TRACKING));
1989
1990 #if OPENTHREAD_CONFIG_MLE_STEERING_DATA_SET_OOB_ENABLE
1991 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_OOB_STEERING_DATA));
1992 #endif
1993
1994 #if OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE
1995 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_SLAAC));
1996 #endif
1997
1998 #if OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE
1999 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_RADIO_COEX));
2000 #endif
2001
2002 #if OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE
2003 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_MAC_RETRY_HISTOGRAM));
2004 #endif
2005
2006 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
2007 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_PEEK_POKE));
2008 #endif
2009
2010 #if OPENTHREAD_CONFIG_MLE_MAX_CHILDREN > 0
2011 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_ROLE_ROUTER));
2012 #endif
2013
2014 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_ROLE_SLEEPY));
2015
2016 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_COMMISSIONER_ENABLE
2017 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_COMMISSIONER));
2018 #endif
2019
2020 #if OPENTHREAD_CONFIG_JOINER_ENABLE
2021 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_JOINER));
2022 #endif
2023
2024 #if OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE
2025 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_BORDER_ROUTER));
2026 #endif
2027
2028 #if OPENTHREAD_CONFIG_UDP_FORWARD_ENABLE
2029 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_UDP_FORWARD));
2030 #endif
2031
2032 #if OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE
2033 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_SERVICE));
2034 #endif
2035
2036 #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE
2037 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_CSL_RECEIVER));
2038 #endif
2039
2040 #if OPENTHREAD_CONFIG_MULTI_RADIO
2041 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_MULTI_RADIO));
2042 #endif
2043
2044 #if OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE
2045 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_SRP_CLIENT));
2046 #endif
2047
2048 #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE
2049 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_LINK_METRICS));
2050 #endif
2051
2052 #if OPENTHREAD_CONFIG_DUA_ENABLE
2053 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_DUA));
2054 #endif
2055
2056 #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE
2057 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_REFERENCE_DEVICE));
2058 #endif
2059
2060 #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE
2061 SuccessOrExit(error = mEncoder.WriteUintPacked(SPINEL_CAP_THREAD_BACKBONE_ROUTER));
2062 #endif
2063
2064 #endif // OPENTHREAD_MTD || OPENTHREAD_FTD
2065
2066 exit:
2067 return error;
2068 }
2069
HandlePropertyGet(void)2070 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_NCP_VERSION>(void)
2071 {
2072 return mEncoder.WriteUtf8(otGetVersionString());
2073 }
2074
HandlePropertyGet(void)2075 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_INTERFACE_COUNT>(void)
2076 {
2077 uint8_t instances = 1;
2078 #if OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
2079 instances = 0;
2080 for (uint8_t i = 0; i <= SPINEL_HEADER_IID_MAX; i++)
2081 {
2082 if (mInstances[i] != nullptr)
2083 {
2084 instances++;
2085 }
2086 }
2087 #endif // OPENTHREAD_CONFIG_MULTIPAN_RCP_ENABLE && OPENTHREAD_RADIO
2088
2089 return mEncoder.WriteUint8(instances);
2090 }
2091
2092 #if OPENTHREAD_CONFIG_NCP_ENABLE_MCU_POWER_STATE_CONTROL
2093
HandlePropertyGet(void)2094 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MCU_POWER_STATE>(void)
2095 {
2096 spinel_mcu_power_state_t state = SPINEL_MCU_POWER_STATE_ON;
2097
2098 switch (otPlatGetMcuPowerState(mInstance))
2099 {
2100 case OT_PLAT_MCU_POWER_STATE_ON:
2101 state = SPINEL_MCU_POWER_STATE_ON;
2102 break;
2103
2104 case OT_PLAT_MCU_POWER_STATE_LOW_POWER:
2105 state = SPINEL_MCU_POWER_STATE_LOW_POWER;
2106 break;
2107
2108 case OT_PLAT_MCU_POWER_STATE_OFF:
2109 state = SPINEL_MCU_POWER_STATE_OFF;
2110 break;
2111 }
2112
2113 return mEncoder.WriteUint8(state);
2114 }
2115
HandlePropertySet(void)2116 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_MCU_POWER_STATE>(void)
2117 {
2118 otError error = OT_ERROR_NONE;
2119 otPlatMcuPowerState powerState;
2120 uint8_t state;
2121
2122 SuccessOrExit(error = mDecoder.ReadUint8(state));
2123
2124 switch (state)
2125 {
2126 case SPINEL_MCU_POWER_STATE_ON:
2127 powerState = OT_PLAT_MCU_POWER_STATE_ON;
2128 break;
2129
2130 case SPINEL_MCU_POWER_STATE_LOW_POWER:
2131 powerState = OT_PLAT_MCU_POWER_STATE_LOW_POWER;
2132 break;
2133
2134 case SPINEL_MCU_POWER_STATE_OFF:
2135 powerState = OT_PLAT_MCU_POWER_STATE_OFF;
2136 break;
2137
2138 default:
2139 ExitNow(error = OT_ERROR_INVALID_ARGS);
2140 }
2141
2142 SuccessOrExit(error = otPlatSetMcuPowerState(mInstance, powerState));
2143
2144 #if OPENTHREAD_FTD || OPENTHREAD_MTD
2145
2146 // If the call `otPlatSetMcuPowerState()` was successful and the desire
2147 // state is `OFF`, ensure to disable Thread (MLE) operation (and stop
2148 // legacy) and also bring the IPv6 interface down.
2149
2150 if (powerState == OT_PLAT_MCU_POWER_STATE_OFF)
2151 {
2152 if (otThreadGetDeviceRole(mInstance) != OT_DEVICE_ROLE_DISABLED)
2153 {
2154 IgnoreError(otThreadSetEnabled(mInstance, false));
2155 }
2156
2157 if (otIp6IsEnabled(mInstance))
2158 {
2159 IgnoreError(otIp6SetEnabled(mInstance, false));
2160 }
2161 }
2162 #endif // #if OPENTHREAD_FTD || OPENTHREAD_MTD
2163
2164 exit:
2165 return error;
2166 }
2167
2168 #else // OPENTHREAD_CONFIG_NCP_ENABLE_MCU_POWER_STATE_CONTROL
2169
HandlePropertyGet(void)2170 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_MCU_POWER_STATE>(void)
2171 {
2172 return mEncoder.WriteUint8(SPINEL_MCU_POWER_STATE_ON);
2173 }
2174
2175 #endif // OPENTHREAD_CONFIG_NCP_ENABLE_MCU_POWER_STATE_CONTROL
2176
HandlePropertyGet(void)2177 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_POWER_STATE>(void)
2178 {
2179 return mEncoder.WriteUint8(SPINEL_POWER_STATE_ONLINE);
2180 }
2181
HandlePropertySet(void)2182 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_POWER_STATE>(void) { return OT_ERROR_NOT_IMPLEMENTED; }
2183
HandlePropertyGet(void)2184 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_HWADDR>(void)
2185 {
2186 otExtAddress hwAddr;
2187
2188 otLinkGetFactoryAssignedIeeeEui64(mInstance, &hwAddr);
2189
2190 return mEncoder.WriteEui64(hwAddr);
2191 }
2192
HandlePropertyGet(void)2193 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_LOCK>(void)
2194 {
2195 // TODO: Implement property lock (Needs API!)
2196 return mEncoder.OverwriteWithLastStatusError(SPINEL_STATUS_UNIMPLEMENTED);
2197 }
2198
HandlePropertyGet(void)2199 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_HOST_POWER_STATE>(void)
2200 {
2201 return mEncoder.WriteUint8(mHostPowerState);
2202 }
2203
2204 // Setting `HOST_POWER_STATE` is treated and implemented differently from other
2205 // handlers as it requires two special behaviors (a) the response frame for the
2206 // set operation should be tracked and only when it is delivered we can assume
2207 // that host is sleep (b) the response is critical so if there is no spinel
2208 // buffer to prepare the response, the current spinel header is saved to
2209 // prepare and send the response as soon as buffer space becomes available.
HandlePropertySet_SPINEL_PROP_HOST_POWER_STATE(uint8_t aHeader)2210 otError NcpBase::HandlePropertySet_SPINEL_PROP_HOST_POWER_STATE(uint8_t aHeader)
2211 {
2212 uint8_t powerState;
2213 otError error = OT_ERROR_NONE;
2214
2215 error = mDecoder.ReadUint8(powerState);
2216
2217 if (error == OT_ERROR_NONE)
2218 {
2219 switch (powerState)
2220 {
2221 case SPINEL_HOST_POWER_STATE_OFFLINE:
2222 case SPINEL_HOST_POWER_STATE_DEEP_SLEEP:
2223 case SPINEL_HOST_POWER_STATE_LOW_POWER:
2224 case SPINEL_HOST_POWER_STATE_ONLINE:
2225 // Adopt the requested power state.
2226 mHostPowerState = static_cast<spinel_host_power_state_t>(powerState);
2227 break;
2228
2229 case SPINEL_HOST_POWER_STATE_RESERVED:
2230 // Per the specification, treat this as synonymous with SPINEL_HOST_POWER_STATE_DEEP_SLEEP.
2231 mHostPowerState = SPINEL_HOST_POWER_STATE_DEEP_SLEEP;
2232 break;
2233
2234 default:
2235 // Per the specification, treat unrecognized values as synonymous with SPINEL_HOST_POWER_STATE_LOW_POWER.
2236 mHostPowerState = SPINEL_HOST_POWER_STATE_LOW_POWER;
2237 break;
2238 }
2239
2240 mHostPowerStateHeader = 0;
2241
2242 error = WritePropertyValueIsFrame(aHeader, SPINEL_PROP_HOST_POWER_STATE);
2243
2244 if (mHostPowerState != SPINEL_HOST_POWER_STATE_ONLINE)
2245 {
2246 if (error == OT_ERROR_NONE)
2247 {
2248 mHostPowerReplyFrameTag = GetLastOutboundFrameTag();
2249 }
2250 else
2251 {
2252 mHostPowerReplyFrameTag = Spinel::Buffer::kInvalidTag;
2253 }
2254
2255 mHostPowerStateInProgress = true;
2256 }
2257
2258 if (error != OT_ERROR_NONE)
2259 {
2260 mHostPowerStateHeader = aHeader;
2261
2262 // The reply will be queued when buffer space becomes available
2263 // in the NCP tx buffer so we return `success` to avoid sending a
2264 // NOMEM status for the same tid through `mDroppedReplyTid` list.
2265
2266 error = OT_ERROR_NONE;
2267 }
2268 }
2269 else
2270 {
2271 error = WriteLastStatusFrame(aHeader, ThreadErrorToSpinelStatus(error));
2272 }
2273
2274 return error;
2275 }
2276
HandlePropertyGet(void)2277 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_UNSOL_UPDATE_LIST>(void)
2278 {
2279 otError error = OT_ERROR_NONE;
2280 uint8_t numEntries;
2281 const ChangedPropsSet::Entry *entry;
2282
2283 entry = mChangedPropsSet.GetSupportedEntries(numEntries);
2284
2285 for (uint8_t index = 0; index < numEntries; index++, entry++)
2286 {
2287 if (entry->mFilterable)
2288 {
2289 SuccessOrExit(error = mEncoder.WriteUintPacked(entry->mPropKey));
2290 }
2291 }
2292
2293 exit:
2294 return error;
2295 }
2296
HandlePropertyGet(void)2297 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_RSSI>(void)
2298 {
2299 return mEncoder.WriteInt8(otPlatRadioGetRssi(mInstance));
2300 }
2301
HandlePropertyGet(void)2302 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_RX_SENSITIVITY>(void)
2303 {
2304 return mEncoder.WriteInt8(otPlatRadioGetReceiveSensitivity(mInstance));
2305 }
2306
HandlePropertyGet(void)2307 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_FREQ>(void)
2308 {
2309 uint32_t freq_khz(0);
2310 const uint8_t chan(otLinkGetChannel(mInstance));
2311
2312 if (chan == 0)
2313 {
2314 freq_khz = 868300;
2315 }
2316 else if (chan < 11)
2317 {
2318 freq_khz = 906000 - (2000 * 1) + 2000 * (chan);
2319 }
2320 else if (chan < 26)
2321 {
2322 freq_khz = 2405000 - (5000 * 11) + 5000 * (chan);
2323 }
2324
2325 return mEncoder.WriteUint32(freq_khz);
2326 }
2327
HandlePropertyGet(void)2328 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_CCA_THRESHOLD>(void)
2329 {
2330 int8_t threshold;
2331 otError error = OT_ERROR_NONE;
2332
2333 error = otPlatRadioGetCcaEnergyDetectThreshold(mInstance, &threshold);
2334
2335 if (error == OT_ERROR_NONE)
2336 {
2337 error = mEncoder.WriteInt8(threshold);
2338 }
2339 else
2340 {
2341 error = mEncoder.OverwriteWithLastStatusError(ThreadErrorToSpinelStatus(error));
2342 }
2343
2344 return error;
2345 }
2346
HandlePropertySet(void)2347 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_CCA_THRESHOLD>(void)
2348 {
2349 int8_t threshold = 0;
2350 otError error = OT_ERROR_NONE;
2351
2352 SuccessOrExit(error = mDecoder.ReadInt8(threshold));
2353 error = otPlatRadioSetCcaEnergyDetectThreshold(mInstance, threshold);
2354
2355 exit:
2356 return error;
2357 }
2358
HandlePropertyGet(void)2359 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_TX_POWER>(void)
2360 {
2361 int8_t power;
2362 otError error;
2363
2364 error = otPlatRadioGetTransmitPower(mInstance, &power);
2365
2366 if (error == OT_ERROR_NONE)
2367 {
2368 error = mEncoder.WriteInt8(power);
2369 }
2370 else
2371 {
2372 error = mEncoder.OverwriteWithLastStatusError(ThreadErrorToSpinelStatus(error));
2373 }
2374
2375 return error;
2376 }
2377
HandlePropertySet(void)2378 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_TX_POWER>(void)
2379 {
2380 int8_t txPower = 0;
2381 otError error = OT_ERROR_NONE;
2382
2383 SuccessOrExit(error = mDecoder.ReadInt8(txPower));
2384 error = otPlatRadioSetTransmitPower(mInstance, txPower);
2385
2386 exit:
2387 return error;
2388 }
2389
HandlePropertyGet(void)2390 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_FEM_LNA_GAIN>(void)
2391 {
2392 int8_t gain;
2393 otError error = OT_ERROR_NONE;
2394
2395 error = otPlatRadioGetFemLnaGain(mInstance, &gain);
2396
2397 if (error == OT_ERROR_NONE)
2398 {
2399 error = mEncoder.WriteInt8(gain);
2400 }
2401 else
2402 {
2403 error = mEncoder.OverwriteWithLastStatusError(ThreadErrorToSpinelStatus(error));
2404 }
2405
2406 return error;
2407 }
2408
HandlePropertySet(void)2409 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_FEM_LNA_GAIN>(void)
2410 {
2411 int8_t gain = 0;
2412 otError error = OT_ERROR_NONE;
2413
2414 SuccessOrExit(error = mDecoder.ReadInt8(gain));
2415 error = otPlatRadioSetFemLnaGain(mInstance, gain);
2416
2417 exit:
2418 return error;
2419 }
2420
HandlePropertySet(void)2421 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_CHAN_MAX_POWER>(void)
2422 {
2423 uint8_t channel;
2424 int8_t maxPower;
2425 otError error = OT_ERROR_NONE;
2426
2427 SuccessOrExit(error = mDecoder.ReadUint8(channel));
2428 SuccessOrExit(error = mDecoder.ReadInt8(maxPower));
2429 error = otPlatRadioSetChannelMaxTransmitPower(mInstance, channel, maxPower);
2430
2431 exit:
2432 return error;
2433 }
2434
HandlePropertyGet(void)2435 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_REGION_CODE>(void)
2436 {
2437 uint16_t regionCode;
2438 otError error = OT_ERROR_NONE;
2439
2440 error = otPlatRadioGetRegion(mInstance, ®ionCode);
2441 if (error == OT_ERROR_NONE)
2442 {
2443 error = mEncoder.WriteUint16(regionCode);
2444 }
2445 else
2446 {
2447 error = mEncoder.OverwriteWithLastStatusError(ThreadErrorToSpinelStatus(error));
2448 }
2449
2450 return error;
2451 }
2452
HandlePropertySet(void)2453 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_REGION_CODE>(void)
2454 {
2455 uint16_t regionCode;
2456 otError error = OT_ERROR_NONE;
2457
2458 SuccessOrExit(error = mDecoder.ReadUint16(regionCode));
2459 error = otPlatRadioSetRegion(mInstance, regionCode);
2460
2461 exit:
2462 return error;
2463 }
2464
HandlePropertyGet(void)2465 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_DEBUG_TEST_ASSERT>(void)
2466 {
2467 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2468 OT_ASSERT(false);
2469 #endif
2470
2471 // We only get to this point if `OT_ASSERT(false)`
2472 // does not cause an NCP reset on the platform.
2473 // In such a case we return `false` as the
2474 // property value to indicate this.
2475
2476 OT_UNREACHABLE_CODE(return mEncoder.WriteBool(false);)
2477 }
2478
HandlePropertyGet(void)2479 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_DEBUG_TEST_WATCHDOG>(void)
2480 {
2481 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2482 while (true)
2483 ;
2484 #endif
2485
2486 OT_UNREACHABLE_CODE(return OT_ERROR_NONE;)
2487 }
2488
HandlePropertyGet(void)2489 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_DEBUG_NCP_LOG_LEVEL>(void)
2490 {
2491 return mEncoder.WriteUint8(ConvertLogLevel(otLoggingGetLevel()));
2492 }
2493
2494 #if OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE
HandlePropertySet(void)2495 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_DEBUG_NCP_LOG_LEVEL>(void)
2496 {
2497 otError error;
2498 uint8_t spinelNcpLogLevel = 0;
2499 otLogLevel logLevel;
2500
2501 SuccessOrExit(error = mDecoder.ReadUint8(spinelNcpLogLevel));
2502
2503 switch (spinelNcpLogLevel)
2504 {
2505 case SPINEL_NCP_LOG_LEVEL_EMERG:
2506 case SPINEL_NCP_LOG_LEVEL_ALERT:
2507 logLevel = OT_LOG_LEVEL_NONE;
2508 break;
2509
2510 case SPINEL_NCP_LOG_LEVEL_CRIT:
2511 logLevel = OT_LOG_LEVEL_CRIT;
2512 break;
2513
2514 case SPINEL_NCP_LOG_LEVEL_ERR:
2515 case SPINEL_NCP_LOG_LEVEL_WARN:
2516 logLevel = OT_LOG_LEVEL_WARN;
2517 break;
2518
2519 case SPINEL_NCP_LOG_LEVEL_NOTICE:
2520 logLevel = OT_LOG_LEVEL_NOTE;
2521 break;
2522
2523 case SPINEL_NCP_LOG_LEVEL_INFO:
2524 logLevel = OT_LOG_LEVEL_INFO;
2525 break;
2526
2527 case SPINEL_NCP_LOG_LEVEL_DEBUG:
2528 logLevel = OT_LOG_LEVEL_DEBG;
2529 break;
2530
2531 default:
2532 ExitNow(error = OT_ERROR_INVALID_ARGS);
2533 }
2534
2535 IgnoreError(otLoggingSetLevel(logLevel));
2536
2537 exit:
2538 return error;
2539 }
2540 #endif // OPENTHREAD_CONFIG_LOG_LEVEL_DYNAMIC_ENABLE
2541
HandlePropertySet(void)2542 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_DEBUG_LOG_TIMESTAMP_BASE>(void)
2543 {
2544 uint64_t timestampBase = 0;
2545 otError error = OT_ERROR_NONE;
2546 uint32_t currentTime = otPlatAlarmMilliGetNow();
2547
2548 SuccessOrExit(error = mDecoder.ReadUint64(timestampBase));
2549 VerifyOrExit(timestampBase >= currentTime, error = OT_ERROR_INVALID_ARGS);
2550
2551 mLogTimestampBase = timestampBase - currentTime;
2552
2553 exit:
2554 return error;
2555 }
2556
HandlePropertyGet(void)2557 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_DEBUG_LOG_TIMESTAMP_BASE>(void)
2558 {
2559 return mEncoder.WriteUint64(mLogTimestampBase);
2560 }
2561
HandlePropertyGet(void)2562 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_CHAN_SUPPORTED>(void)
2563 {
2564 #if OPENTHREAD_RADIO
2565 return EncodeChannelMask(otPlatRadioGetSupportedChannelMask(mInstance));
2566 #else
2567 return EncodeChannelMask(otLinkGetSupportedChannelMask(mInstance));
2568 #endif // OPENTHREAD_RADIO
2569 }
2570
HandlePropertyGet(void)2571 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_PHY_CHAN_PREFERRED>(void)
2572 {
2573 return EncodeChannelMask(otPlatRadioGetPreferredChannelMask(mInstance));
2574 }
2575
2576 #if OPENTHREAD_CONFIG_PLATFORM_RADIO_COEX_ENABLE
HandlePropertySet(void)2577 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_RADIO_COEX_ENABLE>(void)
2578 {
2579 bool enabled;
2580 otError error = OT_ERROR_NONE;
2581
2582 SuccessOrExit(error = mDecoder.ReadBool(enabled));
2583 error = otPlatRadioSetCoexEnabled(mInstance, enabled);
2584
2585 exit:
2586 return error;
2587 }
2588
HandlePropertyGet(void)2589 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_RADIO_COEX_ENABLE>(void)
2590 {
2591 return mEncoder.WriteBool(otPlatRadioIsCoexEnabled(mInstance));
2592 }
2593
HandlePropertyGet(void)2594 template <> otError NcpBase::HandlePropertyGet<SPINEL_PROP_RADIO_COEX_METRICS>(void)
2595 {
2596 otRadioCoexMetrics coexMetrics;
2597 otError error = otPlatRadioGetCoexMetrics(mInstance, &coexMetrics);
2598
2599 if (error != OT_ERROR_NONE)
2600 {
2601 error = mEncoder.OverwriteWithLastStatusError(ThreadErrorToSpinelStatus(error));
2602 ExitNow();
2603 }
2604
2605 // Encode Tx Request related metrics
2606 SuccessOrExit(error = mEncoder.OpenStruct());
2607 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxRequest));
2608 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxGrantImmediate));
2609 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxGrantWait));
2610 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxGrantWaitActivated));
2611 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxGrantWaitTimeout));
2612 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxGrantDeactivatedDuringRequest));
2613 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumTxDelayedGrant));
2614 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mAvgTxRequestToGrantTime));
2615 SuccessOrExit(error = mEncoder.CloseStruct());
2616
2617 // Encode Rx Request related metrics
2618 SuccessOrExit(error = mEncoder.OpenStruct());
2619 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxRequest));
2620 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantImmediate));
2621 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantWait));
2622 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantWaitActivated));
2623 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantWaitTimeout));
2624 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantDeactivatedDuringRequest));
2625 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxDelayedGrant));
2626 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mAvgRxRequestToGrantTime));
2627 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumRxGrantNone));
2628 SuccessOrExit(error = mEncoder.CloseStruct());
2629
2630 // Encode common metrics
2631 SuccessOrExit(error = mEncoder.WriteBool(coexMetrics.mStopped));
2632 SuccessOrExit(error = mEncoder.WriteUint32(coexMetrics.mNumGrantGlitch));
2633
2634 exit:
2635 return error;
2636 }
2637 #endif
2638
2639 #if OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE || OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
DecodeLinkMetrics(otLinkMetrics * aMetrics,bool aAllowPduCount)2640 otError NcpBase::DecodeLinkMetrics(otLinkMetrics *aMetrics, bool aAllowPduCount)
2641 {
2642 otError error = OT_ERROR_NONE;
2643 uint8_t metrics = 0;
2644
2645 SuccessOrExit(error = mDecoder.ReadUint8(metrics));
2646
2647 if (metrics & SPINEL_THREAD_LINK_METRIC_PDU_COUNT)
2648 {
2649 VerifyOrExit(aAllowPduCount, error = OT_ERROR_INVALID_ARGS);
2650 aMetrics->mPduCount = true;
2651 }
2652
2653 if (metrics & SPINEL_THREAD_LINK_METRIC_LQI)
2654 {
2655 aMetrics->mLqi = true;
2656 }
2657
2658 if (metrics & SPINEL_THREAD_LINK_METRIC_LINK_MARGIN)
2659 {
2660 aMetrics->mLinkMargin = true;
2661 }
2662
2663 if (metrics & SPINEL_THREAD_LINK_METRIC_RSSI)
2664 {
2665 aMetrics->mRssi = true;
2666 }
2667
2668 exit:
2669 return error;
2670 }
2671 #endif
2672
2673 #if OPENTHREAD_CONFIG_PLATFORM_POWER_CALIBRATION_ENABLE
HandlePropertySet(void)2674 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_CHAN_TARGET_POWER>(void)
2675 {
2676 otError error;
2677 uint8_t channel;
2678 int16_t targetPower;
2679
2680 SuccessOrExit(error = mDecoder.ReadUint8(channel));
2681 SuccessOrExit(error = mDecoder.ReadInt16(targetPower));
2682 error = otPlatRadioSetChannelTargetPower(mInstance, channel, targetPower);
2683
2684 exit:
2685 return error;
2686 }
2687
HandlePropertyInsert(void)2688 template <> otError NcpBase::HandlePropertyInsert<SPINEL_PROP_PHY_CALIBRATED_POWER>(void)
2689 {
2690 otError error;
2691 uint8_t channel;
2692 int16_t actualPower;
2693 const uint8_t *dataPtr;
2694 uint16_t dataLen;
2695
2696 SuccessOrExit(error = mDecoder.ReadUint8(channel));
2697 SuccessOrExit(error = mDecoder.ReadInt16(actualPower));
2698 SuccessOrExit(error = mDecoder.ReadDataWithLen(dataPtr, dataLen));
2699 error = otPlatRadioAddCalibratedPower(mInstance, channel, actualPower, dataPtr, dataLen);
2700
2701 exit:
2702 return error;
2703 }
2704
HandlePropertySet(void)2705 template <> otError NcpBase::HandlePropertySet<SPINEL_PROP_PHY_CALIBRATED_POWER>(void)
2706 {
2707 return otPlatRadioClearCalibratedPowers(mInstance);
2708 }
2709 #endif // OPENTHREAD_CONFIG_PLATFORM_POWER_CALIBRATION_ENABLE
2710
2711 } // namespace Ncp
2712 } // namespace ot
2713
2714 // ----------------------------------------------------------------------------
2715 // MARK: Peek/Poke delegate API
2716 // ----------------------------------------------------------------------------
2717
2718 #if OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
otNcpRegisterPeekPoke(otNcpDelegateAllowPeekPoke aAllowPeekDelegate,otNcpDelegateAllowPeekPoke aAllowPokeDelegate)2719 void otNcpRegisterPeekPoke(otNcpDelegateAllowPeekPoke aAllowPeekDelegate, otNcpDelegateAllowPeekPoke aAllowPokeDelegate)
2720 {
2721 ot::Ncp::NcpBase *ncp = ot::Ncp::NcpBase::GetNcpInstance();
2722
2723 if (ncp != nullptr)
2724 {
2725 ncp->RegisterPeekPokeDelegates(aAllowPeekDelegate, aAllowPokeDelegate);
2726 }
2727 }
2728 #endif // OPENTHREAD_CONFIG_NCP_ENABLE_PEEK_POKE
2729
2730 // ----------------------------------------------------------------------------
2731 // MARK: Virtual Datastream I/O (Public API)
2732 // ----------------------------------------------------------------------------
2733
otNcpStreamWrite(int aStreamId,const uint8_t * aDataPtr,int aDataLen)2734 otError otNcpStreamWrite(int aStreamId, const uint8_t *aDataPtr, int aDataLen)
2735 {
2736 otError error = OT_ERROR_INVALID_STATE;
2737 ot::Ncp::NcpBase *ncp = ot::Ncp::NcpBase::GetNcpInstance();
2738
2739 if (ncp != nullptr)
2740 {
2741 error = ncp->StreamWrite(aStreamId, aDataPtr, aDataLen);
2742 }
2743
2744 return error;
2745 }
2746
2747 #if (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP)
2748
otPlatLog(otLogLevel aLogLevel,otLogRegion aLogRegion,const char * aFormat,...)2749 extern "C" void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...)
2750 {
2751 va_list args;
2752 char logString[OPENTHREAD_CONFIG_NCP_SPINEL_LOG_MAX_SIZE];
2753 ot::Ncp::NcpBase *ncp = ot::Ncp::NcpBase::GetNcpInstance();
2754
2755 va_start(args, aFormat);
2756
2757 if (vsnprintf(logString, sizeof(logString), aFormat, args) > 0)
2758 {
2759 if (ncp != nullptr)
2760 {
2761 ncp->Log(aLogLevel, aLogRegion, logString);
2762 }
2763 }
2764
2765 va_end(args);
2766 }
2767
2768 #endif // (OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP)
2769