This repository has been archived by the owner on Dec 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
/
NetworkProvisioningServerImpl.cpp
371 lines (305 loc) · 13.3 KB
/
NetworkProvisioningServerImpl.cpp
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
/*
*
* Copyright (c) 2018 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.
*/
#include <Weave/DeviceLayer/internal/WeaveDeviceLayerInternal.h>
#include <Weave/DeviceLayer/internal/NetworkProvisioningServer.h>
#include <Weave/DeviceLayer/internal/DeviceNetworkInfo.h>
#include <Weave/Core/WeaveTLV.h>
#include <Weave/Profiles/WeaveProfiles.h>
#include <Weave/Profiles/common/CommonProfile.h>
#include <Weave/DeviceLayer/ESP32/ESP32Utils.h>
#include <Weave/DeviceLayer/internal/GenericNetworkProvisioningServerImpl.ipp>
#include "esp_event.h"
#include "esp_wifi.h"
using namespace ::nl;
using namespace ::nl::Weave;
using namespace ::nl::Weave::TLV;
using namespace ::nl::Weave::Profiles::Common;
using namespace ::nl::Weave::Profiles::NetworkProvisioning;
using Profiles::kWeaveProfile_Common;
namespace nl {
namespace Weave {
namespace DeviceLayer {
namespace Internal {
NetworkProvisioningServerImpl NetworkProvisioningServerImpl::sInstance;
WEAVE_ERROR NetworkProvisioningServerImpl::_Init(void)
{
return GenericNetworkProvisioningServerImpl<NetworkProvisioningServerImpl>::DoInit();
}
void NetworkProvisioningServerImpl::_OnPlatformEvent(const WeaveDeviceEvent * event)
{
WEAVE_ERROR err;
// Handle ESP system events...
if (event->Type == DeviceEventType::kESPSystemEvent)
{
switch(event->Platform.ESPSystemEvent.event_id) {
case SYSTEM_EVENT_SCAN_DONE:
WeaveLogProgress(DeviceLayer, "SYSTEM_EVENT_SCAN_DONE");
HandleScanDone();
break;
default:
break;
}
}
// Handle a change in WiFi connectivity...
else if (event->Type == DeviceEventType::kWiFiConnectivityChange)
{
// Whenever WiFi connectivity is established, update the persisted WiFi
// station security type to match that used by the connected AP.
if (event->WiFiConnectivityChange.Result == kConnectivity_Established)
{
wifi_ap_record_t ap_info;
err = esp_wifi_sta_get_ap_info(&ap_info);
SuccessOrExit(err);
WiFiSecurityType secType = ESP32Utils::WiFiAuthModeToWeaveWiFiSecurityType(ap_info.authmode);
err = ConfigurationMgrImpl().UpdateWiFiStationSecurityType(secType);
SuccessOrExit(err);
}
}
// Propagate the event to the GenericNetworkProvisioningServerImpl<> base class so
// that it can take action on specific events.
GenericImplClass::_OnPlatformEvent(event);
exit:
return;
}
WEAVE_ERROR NetworkProvisioningServerImpl::GetWiFiStationProvision(NetworkInfo & netInfo, bool includeCredentials)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
wifi_config_t stationConfig;
netInfo.Reset();
err = esp_wifi_get_config(ESP_IF_WIFI_STA, &stationConfig);
SuccessOrExit(err);
VerifyOrExit(stationConfig.sta.ssid[0] != 0, err = WEAVE_ERROR_INCORRECT_STATE);
netInfo.NetworkId = kWiFiStationNetworkId;
netInfo.FieldPresent.NetworkId = true;
netInfo.NetworkType = kNetworkType_WiFi;
memcpy(netInfo.WiFiSSID, stationConfig.sta.ssid, min(strlen((char *)stationConfig.sta.ssid) + 1, sizeof(netInfo.WiFiSSID)));
netInfo.WiFiMode = kWiFiMode_Managed;
netInfo.WiFiRole = kWiFiRole_Station;
err = ConfigurationMgrImpl().GetWiFiStationSecurityType(netInfo.WiFiSecurityType);
if (err == WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
err = WEAVE_NO_ERROR;
}
SuccessOrExit(err);
if (includeCredentials)
{
netInfo.WiFiKeyLen = min(strlen((char *)stationConfig.sta.password), sizeof(netInfo.WiFiKey));
memcpy(netInfo.WiFiKey, stationConfig.sta.password, netInfo.WiFiKeyLen);
}
exit:
return err;
}
WEAVE_ERROR NetworkProvisioningServerImpl::SetWiFiStationProvision(const NetworkInfo & netInfo)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
wifi_config_t wifiConfig;
// Ensure that ESP station mode is enabled. This is required before esp_wifi_set_config(ESP_IF_WIFI_STA,...)
// can be called.
err = ESP32Utils::EnableStationMode();
SuccessOrExit(err);
// Initialize an ESP wifi_config_t structure based on the new provision information.
memset(&wifiConfig, 0, sizeof(wifiConfig));
memcpy(wifiConfig.sta.ssid, netInfo.WiFiSSID, min(strlen(netInfo.WiFiSSID) + 1, sizeof(wifiConfig.sta.ssid)));
memcpy(wifiConfig.sta.password, netInfo.WiFiKey, min((size_t)netInfo.WiFiKeyLen, sizeof(wifiConfig.sta.password)));
if (netInfo.WiFiSecurityType == kWiFiSecurityType_NotSpecified)
{
wifiConfig.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
}
else
{
wifiConfig.sta.scan_method = WIFI_FAST_SCAN;
wifiConfig.sta.threshold.rssi = 0;
switch (netInfo.WiFiSecurityType)
{
case kWiFiSecurityType_None:
wifiConfig.sta.threshold.authmode = WIFI_AUTH_OPEN;
break;
case kWiFiSecurityType_WEP:
wifiConfig.sta.threshold.authmode = WIFI_AUTH_WEP;
break;
case kWiFiSecurityType_WPAPersonal:
wifiConfig.sta.threshold.authmode = WIFI_AUTH_WPA_PSK;
break;
case kWiFiSecurityType_WPA2Personal:
wifiConfig.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
break;
case kWiFiSecurityType_WPA2Enterprise:
wifiConfig.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
break;
default:
ExitNow(err = WEAVE_ERROR_INVALID_ARGUMENT);
}
}
wifiConfig.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;
// Configure the ESP WiFi interface.
err = esp_wifi_set_config(ESP_IF_WIFI_STA, &wifiConfig);
if (err != ESP_OK)
{
WeaveLogError(DeviceLayer, "esp_wifi_set_config() failed: %s", nl::ErrorStr(err));
}
SuccessOrExit(err);
// Store the WiFi Station security type separately in NVS. This is necessary because the ESP wifi API
// does not provide a way to query the configured WiFi auth mode.
err = ConfigurationMgrImpl().UpdateWiFiStationSecurityType(netInfo.WiFiSecurityType);
SuccessOrExit(err);
WeaveLogProgress(DeviceLayer, "WiFi station provision set (SSID: %s)", netInfo.WiFiSSID);
exit:
return err;
}
WEAVE_ERROR NetworkProvisioningServerImpl::ClearWiFiStationProvision(void)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
wifi_config_t stationConfig;
// Clear the ESP WiFi station configuration.
memset(&stationConfig, 0, sizeof(stationConfig));
esp_wifi_set_config(ESP_IF_WIFI_STA, &stationConfig);
// Clear the persisted WiFi station security type.
ConfigurationMgrImpl().UpdateWiFiStationSecurityType(kWiFiSecurityType_NotSpecified);
return err;
}
WEAVE_ERROR NetworkProvisioningServerImpl::InitiateWiFiScan(void)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
wifi_scan_config_t scanConfig;
// Initiate an active scan using the default dwell times. Configure the scan to return hidden networks.
memset(&scanConfig, 0, sizeof(scanConfig));
scanConfig.show_hidden = 1;
scanConfig.scan_type = WIFI_SCAN_TYPE_ACTIVE;
err = esp_wifi_scan_start(&scanConfig, false);
SuccessOrExit(err);
#if WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
// Arm timer in case we never get the scan done event.
SystemLayer.StartTimer(WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT, HandleScanTimeOut, NULL);
#endif // WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
exit:
return err;
}
void NetworkProvisioningServerImpl::HandleScanDone()
{
WEAVE_ERROR err;
wifi_ap_record_t * scanResults = NULL;
uint16_t scanResultCount;
uint16_t encodedResultCount;
PacketBuffer * respBuf = NULL;
// If we receive a SCAN DONE event for a scan that we didn't initiate, simply ignore it.
VerifyOrExit(mState == kState_ScanNetworks_InProgress, err = WEAVE_NO_ERROR);
mState = kState_Idle;
#if WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
// Cancel the scan timeout timer.
SystemLayer.CancelTimer(HandleScanTimeOut, NULL);
#endif // WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
// Determine the number of scan results found.
err = esp_wifi_scan_get_ap_num(&scanResultCount);
SuccessOrExit(err);
// Only return up to WEAVE_DEVICE_CONFIG_MAX_SCAN_NETWORKS_RESULTS.
scanResultCount = min(scanResultCount, (uint16_t)WEAVE_DEVICE_CONFIG_MAX_SCAN_NETWORKS_RESULTS);
// Allocate a buffer to hold the scan results array.
scanResults = (wifi_ap_record_t *)malloc(scanResultCount * sizeof(wifi_ap_record_t));
VerifyOrExit(scanResults != NULL, err = WEAVE_ERROR_NO_MEMORY);
// Collect the scan results from the ESP WiFi driver. Note that this also *frees*
// the internal copy of the results.
err = esp_wifi_scan_get_ap_records(&scanResultCount, scanResults);
SuccessOrExit(err);
// If the ScanNetworks request is still outstanding...
if (GetCurrentOp() == kMsgType_ScanNetworks)
{
nl::Weave::TLV::TLVWriter writer;
TLVType outerContainerType;
// Sort results by rssi.
qsort(scanResults, scanResultCount, sizeof(*scanResults), ESP32Utils::OrderScanResultsByRSSI);
// Allocate a packet buffer to hold the encoded scan results.
respBuf = PacketBuffer::New(WEAVE_SYSTEM_CONFIG_HEADER_RESERVE_SIZE + 1);
VerifyOrExit(respBuf != NULL, err = WEAVE_ERROR_NO_MEMORY);
// Encode the list of scan results into the response buffer. If the encoded size of all
// the results exceeds the size of the buffer, encode only what will fit.
writer.Init(respBuf, respBuf->AvailableDataLength() - 1);
err = writer.StartContainer(AnonymousTag, kTLVType_Array, outerContainerType);
SuccessOrExit(err);
for (encodedResultCount = 0; encodedResultCount < scanResultCount; encodedResultCount++)
{
NetworkInfo netInfo;
const wifi_ap_record_t & scanResult = scanResults[encodedResultCount];
netInfo.Reset();
netInfo.NetworkType = kNetworkType_WiFi;
memcpy(netInfo.WiFiSSID, scanResult.ssid, min(strlen((char *)scanResult.ssid) + 1, (size_t)NetworkInfo::kMaxWiFiSSIDLength));
netInfo.WiFiSSID[NetworkInfo::kMaxWiFiSSIDLength] = 0;
netInfo.WiFiMode = kWiFiMode_Managed;
netInfo.WiFiRole = kWiFiRole_Station;
netInfo.WiFiSecurityType = ESP32Utils::WiFiAuthModeToWeaveWiFiSecurityType(scanResult.authmode);
netInfo.WirelessSignalStrength = scanResult.rssi;
{
nl::Weave::TLV::TLVWriter savePoint = writer;
err = netInfo.Encode(writer);
if (err == WEAVE_ERROR_BUFFER_TOO_SMALL)
{
writer = savePoint;
break;
}
}
SuccessOrExit(err);
}
err = writer.EndContainer(outerContainerType);
SuccessOrExit(err);
err = writer.Finalize();
SuccessOrExit(err);
// Send the scan results to the requestor. Note that this method takes ownership of the
// buffer, success or fail.
err = SendNetworkScanComplete(encodedResultCount, respBuf);
respBuf = NULL;
SuccessOrExit(err);
}
exit:
PacketBuffer::Free(respBuf);
// If an error occurred and we haven't yet responded, send a Internal Error back to the
// requestor.
if (err != WEAVE_NO_ERROR && GetCurrentOp() == kMsgType_ScanNetworks)
{
SendStatusReport(kWeaveProfile_Common, kStatus_InternalError, err);
}
// Tell the ConnectivityManager that the WiFi scan is now done. This allows it to continue
// any activities that were deferred while the scan was in progress.
ConnectivityMgr().OnWiFiScanDone();
}
#if WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
void NetworkProvisioningServerImpl::HandleScanTimeOut(::nl::Weave::System::Layer * aLayer, void * aAppState, ::nl::Weave::System::Error aError)
{
WeaveLogError(DeviceLayer, "WiFi scan timed out");
// Reset the state.
sInstance.mState = kState_Idle;
// Verify that the ScanNetworks request is still outstanding; if so, send a
// Common:InternalError StatusReport to the client.
if (sInstance.GetCurrentOp() == kMsgType_ScanNetworks)
{
sInstance.SendStatusReport(kWeaveProfile_Common, kStatus_InternalError, WEAVE_ERROR_TIMEOUT);
}
// Tell the ConnectivityManager that the WiFi scan is now done.
ConnectivityMgr().OnWiFiScanDone();
}
#endif // WEAVE_DEVICE_CONFIG_WIFI_SCAN_COMPLETION_TIMEOUT
bool NetworkProvisioningServerImpl::IsSupportedWiFiSecurityType(WiFiSecurityType_t wifiSecType)
{
return (wifiSecType == kWiFiSecurityType_None ||
wifiSecType == kWiFiSecurityType_WEP ||
wifiSecType == kWiFiSecurityType_WPAPersonal ||
wifiSecType == kWiFiSecurityType_WPA2Personal ||
wifiSecType == kWiFiSecurityType_WPA2Enterprise);
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace Weave
} // namespace nl