-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathGenericThreadStackManagerImpl_OpenThread.hpp
More file actions
1876 lines (1551 loc) · 71 KB
/
GenericThreadStackManagerImpl_OpenThread.hpp
File metadata and controls
1876 lines (1551 loc) · 71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020-2022 Project CHIP Authors
* Copyright (c) 2019 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Contains non-inline method definitions for the
* GenericThreadStackManagerImpl_OpenThread<> template.
*/
#ifndef GENERIC_THREAD_STACK_MANAGER_IMPL_OPENTHREAD_IPP
#define GENERIC_THREAD_STACK_MANAGER_IMPL_OPENTHREAD_IPP
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#include <cassert>
#include <openthread/dataset.h>
#include <openthread/joiner.h>
#include <openthread/link.h>
#include <openthread/netdata.h>
#include <openthread/tasklet.h>
#include <openthread/thread.h>
#include <openthread/udp.h>
#if CHIP_DEVICE_CONFIG_THREAD_FTD
#include <openthread/dataset_ftd.h>
#include <openthread/thread_ftd.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_MESHCOP
#include <openthread/seeker.h>
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT
#include <openthread/srp_client.h>
#endif
#include <lib/core/CHIPEncoding.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/FixedBufferAllocator.h>
#include <lib/support/ThreadDiscoveryCode.h>
#include <lib/support/ThreadOperationalDataset.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CommissionableDataProvider.h>
#include <platform/DiagnosticDataProvider.h>
#include <platform/OpenThread/GenericNetworkCommissioningThreadDriver.h>
#include <platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h>
#include <platform/OpenThread/OpenThreadUtils.h>
#include <platform/ThreadStackManager.h>
extern "C" void otSysProcessDrivers(otInstance * aInstance);
#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI
extern "C" void otAppCliInit(otInstance * aInstance);
#endif
namespace chip {
namespace DeviceLayer {
namespace Internal {
static_assert(OPENTHREAD_API_VERSION >= 219, "OpenThread version too old");
namespace {
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_DNS_CLIENT
CHIP_ERROR ReadDomainNameComponent(const char *& in, char * out, size_t outSize)
{
const char * dotPos = strchr(in, '.');
VerifyOrReturnError(dotPos != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
const size_t componentSize = static_cast<size_t>(dotPos - in);
VerifyOrReturnError(componentSize < outSize, CHIP_ERROR_INVALID_ARGUMENT);
memcpy(out, in, componentSize);
out[componentSize] = '\0';
in += componentSize + 1;
return CHIP_NO_ERROR;
}
template <size_t N>
CHIP_ERROR ReadDomainNameComponent(const char *& in, char (&out)[N])
{
return ReadDomainNameComponent(in, out, N);
}
#endif
NetworkCommissioning::otScanResponseIterator<NetworkCommissioning::ThreadScanResponse> mScanResponseIter;
} // namespace
/**
* Called by OpenThread to alert the ThreadStackManager of a change in the state of the Thread stack.
*
* By default, applications never need to call this method directly. However, applications that
* wish to receive OpenThread state change call-backs directly from OpenThread (e.g. by calling
* otSetStateChangedCallback() with their own callback function) can call this method to pass
* state change events to the ThreadStackManager.
*/
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::OnOpenThreadStateChange(uint32_t flags, void * context)
{
ChipDeviceEvent event{ .Type = DeviceEventType::kThreadStateChange,
.ThreadStateChange = {
.RoleChanged = (flags & OT_CHANGED_THREAD_ROLE) != 0,
.AddressChanged = (flags & (OT_CHANGED_IP6_ADDRESS_ADDED | OT_CHANGED_IP6_ADDRESS_REMOVED)) != 0,
.NetDataChanged = (flags & OT_CHANGED_THREAD_NETDATA) != 0,
.ChildNodesChanged =
(flags & (OT_CHANGED_THREAD_CHILD_ADDED | OT_CHANGED_THREAD_CHILD_REMOVED)) != 0,
.OpenThread = { .Flags = flags } } };
CHIP_ERROR status = PlatformMgr().PostEvent(&event);
if (status != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "Failed to post Thread state change: %" CHIP_ERROR_FORMAT, status.Format());
}
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([]() { ThreadStackMgrImpl()._UpdateNetworkStatus(); });
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_ProcessThreadActivity()
{
otTaskletsProcess(mOTInst);
otSysProcessDrivers(mOTInst);
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::_HaveRouteToAddress(const Inet::IPAddress & destAddr)
{
VerifyOrReturnValue(mOTInst, false);
bool res = false;
// Lock OpenThread
Impl()->LockThreadStack();
// No routing of IPv4 over Thread.
VerifyOrExit(!destAddr.IsIPv4(), res = false);
// If the device is attached to a Thread network...
if (IsThreadAttachedNoLock())
{
// Link-local addresses are always presumed to be routable, provided the device is attached.
if (destAddr.IsIPv6LinkLocal())
{
ExitNow(res = true);
}
// Iterate over the routes known to the OpenThread stack looking for a route that covers the
// destination address. If found, consider the address routable.
// Ignore any routes advertised by this device.
// If the destination address is a ULA, ignore default routes. Border routers advertising
// default routes are not expected to be capable of routing CHIP fabric ULAs unless they
// advertise those routes specifically.
{
otError otErr;
otNetworkDataIterator routeIter = OT_NETWORK_DATA_ITERATOR_INIT;
otExternalRouteConfig routeConfig;
const bool destIsULA = destAddr.IsIPv6ULA();
while ((otErr = otNetDataGetNextRoute(Impl()->OTInstance(), &routeIter, &routeConfig)) == OT_ERROR_NONE)
{
const Inet::IPPrefix prefix = ToIPPrefix(routeConfig.mPrefix);
char addrStr[64];
prefix.IPAddr.ToString(addrStr);
if (!routeConfig.mNextHopIsThisDevice && (!destIsULA || routeConfig.mPrefix.mLength > 0) &&
ToIPPrefix(routeConfig.mPrefix).MatchAddress(destAddr))
{
ExitNow(res = true);
}
}
}
}
exit:
// Unlock OpenThread
Impl()->UnlockThreadStack();
return res;
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_OnPlatformEvent(const ChipDeviceEvent * event)
{
if (event->Type == DeviceEventType::kThreadStateChange)
{
bool isThreadAttached = Impl()->_IsThreadAttached();
// Avoid sending muliple events if the attachement state didn't change (Child->router or disable->Detached)
if (event->ThreadStateChange.RoleChanged && (isThreadAttached != mIsAttached))
{
ChipDeviceEvent attachEvent{ .Type = DeviceEventType::kThreadConnectivityChange,
.ThreadConnectivityChange = { .Result = (isThreadAttached) ? kConnectivity_Established
: kConnectivity_Lost } };
CHIP_ERROR status = PlatformMgr().PostEvent(&attachEvent);
if (status == CHIP_NO_ERROR)
{
mIsAttached = isThreadAttached;
}
else
{
ChipLogError(DeviceLayer, "Failed to post Thread connectivity change: %" CHIP_ERROR_FORMAT, status.Format());
}
ThreadDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetThreadDiagnosticsDelegate();
if (delegate)
{
if (mIsAttached)
{
delegate->OnConnectionStatusChanged(app::Clusters::ThreadNetworkDiagnostics::ConnectionStatusEnum::kConnected);
// Remove kLinkDown fault if it was set, as the device is now connected.
GeneralFaults<kMaxNetworkFaults> current = mNetworkFaults;
if (current.remove(to_underlying(chip::app::Clusters::ThreadNetworkDiagnostics::NetworkFaultEnum::kLinkDown)) ==
CHIP_NO_ERROR)
{
delegate->OnNetworkFaultChanged(mNetworkFaults, current);
mNetworkFaults = current;
}
}
else
{
delegate->OnConnectionStatusChanged(
app::Clusters::ThreadNetworkDiagnostics::ConnectionStatusEnum::kNotConnected);
GeneralFaults<kMaxNetworkFaults> current;
TEMPORARY_RETURN_IGNORED current.add(
to_underlying(chip::app::Clusters::ThreadNetworkDiagnostics::NetworkFaultEnum::kLinkDown));
delegate->OnNetworkFaultChanged(mNetworkFaults, current);
mNetworkFaults = current;
}
}
}
#if CHIP_DETAIL_LOGGING
Impl()->LockThreadStack();
LogOpenThreadStateChange(mOTInst, event->ThreadStateChange.OpenThread.Flags);
Impl()->UnlockThreadStack();
#endif // CHIP_DETAIL_LOGGING
}
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::_IsThreadEnabled()
{
VerifyOrReturnValue(mOTInst, false);
otDeviceRole curRole;
Impl()->LockThreadStack();
curRole = otThreadGetDeviceRole(mOTInst);
Impl()->UnlockThreadStack();
return (curRole != OT_DEVICE_ROLE_DISABLED);
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_SetThreadEnabled(bool val)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
otError otErr = OT_ERROR_NONE;
Impl()->LockThreadStack();
bool isEnabled = (otThreadGetDeviceRole(mOTInst) != OT_DEVICE_ROLE_DISABLED);
bool isIp6Enabled = otIp6IsEnabled(mOTInst);
if (val && !isIp6Enabled)
{
otErr = otIp6SetEnabled(mOTInst, val);
VerifyOrExit(otErr == OT_ERROR_NONE, );
}
if (val != isEnabled)
{
otErr = otThreadSetEnabled(mOTInst, val);
VerifyOrExit(otErr == OT_ERROR_NONE, );
}
if (!val && isIp6Enabled)
{
otErr = otIp6SetEnabled(mOTInst, val);
VerifyOrExit(otErr == OT_ERROR_NONE, );
}
exit:
Impl()->UnlockThreadStack();
return MapOpenThreadError(otErr);
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_SetThreadProvision(ByteSpan netInfo)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
otError otErr = OT_ERROR_FAILED;
otOperationalDatasetTlvs tlvs;
assert(netInfo.size() <= Thread::kSizeOperationalDataset);
tlvs.mLength = static_cast<uint8_t>(netInfo.size());
memcpy(tlvs.mTlvs, netInfo.data(), netInfo.size());
// Set the dataset as the active dataset for the node.
Impl()->LockThreadStack();
otErr = otDatasetSetActiveTlvs(mOTInst, &tlvs);
Impl()->UnlockThreadStack();
if (otErr != OT_ERROR_NONE)
{
return MapOpenThreadError(otErr);
}
// post an event alerting other subsystems about change in provisioning state
ChipDeviceEvent event{ .Type = DeviceEventType::kServiceProvisioningChange,
.ServiceProvisioningChange = { .IsServiceProvisioned = true } };
return PlatformMgr().PostEvent(&event);
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::_IsThreadProvisioned()
{
VerifyOrReturnValue(mOTInst, false);
bool provisioned;
Impl()->LockThreadStack();
provisioned = otDatasetIsCommissioned(mOTInst);
Impl()->UnlockThreadStack();
return provisioned;
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_GetThreadProvision(Thread::OperationalDataset & dataset)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(Impl()->IsThreadProvisioned(), CHIP_ERROR_INCORRECT_STATE);
otOperationalDatasetTlvs datasetTlv;
Impl()->LockThreadStack();
otError otErr = otDatasetGetActiveTlvs(mOTInst, &datasetTlv);
Impl()->UnlockThreadStack();
if (otErr != OT_ERROR_NONE)
{
return MapOpenThreadError(otErr);
}
ReturnErrorOnFailure(dataset.Init(ByteSpan(datasetTlv.mTlvs, datasetTlv.mLength)));
return CHIP_NO_ERROR;
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::_IsThreadAttached()
{
VerifyOrReturnValue(mOTInst, false);
otDeviceRole curRole;
Impl()->LockThreadStack();
curRole = otThreadGetDeviceRole(mOTInst);
Impl()->UnlockThreadStack();
return (curRole != OT_DEVICE_ROLE_DISABLED && curRole != OT_DEVICE_ROLE_DETACHED);
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_AttachToThreadNetwork(
const Thread::OperationalDataset & dataset, NetworkCommissioning::Internal::WirelessDriver::ConnectCallback * callback)
{
Thread::OperationalDataset current_dataset;
// Validate the dataset change with the current state
TEMPORARY_RETURN_IGNORED ThreadStackMgrImpl().GetThreadProvision(current_dataset);
if (dataset.AsByteSpan().data_equal(current_dataset.AsByteSpan()) && callback == nullptr)
{
return CHIP_NO_ERROR;
}
// Reset the previously set callback since it will never be called in case incorrect dataset was supplied.
mpConnectCallback = nullptr;
#if defined(CONFIG_CHIP_OPENTHREAD_NETWORK_SWITCH_PATH) && CONFIG_CHIP_OPENTHREAD_NETWORK_SWITCH_PATH
if (callback == nullptr && dataset.IsCommissioned() && current_dataset.IsCommissioned() &&
!dataset.AsByteSpan().data_equal(current_dataset.AsByteSpan()) && Impl()->IsThreadEnabled())
{
ReturnErrorOnFailure(Impl()->SetThreadProvision(dataset.AsByteSpan()));
mpConnectCallback = callback;
return CHIP_NO_ERROR;
}
#endif
ReturnErrorOnFailure(Impl()->SetThreadEnabled(false));
ReturnErrorOnFailure(Impl()->SetThreadProvision(dataset.AsByteSpan()));
if (dataset.IsCommissioned())
{
ReturnErrorOnFailure(Impl()->SetThreadEnabled(true));
mpConnectCallback = callback;
}
return CHIP_NO_ERROR;
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_OnThreadAttachFinished()
{
if (mpConnectCallback != nullptr)
{
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this]() {
VerifyOrReturn(mpConnectCallback != nullptr);
mpConnectCallback->OnResult(NetworkCommissioning::Status::kSuccess, CharSpan(), 0);
mpConnectCallback = nullptr;
});
}
}
template <class ImplClass>
CHIP_ERROR
GenericThreadStackManagerImpl_OpenThread<ImplClass>::_StartThreadScan(NetworkCommissioning::ThreadDriver::ScanCallback * callback)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR error = CHIP_NO_ERROR;
#if CHIP_CONFIG_ENABLE_ICD_SERVER
otLinkModeConfig linkMode;
#endif
// If there is another ongoing scan request, reject the new one.
VerifyOrReturnError(mpScanCallback == nullptr, CHIP_ERROR_INCORRECT_STATE);
mpScanCallback = callback;
Impl()->LockThreadStack();
// Ensure that IPv6 interface is up when MLE Discovery is performed.
if (!otIp6IsEnabled(mOTInst))
{
SuccessOrExit(error = MapOpenThreadError(otIp6SetEnabled(mOTInst, true)));
}
#if CHIP_CONFIG_ENABLE_ICD_SERVER
// Thread network discovery makes Sleepy End Devices detach from a network, so temporarily disable the SED mode.
linkMode = otThreadGetLinkMode(mOTInst);
if (!linkMode.mRxOnWhenIdle)
{
mTemporaryRxOnWhenIdle = true;
linkMode.mRxOnWhenIdle = true;
otThreadSetLinkMode(mOTInst, linkMode);
}
#endif
error = MapOpenThreadError(otThreadDiscover(mOTInst, 0, /* all channels */
OT_PANID_BROADCAST, false, false, /* disable PAN ID, EUI64 and Joiner filtering */
_OnNetworkScanFinished, this));
exit:
Impl()->UnlockThreadStack();
if (error != CHIP_NO_ERROR)
{
mpScanCallback = nullptr;
}
return error;
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_OnNetworkScanFinished(otActiveScanResult * aResult, void * aContext)
{
reinterpret_cast<GenericThreadStackManagerImpl_OpenThread *>(aContext)->_OnNetworkScanFinished(aResult);
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_OnNetworkScanFinished(otActiveScanResult * aResult)
{
if (aResult == nullptr) // scan completed
{
#if CHIP_CONFIG_ENABLE_ICD_SERVER
if (mTemporaryRxOnWhenIdle)
{
otLinkModeConfig linkMode = otThreadGetLinkMode(mOTInst);
linkMode.mRxOnWhenIdle = false;
mTemporaryRxOnWhenIdle = false;
otThreadSetLinkMode(mOTInst, linkMode);
}
#endif
// If Thread scanning was done before commissioning, turn off the IPv6 interface.
if (otThreadGetDeviceRole(mOTInst) == OT_DEVICE_ROLE_DISABLED && !otDatasetIsCommissioned(mOTInst))
{
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this]() {
Impl()->LockThreadStack();
auto err = otIp6SetEnabled(mOTInst, false);
if (err != OT_ERROR_NONE)
{
ChipLogProgress(DeviceLayer, "Failed to disable Thread IPv6: %s", otThreadErrorToString(err));
}
Impl()->UnlockThreadStack();
});
}
if (mpScanCallback != nullptr)
{
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this]() {
mpScanCallback->OnFinished(NetworkCommissioning::Status::kSuccess, CharSpan(), &mScanResponseIter);
mpScanCallback = nullptr;
});
}
}
else
{
ChipLogProgress(DeviceLayer, "Thread Network: %s Panid 0x%x Channel %u RSSI %d LQI %u Version %u", aResult->mNetworkName.m8,
aResult->mPanId, aResult->mChannel, aResult->mRssi, aResult->mLqi, aResult->mVersion);
NetworkCommissioning::ThreadScanResponse scanResponse = { 0 };
scanResponse.panId = aResult->mPanId; // why is scanResponse.panID 64b
scanResponse.channel = aResult->mChannel; // why is scanResponse.channel 16b
scanResponse.version = aResult->mVersion;
scanResponse.rssi = aResult->mRssi;
scanResponse.lqi = aResult->mLqi;
scanResponse.extendedAddress = Encoding::BigEndian::Get64(aResult->mExtAddress.m8);
scanResponse.extendedPanId = Encoding::BigEndian::Get64(aResult->mExtendedPanId.m8);
static_assert(OT_NETWORK_NAME_MAX_SIZE <= UINT8_MAX, "Network name length won't fit");
scanResponse.networkNameLen = static_cast<uint8_t>(strnlen(aResult->mNetworkName.m8, OT_NETWORK_NAME_MAX_SIZE));
memcpy(scanResponse.networkName, aResult->mNetworkName.m8, scanResponse.networkNameLen);
mScanResponseIter.Add(&scanResponse);
}
}
template <class ImplClass>
ConnectivityManager::ThreadDeviceType GenericThreadStackManagerImpl_OpenThread<ImplClass>::_GetThreadDeviceType()
{
VerifyOrReturnValue(mOTInst, ConnectivityManager::kThreadDeviceType_NotSupported);
ConnectivityManager::ThreadDeviceType deviceType;
Impl()->LockThreadStack();
const otLinkModeConfig linkMode = otThreadGetLinkMode(mOTInst);
#if CHIP_DEVICE_CONFIG_THREAD_FTD
if (linkMode.mDeviceType && otThreadIsRouterEligible(mOTInst))
ExitNow(deviceType = ConnectivityManager::kThreadDeviceType_Router);
if (linkMode.mDeviceType)
ExitNow(deviceType = ConnectivityManager::kThreadDeviceType_FullEndDevice);
#endif
if (linkMode.mRxOnWhenIdle)
ExitNow(deviceType = ConnectivityManager::kThreadDeviceType_MinimalEndDevice);
#if CHIP_DEVICE_CONFIG_THREAD_SSED
#if OPENTHREAD_API_VERSION >= 347
if (otLinkGetCslPeriod(mOTInst) != 0)
#else
if (otLinkCslGetPeriod(mOTInst) != 0)
#endif // OPENTHREAD_API_VERSION
ExitNow(deviceType = ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice);
#endif // CHIP_DEVICE_CONFIG_THREAD_SSED
ExitNow(deviceType = ConnectivityManager::kThreadDeviceType_SleepyEndDevice);
exit:
Impl()->UnlockThreadStack();
return deviceType;
}
template <class ImplClass>
CHIP_ERROR
GenericThreadStackManagerImpl_OpenThread<ImplClass>::_SetThreadDeviceType(ConnectivityManager::ThreadDeviceType deviceType)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
otError error = OT_ERROR_NONE;
otLinkModeConfig linkMode;
switch (deviceType)
{
#if CHIP_DEVICE_CONFIG_THREAD_FTD
case ConnectivityManager::kThreadDeviceType_Router:
case ConnectivityManager::kThreadDeviceType_FullEndDevice:
#endif
case ConnectivityManager::kThreadDeviceType_MinimalEndDevice:
case ConnectivityManager::kThreadDeviceType_SleepyEndDevice:
#if CHIP_DEVICE_CONFIG_THREAD_SSED
case ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice:
#endif
break;
default:
ExitNow(error = OT_ERROR_INVALID_ARGS);
}
#if CHIP_PROGRESS_LOGGING
{
const char * deviceTypeStr;
switch (deviceType)
{
case ConnectivityManager::kThreadDeviceType_Router:
deviceTypeStr = "ROUTER";
break;
case ConnectivityManager::kThreadDeviceType_FullEndDevice:
deviceTypeStr = "FULL END DEVICE";
break;
case ConnectivityManager::kThreadDeviceType_MinimalEndDevice:
deviceTypeStr = "MINIMAL END DEVICE";
break;
case ConnectivityManager::kThreadDeviceType_SleepyEndDevice:
deviceTypeStr = "SLEEPY END DEVICE";
break;
#if CHIP_DEVICE_CONFIG_THREAD_SSED
case ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice:
deviceTypeStr = "SYNCHRONIZED SLEEPY END DEVICE";
break;
#endif
default:
deviceTypeStr = "(unknown)";
break;
}
ChipLogProgress(DeviceLayer, "Setting OpenThread device type to %s", deviceTypeStr);
}
#endif // CHIP_PROGRESS_LOGGING
Impl()->LockThreadStack();
linkMode = otThreadGetLinkMode(mOTInst);
switch (deviceType)
{
#if CHIP_DEVICE_CONFIG_THREAD_FTD
case ConnectivityManager::kThreadDeviceType_Router:
case ConnectivityManager::kThreadDeviceType_FullEndDevice:
linkMode.mDeviceType = true;
linkMode.mRxOnWhenIdle = true;
// This is expected to succeed for FTDs.
error = otThreadSetRouterEligible(mOTInst, deviceType == ConnectivityManager::kThreadDeviceType_Router);
break;
#endif
case ConnectivityManager::kThreadDeviceType_MinimalEndDevice:
linkMode.mDeviceType = false;
linkMode.mRxOnWhenIdle = true;
break;
case ConnectivityManager::kThreadDeviceType_SleepyEndDevice:
case ConnectivityManager::kThreadDeviceType_SynchronizedSleepyEndDevice:
linkMode.mDeviceType = false;
linkMode.mRxOnWhenIdle = false;
break;
default:
break;
}
#if CHIP_DEVICE_CONFIG_THREAD_FTD
if (error == OT_ERROR_NONE)
#endif
{
error = otThreadSetLinkMode(mOTInst, linkMode);
}
Impl()->UnlockThreadStack();
exit:
return MapOpenThreadError(error);
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_GetPrimary802154MACAddress(uint8_t * buf)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
const otExtAddress * extendedAddr = otLinkGetExtendedAddress(mOTInst);
memcpy(buf, extendedAddr, sizeof(otExtAddress));
return CHIP_NO_ERROR;
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_GetThreadVersion(uint16_t & version)
{
version = otThreadGetVersion();
return CHIP_NO_ERROR;
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_ResetThreadNetworkDiagnosticsCounts()
{
// Based on the spec, only OverrunCount should be resetted.
mOverrunCount = 0;
}
/**
* @brief Helper that sets callbacks for OpenThread state changes and configures the Thread stack.
* Assigns mOTInst to an instance, and configures the OT stack on a device by setting state change callbacks enabling features
* for IPv6 address configuration, enabling the Thread network if necessary, and handling SRP if enabled.
* Allows for the configuration of the Thread stack on a device where the instance and the otCLI are already initialised.
*
* @param otInst Pointer to the OT instance
* @return CHIP_ERROR OpenThread error mapped to CHIP_ERROR
*/
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::ConfigureThreadStack(otInstance * otInst)
{
CHIP_ERROR err = CHIP_NO_ERROR;
otError otErr = OT_ERROR_NONE;
mOTInst = otInst;
// Arrange for OpenThread to call the OnOpenThreadStateChange method whenever a
// state change occurs. Note that we reference the OnOpenThreadStateChange method
// on the concrete implementation class so that that class can override the default
// method implementation if it chooses to.
otErr = otSetStateChangedCallback(otInst, ImplClass::OnOpenThreadStateChange, mOTInst);
VerifyOrExit(otErr == OT_ERROR_NONE, err = MapOpenThreadError(otErr));
// Enable automatic assignment of Thread advertised addresses.
#if defined(OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE) && OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE
otIp6SetSlaacEnabled(otInst, true);
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT
otSrpClientSetCallback(mOTInst, &OnSrpClientNotification, nullptr);
otSrpClientEnableAutoStartMode(mOTInst, &OnSrpClientStateChange, nullptr);
memset(&mSrpClient, 0, sizeof(mSrpClient));
#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_AUTOSTART
// If the Thread stack has been provisioned, but is not currently enabled, enable it now.
if (otThreadGetDeviceRole(mOTInst) == OT_DEVICE_ROLE_DISABLED && otDatasetIsCommissioned(otInst))
{
// Enable the Thread IPv6 interface.
otErr = otIp6SetEnabled(otInst, true);
VerifyOrExit(otErr == OT_ERROR_NONE, err = MapOpenThreadError(otErr));
otErr = otThreadSetEnabled(otInst, true);
VerifyOrExit(otErr == OT_ERROR_NONE, err = MapOpenThreadError(otErr));
ChipLogProgress(DeviceLayer, "OpenThread ifconfig up and thread start");
}
#endif
exit:
ChipLogProgress(DeviceLayer, "OpenThread started: %s", otThreadErrorToString(otErr));
return err;
}
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::DoInit(otInstance * otInst)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Arrange for OpenThread errors to be translated to text.
RegisterOpenThreadErrorFormatter();
mOTInst = NULL;
// If an OpenThread instance hasn't been supplied, call otInstanceInitSingle() to
// create or acquire a singleton instance of OpenThread.
if (otInst == NULL)
{
otInst = otInstanceInitSingle();
VerifyOrExit(otInst != NULL, err = MapOpenThreadError(OT_ERROR_FAILED));
}
#if !defined(PW_RPC_ENABLED) && CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI
otAppCliInit(otInst);
#endif
err = ConfigureThreadStack(otInst);
exit:
return err;
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::IsThreadAttachedNoLock()
{
otDeviceRole curRole = otThreadGetDeviceRole(mOTInst);
return (curRole != OT_DEVICE_ROLE_DISABLED && curRole != OT_DEVICE_ROLE_DETACHED);
}
template <class ImplClass>
bool GenericThreadStackManagerImpl_OpenThread<ImplClass>::IsThreadInterfaceUpNoLock()
{
return otIp6IsEnabled(mOTInst);
}
#if CHIP_CONFIG_ENABLE_ICD_SERVER
template <class ImplClass>
CHIP_ERROR GenericThreadStackManagerImpl_OpenThread<ImplClass>::_SetPollingInterval(System::Clock::Milliseconds32 pollingInterval)
{
VerifyOrReturnError(mOTInst, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR err = CHIP_NO_ERROR;
Impl()->LockThreadStack();
// For Thread devices, the intervals are defined as:
// * poll period for SED devices that poll the parent for data
// * CSL period for SSED devices that listen for messages in scheduled time slots.
#if CHIP_DEVICE_CONFIG_THREAD_SSED
#if OPENTHREAD_API_VERSION >= 347
// Get CSL period in units of us and divide by 1000 to get milliseconds.
uint32_t curIntervalMS = otLinkGetCslPeriod(mOTInst) / 1000;
#else
// Get CSL period in units of 10 symbols, convert it to microseconds and divide by 1000 to get milliseconds.
uint32_t curIntervalMS = otLinkCslGetPeriod(mOTInst) * OT_US_PER_TEN_SYMBOLS / 1000;
#endif // OPENTHREAD_API_VERSION
#else
uint32_t curIntervalMS = otLinkGetPollPeriod(mOTInst);
#endif
otError otErr = OT_ERROR_NONE;
if (pollingInterval.count() != curIntervalMS)
{
#if CHIP_DEVICE_CONFIG_THREAD_SSED
#if OPENTHREAD_API_VERSION >= 347
// Set CSL period in units of us and divide by 1000 to get milliseconds.
otErr = otLinkSetCslPeriod(mOTInst, pollingInterval.count() * 1000);
curIntervalMS = otLinkGetCslPeriod(mOTInst) / 1000;
#else
// Set CSL period in units of 10 symbols, convert it to microseconds and divide by 1000 to get milliseconds.
otErr = otLinkCslSetPeriod(mOTInst, pollingInterval.count() * 1000 / OT_US_PER_TEN_SYMBOLS);
curIntervalMS = otLinkCslGetPeriod(mOTInst) * OT_US_PER_TEN_SYMBOLS / 1000;
#endif // OPENTHREAD_API_VERSION
#else
otErr = otLinkSetPollPeriod(mOTInst, pollingInterval.count());
curIntervalMS = otLinkGetPollPeriod(mOTInst);
#endif
err = MapOpenThreadError(otErr);
}
Impl()->UnlockThreadStack();
if (otErr != OT_ERROR_NONE)
{
ChipLogError(DeviceLayer, "Failed to set SED interval to %" PRId32 "ms. Defaulting to %" PRId32 "ms",
pollingInterval.count(), curIntervalMS);
}
return err;
}
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_ErasePersistentInfo()
{
VerifyOrReturn(mOTInst);
ChipLogProgress(DeviceLayer, "Erasing Thread persistent info...");
Impl()->LockThreadStack();
std::ignore = otThreadSetEnabled(mOTInst, false);
std::ignore = otIp6SetEnabled(mOTInst, false);
std::ignore = otInstanceErasePersistentInfo(mOTInst);
if (mpCommissioningDriver)
{
mpCommissioningDriver->ClearNetwork();
}
Impl()->UnlockThreadStack();
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_MESHCOP
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_RendezvousStop()
{
otSeekerStop(mOTInst);
_CancelRendezvousAnnouncement();
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::_CancelRendezvousAnnouncement()
{
DeviceLayer::SystemLayer().CancelTimer(_HandleRendezvousRetransmissionTimer, this);
mRendezvousRetransmissionCount = 0;
}
template <class ImplClass>
CHIP_ERROR
GenericThreadStackManagerImpl_OpenThread<ImplClass>::_RendezvousStart(RendezvousAnnouncementRequestCallback announcementRequest,
void * context)
{
CHIP_ERROR error = CHIP_NO_ERROR;
Impl()->LockThreadStack();
VerifyOrExit(otThreadGetDeviceRole(mOTInst) == OT_DEVICE_ROLE_DISABLED, error = MapOpenThreadError(OT_ERROR_INVALID_STATE));
VerifyOrExit(!otSeekerIsRunning(mOTInst), error = MapOpenThreadError(OT_ERROR_BUSY));
if (!otIp6IsEnabled(mOTInst))
{
SuccessOrExit(error = MapOpenThreadError(otIp6SetEnabled(mOTInst, true)));
}
_CancelRendezvousAnnouncement();
mRendezvousAnnouncementRequestCallback = announcementRequest;
mRendezvousAnnouncementRequestContext = context;
SuccessOrExit(error = MapOpenThreadError(otSeekerSetUdpPort(mOTInst, CHIP_PORT)));
SuccessOrExit(error = MapOpenThreadError(otSeekerStart(mOTInst, _HandleSeekerScanEvaluator, this)));
exit:
Impl()->UnlockThreadStack();
ChipLogProgress(DeviceLayer, "Rendezvous start: %s", chip::ErrorStr(error));
return error;
}
template <class ImplClass>
otSeekerVerdict GenericThreadStackManagerImpl_OpenThread<ImplClass>::_HandleSeekerScanEvaluator(void * aContext,
const otSeekerScanResult * aResult)
{
auto * self = static_cast<GenericThreadStackManagerImpl_OpenThread *>(aContext);
if (aResult == nullptr)
{
self->TryNextNetwork();
return OT_SEEKER_ACCEPT;
}
{
uint16_t discriminator;
if (DeviceLayer::GetCommissionableDataProvider()->GetSetupDiscriminator(discriminator) != CHIP_NO_ERROR)
{
return OT_SEEKER_IGNORE;
}
Thread::DiscoveryCode code(discriminator);
otJoinerDiscerner discerner;
discerner.mValue = code.AsUInt64();
discerner.mLength = 64;
if (otSteeringDataContainsDiscerner(&aResult->mSteeringData, &discerner))
{
return OT_SEEKER_ACCEPT_PREFERRED;
}
discerner.mValue = code.AsUInt64Short();
discerner.mLength = 64;
if (otSteeringDataContainsDiscerner(&aResult->mSteeringData, &discerner))
{
return OT_SEEKER_ACCEPT;
}
}
return OT_SEEKER_IGNORE;
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::TryNextNetwork()
{
otSockAddr targetAddr;
if (otSeekerSetUpNextConnection(mOTInst, &targetAddr) == OT_ERROR_NONE)
{
mRendezvousPeerAddr =
chip::Transport::PeerAddress::UDP(ToIPAddress(targetAddr.mAddress), targetAddr.mPort, Inet::InterfaceId::Null());
DeviceLayer::SystemLayer().ScheduleLambda([this]() { SendRendezvousAnnouncement(); });
}
else if (otSeekerIsRunning(mOTInst))
{
otSeekerStop(mOTInst);
auto err = MapOpenThreadError(otSeekerStart(mOTInst, _HandleSeekerScanEvaluator, this));
ChipLogProgress(DeviceLayer, "Restart rendezvous: %s", chip::ErrorStr(err));
}
}
template <class ImplClass>
void GenericThreadStackManagerImpl_OpenThread<ImplClass>::SendRendezvousAnnouncement()
{
CHIP_ERROR err = CHIP_NO_ERROR;
if (mRendezvousAnnouncementRequestCallback != nullptr)
{
err = mRendezvousAnnouncementRequestCallback(mRendezvousAnnouncementRequestContext, mRendezvousPeerAddr);
}
if (err == CHIP_NO_ERROR)
{
mRendezvousRetransmissionCount++;
if (mRendezvousRetransmissionCount < kMaxRendezvousRetransmissions)
{
const uint32_t kRendezvousRetransmissionIntervalMs = 1250;
ChipLogProgress(DeviceLayer, "Try the current Thread network #%u", mRendezvousRetransmissionCount);
DeviceLayer::SystemLayer().StartTimer(System::Clock::Milliseconds32(kRendezvousRetransmissionIntervalMs),
_HandleRendezvousRetransmissionTimer, this);
}
else
{
ChipLogProgress(DeviceLayer, "Give up the current Thread network!");