Repository navigation
Expand file tree
/
Copy pathWifiInterfaceImpl.cpp
More file actions
1311 lines (1086 loc) · 53.1 KB
/
Copy pathWifiInterfaceImpl.cpp
File metadata and controls
1311 lines (1086 loc) · 53.1 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) 2023 Project CHIP Authors
*
* 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.
*/
#if (SL_MATTER_GN_BUILD == 0)
#include "sl_matter_wifi_config.h"
#endif // SL_MATTER_GN_BUILD
#include "SlNetConfig.h"
#if defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
#include "ble_config.h"
#endif // defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
#include "sl_status.h"
#include "sl_wifi_device.h"
#include <algorithm>
#include <app/icd/server/ICDServerConfig.h>
#include <cmsis_os2.h>
#include <inet/IPAddress.h>
#include <inet/InetConfig.h>
#if SL_INET_CONFIG_UDP_LWIP_QUEUE_UNTIL_NETIF_READY
#include <inet/UDPEndPointImplLwIP.h>
// TODO: Remove nogncheck once we have a proper way to include this file.
#include <platform/CHIPDeviceLayer.h> // nogncheck
#endif // SL_INET_CONFIG_UDP_LWIP_QUEUE_UNTIL_NETIF_READY
#include <lib/support/CHIPMem.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/NetworkCommissioning.h>
#include <platform/silabs/wifi/SiWx/WifiInterfaceImpl.h>
#include <sl_cmsis_os2_common.h>
extern "C" {
#include "sl_si91x_driver.h"
#include "sl_si91x_host_interface.h"
#include "sl_si91x_types.h"
#include "sl_utility.h"
#include "sl_wifi.h"
#include "sl_wifi_callback_framework.h"
#include "sl_wifi_constants.h"
#include "sl_wifi_types.h"
#if SL_MBEDTLS_USE_TINYCRYPT
#include "sl_si91x_constants.h"
#include "sl_si91x_trng.h"
#else
#include <psa/crypto.h>
#endif // SL_MBEDTLS_USE_TINYCRYPT
#include <sl_net.h>
#include <sl_net_constants.h>
#include <sl_net_for_lwip.h>
#include <sl_net_wifi_types.h>
}
#if SLI_SI91X_MCU_INTERFACE
#include "rsi_wisemcu_hardware_setup.h"
#endif // SLI_SI91X_MCU_INTERFACE
#if (EXP_BOARD)
#if defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
#include "rsi_bt_common_apis.h"
#endif // defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
#include "sl_board_configuration.h"
#endif
#if CHIP_CONFIG_ENABLE_ICD_SERVER
#include <app/icd/server/ICDConfigurationData.h> // nogncheck
#include <platform/silabs/wifi/icd/WifiSleepManager.h> // nogncheck
#if SLI_SI91X_MCU_INTERFACE // SoC Only
#include "rsi_rom_power_save.h"
#include "sl_gpio_board.h"
#include "sl_si91x_driver_gpio.h"
#include "sl_si91x_power_manager.h"
#endif // SLI_SI91X_MCU_INTERFACE
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
using namespace chip::DeviceLayer::Internal;
using namespace chip::DeviceLayer::Silabs;
using namespace chip::app::Clusters::NetworkCommissioning;
// TODO: This needs to be refactored so we don't need the global object
WfxRsi_t wfx_rsi;
namespace {
osThreadId_t sWlanThread;
constexpr uint32_t kWlanTaskSize = 2048;
uint8_t wlanStack[kWlanTaskSize];
osThread_t sWlanTaskControlBlock;
constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi",
.attr_bits = osThreadDetached,
.cb_mem = &sWlanTaskControlBlock,
.cb_size = osThreadCbSize,
.stack_mem = wlanStack,
.stack_size = kWlanTaskSize,
.priority = osPriorityAboveNormal7 };
#if CHIP_CONFIG_ENABLE_ICD_SERVER
constexpr uint32_t kTimeToFullBeaconReception = 5000; // 5 seconds
constexpr char kMatterMdnsIpv6McastAddress[] = "ff02::fb";
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
wfx_wifi_scan_ext_t temp_reset;
osSemaphoreId_t sScanCompleteSemaphore;
osMutexId_t sScanInProgressSemaphore;
osMessageQueueId_t sWifiEventQueue = nullptr;
sl_net_wifi_lwip_context_t wifi_client_context;
sl_wifi_security_t security = SL_WIFI_SECURITY_UNKNOWN;
constexpr int8_t kAdvScanThreshold = -40;
constexpr uint8_t kAdvRssiToleranceThreshold = 5;
constexpr uint8_t kAdvActiveScanDuration = 15;
constexpr uint8_t kAdvPassiveScanDuration = 110;
constexpr uint8_t kAdvMultiProbe = 1;
constexpr uint8_t kAdvScanPeriodicity = 10;
constexpr uint8_t kAdvEnableInstantbgScan = 1;
// TODO: Confirm that this value works for size and timing
constexpr uint8_t kWfxQueueSize = 10;
// TODO: Figure out why we actually need this, we are already handling failure and retries somewhere else.
constexpr uint16_t kWifiScanTimeoutTicks = 10000;
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Settle delay before scan and between scan/join so the NWP can return to power save.
// Neutral-less switch products requirement is to stay within 30 mA over any 250 ms window.
constexpr uint32_t kNeutralLessSwitchSettleDelayMs = 250;
// Time after the last received packet before the NWP enters sleep (ASSOCIATED_POWER_SAVE_LOW_LATENCY).
// Shorter than the SDK default (50 ms) to meet the neutral-less switch power budget.
constexpr uint8_t kWifiMonitorIntervalMs = 30;
#endif // SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Convert sl_wifi_security_t to Matter WiFiSecurityBitmap flags
static chip::BitFlags<WiFiSecurityBitmap> ConvertSlWifiSecurityToBitmap(const sl_wifi_security_t security)
{
chip::BitFlags<WiFiSecurityBitmap> flags;
switch (security)
{
case SL_WIFI_OPEN:
flags.Set(WiFiSecurityBitmap::kUnencrypted);
break;
case SL_WIFI_WEP:
flags.Set(WiFiSecurityBitmap::kWep);
break;
case SL_WIFI_WPA:
case SL_WIFI_WPA_ENTERPRISE:
flags.Set(WiFiSecurityBitmap::kWpaPersonal);
break;
case SL_WIFI_WPA2:
case SL_WIFI_WPA2_ENTERPRISE:
flags.Set(WiFiSecurityBitmap::kWpa2Personal);
break;
case SL_WIFI_WPA_WPA2_MIXED:
flags.Set(WiFiSecurityBitmap::kWpaPersonal).Set(WiFiSecurityBitmap::kWpa2Personal);
break;
case SL_WIFI_WPA3_TRANSITION:
case SL_WIFI_WPA3_TRANSITION_ENTERPRISE:
flags.Set(WiFiSecurityBitmap::kWpa2Personal).Set(WiFiSecurityBitmap::kWpa3Personal);
break;
case SL_WIFI_WPA3:
case SL_WIFI_WPA3_ENTERPRISE:
flags.Set(WiFiSecurityBitmap::kWpa3Personal);
break;
default:
break;
}
return flags;
}
/**
* @brief Network Scan callback when the device receive a scan operation from the controller.
* This callback is used whe the Network Commission Driver send a ScanNetworks command.
*
* If the scan network was requested for a specific SSID - wfx_rsi.scan_ssid had a valid value,
* the callback will only forward that specific networks information.
* If no ssid is provided, wfx_rsi.scan_ssid is a nullptr, we return the information of all scanned networks.
*/
sl_status_t BackgroundScanCallback(sl_wifi_event_t event, sl_wifi_scan_result_t * result, uint32_t result_length, void * arg)
{
VerifyOrReturnError(result != nullptr, SL_STATUS_NULL_POINTER);
VerifyOrReturnError(wfx_rsi.scan_cb != nullptr, SL_STATUS_INVALID_HANDLE);
chip::ByteSpan requestedSsidSpan = {};
// arg is set to requested SSID if provided in sl_wifi_set_scan_callback
if (arg != nullptr)
{
sl_wifi_ssid_t * requestedSsidPtr = static_cast<sl_wifi_ssid_t *>(arg);
requestedSsidSpan = chip::ByteSpan(requestedSsidPtr->value, requestedSsidPtr->length);
}
uint32_t nbreResults = result->scan_count;
for (uint32_t i = 0; i < nbreResults; i++)
{
// Length excludes null-character
size_t ssidLen = strnlen(reinterpret_cast<char *>(result->scan_info[i].ssid), kMaxWiFiSSIDLength);
chip::ByteSpan ssidSpan(result->scan_info[i].ssid, ssidLen);
if (requestedSsidSpan.empty() || requestedSsidSpan.data_equal(ssidSpan))
{
// Create a new scan response for the current scan result
chip::DeviceLayer::NetworkCommissioning::WiFiScanResponse currentScanResult = {};
// Copy the scanned SSID to the scan response
chip::MutableByteSpan responseSsidSpan(currentScanResult.ssid, kMaxWiFiSSIDLength);
VerifyOrReturnError(chip::CopySpanToMutableSpan(ssidSpan, responseSsidSpan) == CHIP_NO_ERROR,
SL_STATUS_SI91X_MEMORY_IS_NOT_SUFFICIENT);
currentScanResult.ssidLen = static_cast<uint8_t>(ssidLen);
// Copy the BSSID to the scan response
chip::ByteSpan bssidSpan(result->scan_info[i].bssid, kWiFiBSSIDLength);
chip::MutableByteSpan responseBssidSpan(currentScanResult.bssid, kWiFiBSSIDLength);
VerifyOrReturnError(chip::CopySpanToMutableSpan(bssidSpan, responseBssidSpan) == CHIP_NO_ERROR,
SL_STATUS_SI91X_MEMORY_IS_NOT_SUFFICIENT);
// Convert the RSSI to a int8_t value
int16_t rssi = std::clamp(((-1) * result->scan_info[i].rssi_val), INT8_MIN, INT8_MAX);
currentScanResult.signal.strength = static_cast<int8_t>(rssi);
currentScanResult.signal.type = chip::DeviceLayer::NetworkCommissioning::WirelessSignalType::kdBm;
currentScanResult.channel = static_cast<uint16_t>(result->scan_info[i].rf_channel);
currentScanResult.wiFiBand = WiFiBandEnum::k2g4;
currentScanResult.security =
ConvertSlWifiSecurityToBitmap(static_cast<sl_wifi_security_t>(result->scan_info[i].security_mode));
wfx_rsi.scan_cb(¤tScanResult);
}
}
// null callback to indicate that the scan is complete
wfx_rsi.scan_cb(nullptr);
wfx_rsi.scan_cb = nullptr;
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kScanStarted);
osSemaphoreRelease(sScanCompleteSemaphore);
return SL_STATUS_OK;
}
sl_status_t SiWxPlatformInit(void)
{
sl_status_t status = SL_STATUS_OK;
#ifdef SLI_SI91X_MCU_INTERFACE
// SoC Configurations
uint8_t xtal_enable = 1;
status = sl_si91x_m4_ta_secure_handshake(SL_SI91X_ENABLE_XTAL, 1, &xtal_enable, 0, nullptr);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_si91x_m4_ta_secure_handshake failed: 0x%lx", static_cast<uint32_t>(status)));
#endif // SLI_SI91X_MCU_INTERFACE
sl_wifi_firmware_version_t version = { 0 };
status = sl_wifi_get_firmware_version(&version);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_wifi_get_firmware_version failed: 0x%lx", static_cast<uint32_t>(status)));
ChipLogDetail(DeviceLayer, "Firmware version is: %x%x.%d.%d.%d.%d.%d.%d", version.chip_id, version.rom_id, version.major,
version.minor, version.security_version, version.patch_num, version.customer_id, version.build_num);
status = sl_wifi_get_mac_address(SL_WIFI_CLIENT_INTERFACE, reinterpret_cast<sl_mac_address_t *>(wfx_rsi.sta_mac.data()));
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_wifi_get_mac_address failed: 0x%lx", static_cast<uint32_t>(status)));
#ifdef SL_MBEDTLS_USE_TINYCRYPT
constexpr uint32_t trngKey[TRNG_KEY_SIZE] = { 0x16157E2B, 0xA6D2AE28, 0x8815F7AB, 0x3C4FCF09 };
// To check the Entropy of TRNG and verify TRNG functioning.
status = sl_si91x_trng_entropy();
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_si91x_trng_entropy failed: 0x%lx", static_cast<uint32_t>(status)));
// Initiate and program the key required for TRNG hardware engine
status = sl_si91x_trng_program_key((uint32_t *) trngKey, TRNG_KEY_SIZE);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_si91x_trng_program_key failed: 0x%lx", static_cast<uint32_t>(status)));
#endif // SL_MBEDTLS_USE_TINYCRYPT
wfx_rsi.dev_state.Set(WifiInterface::WifiState::kStationInit);
return status;
}
sl_status_t ScanCallback(sl_wifi_event_t event, sl_wifi_scan_result_t * scan_result, uint32_t result_length, void * arg)
{
sl_status_t status = SL_STATUS_OK;
if (SL_WIFI_CHECK_IF_EVENT_FAILED(event))
{
if (scan_result != nullptr)
{
status = *reinterpret_cast<sl_status_t *>(scan_result);
ChipLogError(DeviceLayer, "ScanCallback: failed: 0x%lx", status);
}
// SET FALLBACK VALUES FOR THE SCAN
wfx_rsi.ap_chan = SL_WIFI_AUTO_CHANNEL;
security = SL_WIFI_WPA3_TRANSITION;
}
else
{
security = static_cast<sl_wifi_security_t>(scan_result->scan_info[0].security_mode);
wfx_rsi.ap_chan = scan_result->scan_info[0].rf_channel;
wfx_rsi.credentials.security = ConvertSlWifiSecurityToBitmap(security);
chip::MutableByteSpan bssidSpan(wfx_rsi.ap_bssid.data(), kWiFiBSSIDLength);
chip::ByteSpan inBssid(scan_result->scan_info[0].bssid, kWiFiBSSIDLength);
TEMPORARY_RETURN_IGNORED chip::CopySpanToMutableSpan(inBssid, bssidSpan);
}
osSemaphoreRelease(sScanCompleteSemaphore);
return status;
}
sl_status_t InitiateScan()
{
sl_status_t status = SL_STATUS_OK;
sl_wifi_ssid_t ssid = { 0 };
sl_wifi_scan_configuration_t wifi_scan_configuration = default_wifi_scan_configuration;
ssid.length = wfx_rsi.credentials.ssidLen;
chip::ByteSpan requestedSsidSpan(wfx_rsi.credentials.ssid, wfx_rsi.credentials.ssidLen);
chip::MutableByteSpan ssidSpan(ssid.value, ssid.length);
TEMPORARY_RETURN_IGNORED chip::CopySpanToMutableSpan(requestedSsidSpan, ssidSpan);
sl_wifi_set_scan_callback(ScanCallback, NULL);
osMutexAcquire(sScanInProgressSemaphore, osWaitForever);
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Allow power-save state to settle before starting the scan.
osDelay(kNeutralLessSwitchSettleDelayMs);
#endif // defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// This is an odd success code?
status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, &ssid, &wifi_scan_configuration);
if (status == SL_STATUS_IN_PROGRESS)
{
osSemaphoreAcquire(sScanCompleteSemaphore, kWifiScanTimeoutTicks);
status = SL_STATUS_OK;
}
osMutexRelease(sScanInProgressSemaphore);
VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogProgress(DeviceLayer, "sl_wifi_start_scan failed: 0x%lx", status));
return status;
}
sl_status_t SetWifiConfigurations()
{
sl_status_t status = SL_STATUS_OK;
uint8_t join_feature_bitmap = SL_SI91X_JOIN_FEAT_LISTEN_INTERVAL_VALID; // initialize with default value
#if CHIP_CONFIG_ENABLE_ICD_SERVER
sl_wifi_listen_interval_v2_t sleep_interval = {
.listen_interval = chip::ICDConfigurationData::GetInstance().GetSlowPollingInterval().count()
};
status = sl_wifi_set_listen_interval_v2(SL_WIFI_CLIENT_INTERFACE, sleep_interval);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_wifi_set_listen_interval_v2 failed: 0x%lx", status));
// This is be triggered on the disconnect use case, providing the amount of TA tries
// Setting the TA retry to 1 and giving the control to the M4 for improved power efficiency
// When max_retry_attempts is set to 0, TA will retry indefinitely.
sl_wifi_advanced_client_configuration_t client_config = { .max_retry_attempts = 1 };
status = sl_wifi_set_advanced_client_configuration(SL_WIFI_CLIENT_INTERFACE, &client_config);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_wifi_set_advanced_client_configuration failed: 0x%lx", status));
join_feature_bitmap |= SL_SI91X_JOIN_FEAT_PS_CMD_LISTEN_INTERVAL_VALID;
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
if (wfx_rsi.credentials.keyLen != 0)
{
status = sl_net_set_credential(SL_NET_DEFAULT_WIFI_CLIENT_CREDENTIAL_ID, SL_NET_WIFI_PSK, &wfx_rsi.credentials.key[0],
wfx_rsi.credentials.keyLen);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_net_set_credential failed: 0x%lx", status));
}
sl_net_wifi_client_profile_t profile = {
.config = {
.ssid = {
.value = { 0 },
// static cast because the types dont match
.length = static_cast<uint8_t>(wfx_rsi.credentials.ssidLen),
},
.channel = {
.channel = SL_WIFI_AUTO_CHANNEL,
.band = SL_WIFI_AUTO_BAND,
.bandwidth = SL_WIFI_AUTO_BANDWIDTH
},
.bssid = {{0}},
.bss_type = SL_WIFI_BSS_TYPE_INFRASTRUCTURE,
.security = security,
.encryption = SL_WIFI_DEFAULT_ENCRYPTION,
.client_options = SL_WIFI_JOIN_WITH_SCAN,
.credential_id = (security == SL_WIFI_OPEN) ? SL_NET_NO_CREDENTIAL_ID : SL_NET_DEFAULT_WIFI_CLIENT_CREDENTIAL_ID,
.channel_bitmap = {
.channel_bitmap_2_4 = SL_WIFI_DEFAULT_CHANNEL_BITMAP
},
},
.ip = {
#if defined(SL_MATTER_ENABLE_DUAL_STACK) && SL_MATTER_ENABLE_DUAL_STACK
.mode = SL_IP_MANAGEMENT_DHCP_IPV4_LINK_LOCAL_IPV6,
.type = static_cast<sl_ip_address_type_t>(SL_IPV4 | SL_IPV6),
#else
.mode = SL_IP_MANAGEMENT_DHCP,
.type = SL_IPV6,
#endif // defined(SL_MATTER_ENABLE_DUAL_STACK) && SL_MATTER_ENABLE_DUAL_STACK
.host_name = NULL,
.ip = {{{0}}},
}
};
chip::MutableByteSpan output(profile.config.ssid.value, kMaxWiFiSSIDLength);
chip::ByteSpan input(wfx_rsi.credentials.ssid, wfx_rsi.credentials.ssidLen);
TEMPORARY_RETURN_IGNORED chip::CopySpanToMutableSpan(input, output);
if (wfx_rsi.ap_chan != SL_WIFI_AUTO_CHANNEL)
{
// AP channel is known - This indicates that the network scan was done for a specific SSID.
// Providing the channel and BSSID in the profile avoids scanning all channels again.
profile.config.channel.channel = wfx_rsi.ap_chan;
profile.config.channel_bitmap.channel_bitmap_2_4 = (1UL << (wfx_rsi.ap_chan - 1));
chip::MutableByteSpan bssidSpan(profile.config.bssid.octet, kWiFiBSSIDLength);
chip::ByteSpan inBssid(wfx_rsi.ap_bssid.data(), kWiFiBSSIDLength);
TEMPORARY_RETURN_IGNORED chip::CopySpanToMutableSpan(inBssid, bssidSpan);
}
status = sl_wifi_set_join_configuration(SL_WIFI_CLIENT_INTERFACE, join_feature_bitmap);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "sl_wifi_set_join_configuration failed: 0x%lx", status));
status = sl_net_set_profile(SL_NET_WIFI_CLIENT_INTERFACE, SL_NET_DEFAULT_WIFI_CLIENT_PROFILE_ID, &profile);
VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_set_profile failed: 0x%lx", status));
return status;
}
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
/**
* @brief Applies the Matter neutral-less switch application profile.
*
* @return SL_STATUS_OK on success, or the sl_status_t error code from sl_net_set_application_profile on failure.
*/
sl_status_t ApplyNeutralLessSwitchProfile()
{
sl_status_t status =
sl_net_set_application_profile(SL_NET_WIFI_CLIENT_INTERFACE, SL_NET_APPLICATION_PROFILE_MATTER_NEUTRAL_LESS_SWITCH);
VerifyOrReturnError(status == SL_STATUS_OK, status,
ChipLogError(DeviceLayer, "Failed to set application profile: 0x%lx", static_cast<uint32_t>(status)));
return status;
}
#endif // SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
#if CHIP_CONFIG_ENABLE_ICD_SERVER
/**
* @brief Converts the Matter Power Save Configuration to the SiWx Power Save Configuration
*
* @param configuration Matter Power Save Configuration
*
* @return sl_wifi_system_performance_profile_t SiWx Power Save Configuration; Default value is High Performance
* kHighPerformance: HIGH_PERFORMANCE
* kConnectedSleep: ASSOCIATED_POWER_SAVE_LOW_LATENCY
* kDeepSleep: DEEP_SLEEP_WITH_RAM_RETENTION
*/
sl_wifi_system_performance_profile_t ConvertPowerSaveConfiguration(PowerSaveInterface::PowerSaveConfiguration configuration)
{
sl_wifi_system_performance_profile_t profile = HIGH_PERFORMANCE;
switch (configuration)
{
case PowerSaveInterface::PowerSaveConfiguration::kHighPerformance:
profile = HIGH_PERFORMANCE;
break;
case PowerSaveInterface::PowerSaveConfiguration::kConnectedSleep:
case PowerSaveInterface::PowerSaveConfiguration::kLIConnectedSleep:
profile = ASSOCIATED_POWER_SAVE_LOW_LATENCY;
break;
case PowerSaveInterface::PowerSaveConfiguration::kDeepSleep:
profile = DEEP_SLEEP_WITH_RAM_RETENTION;
break;
default:
break;
}
return profile;
}
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
} // namespace
namespace chip {
namespace DeviceLayer {
namespace Silabs {
WifiInterfaceImpl WifiInterfaceImpl::mInstance;
WifiInterface & WifiInterface::GetInstance()
{
return WifiInterfaceImpl::GetInstance();
}
void WifiInterfaceImpl::MatterWifiTask(void * arg)
{
(void) arg;
WifiPlatformEvent event;
sl_status_t status = SL_STATUS_OK;
status = SiWxPlatformInit();
VerifyOrReturn(status == SL_STATUS_OK,
ChipLogError(DeviceLayer, "MatterWifiTask: SiWxPlatformInit failed: 0x%lx", static_cast<uint32_t>(status)));
#if CHIP_CONFIG_ENABLE_ICD_SERVER
// Remove High performance request after the device is initialized
TEMPORARY_RETURN_IGNORED chip::DeviceLayer::Silabs::WifiSleepManager::GetInstance().RemoveHighPerformanceRequest();
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
WifiInterfaceImpl::GetInstance().NotifyWifiTaskInitialized();
ChipLogDetail(DeviceLayer, "MatterWifiTask: starting event loop");
for (;;)
{
if (osMessageQueueGet(sWifiEventQueue, &event, nullptr, osWaitForever) == osOK)
{
WifiInterfaceImpl::GetInstance().ProcessEvent(event);
}
else
{
ChipLogError(DeviceLayer, "MatterWifiTask: get event failed: 0x%lx", static_cast<uint32_t>(status));
}
}
}
CHIP_ERROR WifiInterfaceImpl::InitWiFiStack(void)
{
sl_status_t status = SL_STATUS_OK;
#if CHIP_CONFIG_ENABLE_ICD_SERVER
// Force the device to high performance mode during the init sequence.
TEMPORARY_RETURN_IGNORED chip::DeviceLayer::Silabs::WifiSleepManager::GetInstance().RequestHighPerformanceWithoutTransition();
#endif // CHIP_CONFIG_ENABLE_ICD_SERVER
// The device configuration must be fully built before sl_net_init, which consumes it.
sl_wifi_device_configuration_t deviceConfiguration = SLNetGetDeviceConfig();
status = sl_net_init(SL_NET_WIFI_CLIENT_INTERFACE, &deviceConfiguration, &wifi_client_context, nullptr);
VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status));
// Create Sempaphore for scan completion
sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr);
VerifyOrReturnError(sScanCompleteSemaphore != nullptr, CHIP_ERROR_NO_MEMORY);
// Create Semaphore for scan in-progress protection
sScanInProgressSemaphore = osMutexNew(nullptr);
VerifyOrReturnError(sScanInProgressSemaphore != nullptr, CHIP_ERROR_NO_MEMORY);
// Create the message queue
sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WifiPlatformEvent), nullptr);
VerifyOrReturnError(sWifiEventQueue != nullptr, CHIP_ERROR_NO_MEMORY);
#ifndef SL_MBEDTLS_USE_TINYCRYPT
// PSA Crypto initialization
VerifyOrReturnError(psa_crypto_init() == PSA_SUCCESS, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "psa_crypto_init failed: %lx", static_cast<uint32_t>(status)));
#endif // SL_MBEDTLS_USE_TINYCRYPT
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
status = ApplyNeutralLessSwitchProfile();
VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL);
#endif // SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
return CHIP_NO_ERROR;
}
void WifiInterfaceImpl::ProcessEvent(WifiPlatformEvent event)
{
switch (event)
{
case WifiPlatformEvent::kStationConnect:
ChipLogDetail(DeviceLayer, "WifiPlatformEvent::kStationConnect");
wfx_rsi.dev_state.Set(WifiInterface::WifiState::kStationConnected);
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kStationConnecting);
ResetConnectivityNotificationFlags();
break;
case WifiPlatformEvent::kStationDisconnect: {
ChipLogDetail(DeviceLayer, "WifiPlatformEvent::kStationDisconnect");
TriggerPlatformWifiDisconnection();
ClearWifiDisconnectedState();
}
break;
case WifiPlatformEvent::kAPStart:
// TODO: Currently unimplemented
break;
case WifiPlatformEvent::kStationStartScan:
ChipLogDetail(DeviceLayer, "WifiPlatformEvent::kStationStartScan");
InitiateScan();
PostWifiPlatformEvent(WifiPlatformEvent::kStationStartJoin);
break;
case WifiPlatformEvent::kStationStartJoin:
ChipLogDetail(DeviceLayer, "WifiPlatformEvent::kStationStartJoin");
JoinWifiNetwork();
break;
case WifiPlatformEvent::kConnectionComplete:
ChipLogDetail(DeviceLayer, "WifiPlatformEvent::kConnectionComplete");
NotifySuccessfulConnection();
default:
break;
}
}
void WifiInterfaceImpl::NotifySuccessfulConnection(void)
{
struct netif * sta_netif = &wifi_client_context.netif;
VerifyOrReturn(sta_netif != nullptr, ChipLogError(DeviceLayer, "NotifySuccessfulConnection: failed to get STA netif"));
#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4)
GotIPv4Address((uint32_t) sta_netif->ip_addr.u_addr.ip4.addr);
#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */
char addrStr[chip::Inet::IPAddress::kMaxStringLength] = { 0 };
VerifyOrReturn(ip6addr_ntoa_r(netif_ip6_addr(sta_netif, 0), addrStr, sizeof(addrStr)) != nullptr);
ChipLogProgress(DeviceLayer, "SLAAC OK: linklocal addr: %s", addrStr);
NotifyIPv6Change(true);
NotifyConnectivity();
#if SL_INET_CONFIG_UDP_LWIP_QUEUE_UNTIL_NETIF_READY
{
CHIP_ERROR flushErr =
chip::DeviceLayer::SystemLayer().ScheduleLambda([]() { chip::Inet::UDPEndPointImplLwIP::FlushDeferredSendQueue(); });
if (flushErr != CHIP_NO_ERROR)
{
ChipLogError(DeviceLayer, "ScheduleLambda(FlushDeferredSendQueue) failed: %" CHIP_ERROR_FORMAT, flushErr.Format());
}
}
#endif // SL_INET_CONFIG_UDP_LWIP_QUEUE_UNTIL_NETIF_READY
}
sl_status_t WifiInterfaceImpl::JoinWifiNetwork(void)
{
VerifyOrReturnError(
!wfx_rsi.dev_state.HasAny(WifiInterface::WifiState::kStationConnecting, WifiInterface::WifiState::kStationConnected),
SL_STATUS_IN_PROGRESS);
sl_status_t status = SL_STATUS_OK;
// Start Join Network
wfx_rsi.dev_state.Set(WifiInterface::WifiState::kStationConnecting);
status = SetWifiConfigurations();
VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "Failure to set the Wifi Configurations!"));
status = sl_wifi_set_join_callback(JoinCallback, nullptr);
VerifyOrReturnError(status == SL_STATUS_OK, status);
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Ensure a delay between scan and join.
osDelay(kNeutralLessSwitchSettleDelayMs);
#endif // defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
status = sl_net_up(SL_NET_WIFI_CLIENT_INTERFACE, SL_NET_DEFAULT_WIFI_CLIENT_PROFILE_ID);
if (!(wfx_rsi.dev_state.Has(WifiInterface::WifiState::kStationConnecting)))
{
// TODO: Remove this check once the sl_net_up is fixed, sl_net_up is not completely synchronous
// and issue is mostly seen on OPEN access points
// sl_net_up can return SL_STATUS_SUCCESS, even if the join callback has been called
// If the state has changed, it means that the join callback has already been called
// rejoin already started, so we should not proceed with further processing
ChipLogDetail(DeviceLayer, "JoinCallback already called, skipping further processing");
status = SL_STATUS_FAIL;
}
if (status == SL_STATUS_OK)
{
WifiPlatformEvent event = WifiPlatformEvent::kStationConnect;
PostWifiPlatformEvent(event);
return status;
}
// failure only happens when the firmware returns an error
ChipLogError(DeviceLayer, "sl_net_up failed: 0x%lx", static_cast<uint32_t>(status));
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Re-apply after join failure.
TEMPORARY_RETURN_IGNORED ApplyNeutralLessSwitchProfile();
#endif // SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kStationConnecting).Clear(WifiInterface::WifiState::kStationConnected);
mLastDisconnectionReason = static_cast<uint16_t>(status);
WifiInterface::NotifyDisconnection(mLastDisconnectionReason);
return status;
}
sl_status_t WifiInterfaceImpl::JoinCallback(sl_wifi_event_t event, char * result, uint32_t resultLenght, void * arg)
{
sl_status_t status = SL_STATUS_OK;
// If the failed event is encountered when sl_net_up is in-progress,
// we ignore it and wait for the sl_net_up to complete.
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
// Re-apply the application profile after a join failure.
TEMPORARY_RETURN_IGNORED ApplyNeutralLessSwitchProfile();
#endif // SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
if (wfx_rsi.dev_state.Has(WifiInterface::WifiState::kStationConnecting))
{
wfx_rsi.dev_state.Clear(WifiState::kStationConnecting);
if (SL_WIFI_CHECK_IF_EVENT_FAILED(event))
{
// Returning SL_STATUS_IN_PROGRESS here is intentional: if a failed event is encountered while sl_net_up is still in
// progress, we do not want to report a final failure yet, as the connection process may still be ongoing and the final
// outcome will be determined once sl_net_up completes. This prevents premature error handling by higher layers.
return SL_STATUS_IN_PROGRESS;
}
}
if (SL_WIFI_CHECK_IF_EVENT_FAILED(event))
{
status = *reinterpret_cast<sl_status_t *>(result);
ChipLogError(DeviceLayer, "JoinCallback: failed: 0x%lx", status);
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kStationConnected);
uint16_t reason = static_cast<uint16_t>(status);
WifiInterfaceImpl & self = WifiInterfaceImpl::GetInstance();
self.mLastDisconnectionReason = reason;
self.NotifyDisconnection(self.mLastDisconnectionReason);
}
return status;
}
CHIP_ERROR WifiInterfaceImpl::GetAccessPointInfo(NetworkCommissioning::WiFiScanResponse & info)
{
// TODO: Convert this to a int8
int32_t rssi = 0;
// TODO: sl_wifi_get_wireless_info API is being deprecated with WiseConnect v4.0.x, we need to use the new API
// sl_wifi_get_interface_info after upgrading to WiseConnect v4.0.x
sl_si91x_rsp_wireless_info_t wireless_info = { 0 };
if (sl_wifi_get_wireless_info(&wireless_info) == SL_STATUS_OK)
{
size_t ssid_len = strnlen(reinterpret_cast<const char *>(wireless_info.ssid), kMaxWiFiSSIDLength);
VerifyOrReturnError(ssid_len <= kMaxWiFiSSIDLength, CHIP_ERROR_INVALID_STRING_LENGTH);
// Update wfx_rsi with values from sl_wifi_get_wireless_info
wfx_rsi.ap_chan = static_cast<uint16_t>(wireless_info.channel_number & 0xFF);
chip::ByteSpan bssidSrc(wireless_info.bssid, kWiFiBSSIDLength);
chip::MutableByteSpan bssidDst(wfx_rsi.ap_bssid.data(), kWiFiBSSIDLength);
ReturnErrorOnFailure(chip::CopySpanToMutableSpan(bssidSrc, bssidDst));
chip::ByteSpan ssidSrc(wireless_info.ssid, ssid_len);
chip::MutableByteSpan ssidDst(wfx_rsi.credentials.ssid, kMaxWiFiSSIDLength);
ReturnErrorOnFailure(chip::CopySpanToMutableSpan(ssidSrc, ssidDst));
wfx_rsi.credentials.ssidLen = static_cast<uint8_t>(ssid_len);
wfx_rsi.credentials.security = ConvertSlWifiSecurityToBitmap(static_cast<sl_wifi_security_t>(wireless_info.sec_type));
}
info.security = wfx_rsi.credentials.security;
info.channel = wfx_rsi.ap_chan;
info.wiFiBand = WiFiBandEnum::k2g4;
chip::MutableByteSpan output(info.ssid, kMaxWiFiSSIDLength);
chip::ByteSpan ssid(wfx_rsi.credentials.ssid, wfx_rsi.credentials.ssidLen);
ReturnErrorOnFailure(chip::CopySpanToMutableSpan(ssid, output));
info.ssidLen = static_cast<uint8_t>(output.size());
chip::ByteSpan apBssidSpan(wfx_rsi.ap_bssid.data(), wfx_rsi.ap_bssid.size());
chip::MutableByteSpan bssidSpan(info.bssid, kWiFiBSSIDLength);
ReturnErrorOnFailure(chip::CopySpanToMutableSpan(apBssidSpan, bssidSpan));
// TODO: add error processing
sl_wifi_get_signal_strength(SL_WIFI_CLIENT_INTERFACE, &(rssi));
info.signal.strength = static_cast<int8_t>(std::clamp(rssi, static_cast<int32_t>(INT8_MIN), static_cast<int32_t>(INT8_MAX)));
info.signal.type = NetworkCommissioning::WirelessSignalType::kdBm;
return CHIP_NO_ERROR;
}
CHIP_ERROR WifiInterfaceImpl::GetAccessPointExtendedInfo(wfx_wifi_scan_ext_t & info)
{
sl_wifi_statistics_t test = { 0 };
sl_status_t status = sl_wifi_get_statistics(SL_WIFI_CLIENT_INTERFACE, &test);
VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL);
info.beacon_lost_count = test.beacon_lost_count - temp_reset.beacon_lost_count;
info.beacon_rx_count = test.beacon_rx_count - temp_reset.beacon_rx_count;
info.mcast_rx_count = test.mcast_rx_count - temp_reset.mcast_rx_count;
info.mcast_tx_count = test.mcast_tx_count - temp_reset.mcast_tx_count;
info.ucast_rx_count = test.ucast_rx_count - temp_reset.ucast_rx_count;
info.ucast_tx_count = test.ucast_tx_count - temp_reset.ucast_tx_count;
info.overrun_count = test.overrun_count - temp_reset.overrun_count;
return CHIP_NO_ERROR;
}
CHIP_ERROR WifiInterfaceImpl::ResetCounters()
{
sl_wifi_statistics_t test = { 0 };
sl_status_t status = sl_wifi_get_statistics(SL_WIFI_CLIENT_INTERFACE, &test);
VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL);
temp_reset.beacon_lost_count = test.beacon_lost_count;
temp_reset.beacon_rx_count = test.beacon_rx_count;
temp_reset.mcast_rx_count = test.mcast_rx_count;
temp_reset.mcast_tx_count = test.mcast_tx_count;
temp_reset.ucast_rx_count = test.ucast_rx_count;
temp_reset.ucast_tx_count = test.ucast_tx_count;
temp_reset.overrun_count = test.overrun_count;
return CHIP_NO_ERROR;
}
void WifiInterfaceImpl::PostWifiPlatformEvent(WifiPlatformEvent event)
{
sl_status_t status = osMessageQueuePut(sWifiEventQueue, &event, 0, 0);
if (status != osOK)
{
ChipLogError(DeviceLayer, "PostWifiPlatformEvent: failed to post event with status: %ld", status);
// TODO: Handle error, requeue event depending on queue size or notify relevant task,
// Chipdie, etc.
}
}
sl_status_t WifiInterfaceImpl::TriggerPlatformWifiDisconnection()
{
sl_status_t status = sl_net_down(SL_NET_WIFI_CLIENT_INTERFACE);
VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_down failed: 0x%lx", status));
mLastDisconnectionReason = static_cast<uint16_t>(status);
WifiInterface::NotifyDisconnection(mLastDisconnectionReason);
return SL_STATUS_OK;
}
void WifiInterfaceImpl::ClearWifiDisconnectedState()
{
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kStationReady)
.Clear(WifiInterface::WifiState::kStationConnecting)
.Clear(WifiInterface::WifiState::kStationConnected);
ResetConnectivityNotificationFlags();
#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4)
NotifyIPv4Change(false);
#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */
NotifyIPv6Change(false);
}
#if CHIP_CONFIG_ENABLE_ICD_SERVER
#if defined(CHIP_CONFIG_ENABLE_ICD_LIT) && (CHIP_CONFIG_ENABLE_ICD_LIT == 1)
namespace {
osTimerId_t sLitPrecheckInReconnectTimer = nullptr;
constexpr uint32_t kLitPrecheckInMarginSeconds = 15;
void OnLitPrecheckInReconnectOsTimer(void *)
{
WifiInterfaceImpl & self = WifiInterfaceImpl::GetInstance();
VerifyOrReturn(self.IsWifiProvisioned() && !self.IsStationConnected());
ChipLogProgress(DeviceLayer, "LIT precheck-in: reconnecting Wi-Fi before ICD traffic");
VerifyOrReturn(self.ConfigureLITConnect() == CHIP_NO_ERROR, ChipLogError(DeviceLayer, "LIT precheck-in reconnect failed"));
}
} // namespace
CHIP_ERROR WifiInterfaceImpl::InitLitPrecheckInReconnectTimer()
{
VerifyOrReturnError(sLitPrecheckInReconnectTimer == nullptr, CHIP_NO_ERROR);
sLitPrecheckInReconnectTimer = osTimerNew(OnLitPrecheckInReconnectOsTimer, osTimerOnce, nullptr, nullptr);
VerifyOrReturnError(sLitPrecheckInReconnectTimer != nullptr, CHIP_ERROR_INTERNAL,
ChipLogDetail(DeviceLayer, "LIT precheck-in osTimerNew failed"));
return CHIP_NO_ERROR;
}
CHIP_ERROR WifiInterfaceImpl::ConfigureLITConnect()
{
VerifyOrReturnError(IsWifiProvisioned(), CHIP_NO_ERROR);
VerifyOrReturnError(!IsStationConnected(), CHIP_NO_ERROR);
if (!wfx_rsi.dev_state.Has(WifiInterface::WifiState::kStationConnecting))
{
return ConnectToAccessPoint();
}
return CHIP_NO_ERROR;
}
CHIP_ERROR WifiInterfaceImpl::ConfigureLITDisconnect()
{
CancelConnectionAttempt();
wfx_rsi.dev_state.Clear(WifiInterface::WifiState::kStationConnected);
TriggerPlatformWifiDisconnection();
return CHIP_NO_ERROR;
}
void WifiInterfaceImpl::CancelLitPrecheckInReconnectTimer()
{
VerifyOrReturn(sLitPrecheckInReconnectTimer != nullptr);
(void) osTimerStop(sLitPrecheckInReconnectTimer);
}
void WifiInterfaceImpl::StartLitPrecheckInReconnectTimer()
{
VerifyOrReturn(sLitPrecheckInReconnectTimer != nullptr);
const uint32_t idleSec = chip::ICDConfigurationData::GetInstance().GetModeBasedIdleModeDuration().count();
const uint32_t activeThresholdSec = chip::ICDConfigurationData::GetInstance().GetActiveModeThreshold().count() / 1000;
const uint32_t delaySec =
(idleSec > kLitPrecheckInMarginSeconds) ? (idleSec - activeThresholdSec - kLitPrecheckInMarginSeconds) : 1u;
const uint32_t delayMs = delaySec * 1000u;
(void) osTimerStop(sLitPrecheckInReconnectTimer);
if (osTimerStart(sLitPrecheckInReconnectTimer, pdMS_TO_TICKS(delayMs)) != osOK)
{
ChipLogDetail(DeviceLayer, "LIT precheck-in osTimerStart failed (delay ms=%u)", static_cast<unsigned>(delayMs));
}
}
#endif // defined(CHIP_CONFIG_ENABLE_ICD_LIT) && (CHIP_CONFIG_ENABLE_ICD_LIT == 1)
CHIP_ERROR WifiInterfaceImpl::ConfigurePowerSave(PowerSaveInterface::PowerSaveConfiguration configuration, uint32_t listenInterval)
{
// Power save configuration is already set, nothing to do
VerifyOrReturnValue(mCurrentPowerSaveConfiguration != configuration, CHIP_NO_ERROR);
#if defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
int32_t error = rsi_bt_power_save_profile(RSI_SLEEP_MODE_2, RSI_MAX_PSP);
VerifyOrReturnError(error == RSI_SUCCESS, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "rsi_bt_power_save_profile failed: %ld", error));
#endif // defined(SLI_SI91X_ENABLE_BLE) && SLI_SI91X_ENABLE_BLE
sl_wifi_performance_profile_v2_t wifi_profile = { .profile = ConvertPowerSaveConfiguration(configuration),
.dtim_aligned_type = SL_SI91X_ALIGN_WITH_BEACON,
.listen_interval = listenInterval };
#if defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
wifi_profile.monitor_interval = kWifiMonitorIntervalMs;
#endif // defined(SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI) && SL_MATTER_NEUTRAL_LESS_SWITCH_WIFI
sl_status_t status = sl_wifi_set_performance_profile_v2(&wifi_profile);
VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "sl_wifi_set_performance_profile_v2 failed: 0x%lx", status));
mCurrentPowerSaveConfiguration = configuration;
return CHIP_NO_ERROR;
}
CHIP_ERROR WifiInterfaceImpl::ConfigureBroadcastFilter(bool enableBroadcastFilter)
{
// Skip the underlying call if the filter is already in the requested state.
VerifyOrReturnValue(mBroadcastFilterEnabled != enableBroadcastFilter, CHIP_NO_ERROR);
sl_status_t status = sl_wifi_allowlist_mcast_remove_all();
VerifyOrReturnError(
status == SL_STATUS_OK, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "sl_wifi_allowlist_mcast_remove_all failed: 0x%" PRIx32, static_cast<uint32_t>(status)));
if (!enableBroadcastFilter)
{
// Filter disabled: allowlist Matter mDNS (ff02::fb) so only that multicast is received.
// Use sl_inet_pton6 so the address is in the endianness expected by the NWP.
sl_ip_address_t mdnsIpv6McastAddress = {};
uint8_t parsedAddress[SL_IPV6_ADDRESS_LENGTH] = {};
const int parseStatus =
sl_inet_pton6(kMatterMdnsIpv6McastAddress, kMatterMdnsIpv6McastAddress + sizeof(kMatterMdnsIpv6McastAddress) - 1,
parsedAddress, reinterpret_cast<unsigned int *>(mdnsIpv6McastAddress.ip.v6.value));
VerifyOrReturnError(parseStatus == 1, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "Failed to parse Matter mDNS IPv6 multicast address"));
mdnsIpv6McastAddress.type = SL_IPV6;
sl_ip_address_handle_t allowlistHandle = UINT8_MAX;
status = sl_wifi_allowlist_mcast_add_ip(&mdnsIpv6McastAddress, &allowlistHandle);
VerifyOrReturnError(
status == SL_STATUS_OK, CHIP_ERROR_INTERNAL,
ChipLogError(DeviceLayer, "sl_wifi_allowlist_mcast_add_ip failed: 0x%" PRIx32, static_cast<uint32_t>(status)));
}