• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2020 HiHope Community.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * 1. Redistributions of source code must retain the above copyright notice, this
8  *    list of conditions and the following disclaimer.
9  *
10  * 2. Redistributions in binary form must reproduce the above copyright notice,
11  *    this list of conditions and the following disclaimer in the documentation
12  *    and/or other materials provided with the distribution.
13  *
14  * 3. Neither the name of the copyright holder nor the names of its
15  *    contributors may be used to endorse or promote products derived from
16  *    this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /* From w800 sdk */
31 #include "stddef.h"
32 #include "wm_type_def.h"
33 #include "wm_wifi.h"
34 #include "wm_params.h"
35 #include "wm_mem.h"
36 #include "wm_efuse.h"
37 #include "kv_store.h"
38 
39 /* Why we doing this?
40  * Symbol @WIFI_DISCONNECTED conflict with OHOS wifiservice,
41  * locate in foundation/communication/interfaces/kits/wifi_lite/wifiservice/wifi_linked_info.h
42  * They have different types. to avoid this confliction, redefine this macro with another name.
43  */
44 #ifdef WIFI_DISCONNECTED
45 #undef WIFI_DISCONNECTED // avoid conflict with wifi_linked_info.h
46 #endif
47 
48 #include "wifi_error_code.h"
49 #include "wifi_event.h"
50 #include "wifi_linked_info.h"
51 #include "securec.h"
52 #include "wifi_device.h"
53 
54 #include <stdio.h>
55 
56 #define BSS_BUFFER_SIZE (2048)
57 #define TLS_SSID_MAX_LEN (32) /* see wifi/wm_wifi.h ssid definition */
58 
59 static WifiDeviceConfig gWifiConfigs[WIFI_MAX_CONFIG_SIZE] = {{{0}, {0}, {0}, 0, WIFI_CONFIG_INVALID, 0, 0}};
60 static int gWifiStaStatus = WIFI_STA_NOT_ACTIVE;
61 static WifiEvent* gWifiEvents[WIFI_MAX_EVENT_SIZE] = {0};
62 static u8 gWifiScanDone = FALSE;
63 
64 // 0x1: NETIF_WIFI_JOIN_SUCCESS, 0x2: NETIF_WIFI_JOIN_FAILED, 0x3: NETIF_WIFI_DISCONNECTED
65 static volatile u8 g_connectStatus = 0;
66 
67 u8 g_hasConnected = 0;
68 
69 #define KV_FILE_NAME  "/data"
70 #define WIFI_CFG_INFO   "wifi_cfg_info"
71 
72 static int gScannedAPCount;
73 static u8* gScannedBuffer;
74 
75 #define MAX_WIFI_KV_NAME_LEN  (32)
76 
77 #define MAX_WIFI_KV_STRING_LEN  (160)
78 static u8 kvstring[MAX_WIFI_KV_STRING_LEN];
79 static u8 keystring[MAX_WIFI_KV_NAME_LEN];
80 static u8 keynew = 0;
81 static u8 keyold  = 0;
82 
83 // #ifndef DEBUG
84 #define DEBUG (1)
85 // #endif
86 
87 #define debug_wifi(fmt, ...)            \
88     do {                                \
89         if (DEBUG) {                    \
90             printf(fmt, ##__VA_ARGS__); \
91         }                               \
92     } while (0)
93 /*
94  * w800 doesn't support enable/disable wifi sta function
95  * always return success.
96  */
97 
EnableWifi(void)98 WifiErrorCode EnableWifi(void)
99 {
100     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
101         return ERROR_WIFI_UNKNOWN;
102     }
103 
104     if (gWifiStaStatus == WIFI_STA_ACTIVE) {
105         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
106             return ERROR_WIFI_UNKNOWN;
107         }
108         return ERROR_WIFI_BUSY;
109     }
110     tls_wifi_init();
111     gWifiStaStatus = WIFI_STA_ACTIVE;
112 
113     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
114         return ERROR_WIFI_UNKNOWN;
115     }
116     return WIFI_SUCCESS;
117 }
118 
DisableWifi(void)119 WifiErrorCode DisableWifi(void)
120 {
121     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
122         return ERROR_WIFI_UNKNOWN;
123     }
124 
125     if (gWifiStaStatus == WIFI_STA_NOT_ACTIVE) {
126         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
127             return ERROR_WIFI_UNKNOWN;
128         }
129         return ERROR_WIFI_NOT_STARTED;
130     }
131 
132     gWifiStaStatus = WIFI_STA_NOT_ACTIVE;
133 
134     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
135         return ERROR_WIFI_UNKNOWN;
136     }
137     return WIFI_SUCCESS;
138 }
139 
IsWifiActive(void)140 int IsWifiActive(void)
141 {
142     int ret;
143     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
144         return ERROR_WIFI_UNKNOWN;
145     }
146 
147     ret = gWifiStaStatus;
148 
149     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
150         return ERROR_WIFI_UNKNOWN;
151     }
152 
153     return ret;
154 }
155 
DispatchScanStateChangeEvent(const WifiEvent * event,WifiEventState state)156 static void DispatchScanStateChangeEvent(const WifiEvent* event, WifiEventState state)
157 {
158     int bssCount = 0;
159     if (event == NULL || event->OnWifiScanStateChanged == NULL) {
160         return;
161     }
162 
163     if (state == WIFI_STATE_NOT_AVAILABLE) {
164         event->OnWifiScanStateChanged(state, bssCount);
165         return;
166     }
167 
168     if (state == WIFI_STATE_AVAILABLE) {
169         bssCount = gScannedAPCount;
170         if (bssCount < 0) {
171             printf("Get scanned count failed.\n");
172             bssCount = 0;
173         }
174         event->OnWifiScanStateChanged(state, bssCount);
175         return;
176     }
177 }
178 
DispatchConnectEvent(int state,WifiLinkedInfo * info)179 static void DispatchConnectEvent(int state, WifiLinkedInfo* info)
180 {
181     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
182         if (gWifiEvents[i] != NULL && gWifiEvents[i]->OnWifiConnectionChanged != NULL) {
183             gWifiEvents[i]->OnWifiConnectionChanged(state, info);
184         }
185     }
186 }
187 
DispatchHotspotStateChangedEvent(int state)188 static void DispatchHotspotStateChangedEvent(int state)
189 {
190     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
191         if (gWifiEvents[i] != NULL && gWifiEvents[i]->OnHotspotStateChanged != NULL) {
192             gWifiEvents[i]->OnHotspotStateChanged(state);
193         }
194     }
195 }
196 
DispatchJoinEvent(StationInfo * info)197 static void DispatchJoinEvent(StationInfo* info)
198 {
199     if (!info) return;
200 
201     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
202         if (gWifiEvents[i] != NULL && gWifiEvents[i]->OnHotspotStaJoin != NULL) {
203             gWifiEvents[i]->OnHotspotStaJoin(info);
204         }
205     }
206 }
207 
DispatchLeaveEvent(StationInfo * info)208 static void DispatchLeaveEvent(StationInfo* info)
209 {
210     if (!info) return;
211 
212     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
213         if (gWifiEvents[i] != NULL && gWifiEvents[i]->OnHotspotStaLeave != NULL) {
214             gWifiEvents[i]->OnHotspotStaLeave(info);
215         }
216     }
217 }
218 
WifiScanHandler(void)219 static void WifiScanHandler(void)
220 {
221     int ret;
222     struct tls_scan_bss_t *scanRes = NULL;
223 
224     if (gScannedBuffer == NULL) {
225         printf("[wifi_device]: scan buffer is NULL!\n");
226 
227         gWifiScanDone = TRUE;
228         return;
229     }
230 
231     ret = tls_wifi_get_scan_rslt(gScannedBuffer, BSS_BUFFER_SIZE);
232     if (ret == WM_FAILED) {
233         printf("[wifi_device]: get scan result failed.\n");
234         tls_mem_free(gScannedBuffer);
235         gScannedBuffer = NULL;
236 
237         gWifiScanDone = TRUE;
238         return;
239     }
240 
241     scanRes = (struct tls_scan_bss_t *)gScannedBuffer;
242     gScannedAPCount = scanRes->count;
243 
244     LockWifiEventLock();
245 
246     printf("[wifi_service]: dispatch scan event.\n");
247     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
248         if (gWifiEvents[i] != NULL) {
249             DispatchScanStateChangeEvent(gWifiEvents[i], WIFI_STATE_AVAILABLE);
250         }
251     }
252     UnlockWifiEventLock();
253     gWifiScanDone = TRUE;
254 }
255 
Scan(void)256 WifiErrorCode Scan(void)
257 {
258     /* Check wifi station status */
259     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
260         return ERROR_WIFI_UNKNOWN;
261     }
262 
263     if (gWifiStaStatus == WIFI_STA_NOT_ACTIVE) {
264         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
265             return ERROR_WIFI_UNKNOWN;
266         }
267         return ERROR_WIFI_NOT_STARTED;
268     }
269 
270     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
271         return ERROR_WIFI_UNKNOWN;
272     }
273 
274     if (LockWifiEventLock() != WIFI_SUCCESS) {
275         return ERROR_WIFI_UNKNOWN;
276     }
277 
278     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
279         if (gWifiEvents[i] == NULL) {
280             continue;
281         }
282         DispatchScanStateChangeEvent(gWifiEvents[i], WIFI_STATE_NOT_AVAILABLE);
283     }
284 
285     if (UnlockWifiEventLock() != WIFI_SUCCESS) {
286         return ERROR_WIFI_UNKNOWN;
287     }
288 
289     if (gScannedBuffer != NULL) {
290         memset_s(gScannedBuffer, sizeof(gScannedBuffer), 0, BSS_BUFFER_SIZE);
291     } else {
292         gScannedBuffer = tls_mem_alloc(BSS_BUFFER_SIZE);
293         if (gScannedBuffer == NULL) {
294             printf("[wifi_device]: Scan allocate memory failed.\n");
295             return ERROR_WIFI_UNKNOWN;
296         }
297     }
298 
299     tls_wifi_scan_result_cb_register(WifiScanHandler);
300     if (tls_wifi_scan() != WM_SUCCESS) {
301         printf("[wifi_service]:Scan failed to start sta scan.\n");
302         tls_wifi_scan_result_cb_register(NULL);
303         return ERROR_WIFI_UNKNOWN;
304     }
305 
306     while (gWifiScanDone == FALSE) {
307         osDelay(50); /* 500 ms */
308     }
309     gWifiScanDone = FALSE; /* Reset scan flag */
310 
311     return WIFI_SUCCESS;
312 }
313 
WifiEventCallback(u8 status)314 static void WifiEventCallback(u8 status)
315 {
316     switch (status) {
317         case NETIF_WIFI_JOIN_SUCCESS:
318             debug_wifi("WifiEventCallback status = WIFI_JOIN_SUCCESS\n");
319             WifiLinkedInfo info = {0};
320             WifiErrorCode err = GetLinkedInfo(&info);
321             if (err != WIFI_SUCCESS) {
322                 DispatchConnectEvent(WIFI_STATE_NOT_AVAILABLE, NULL);
323             } else {
324                 DispatchConnectEvent(WIFI_STATE_AVAILABLE, &info);
325             }
326             break;
327         case NETIF_WIFI_JOIN_FAILED:
328             debug_wifi("WifiEventCallback status = WIFI_JOIN_FAILED\n");
329             DispatchConnectEvent(WIFI_STATE_NOT_AVAILABLE, NULL);
330             break;
331         case NETIF_WIFI_DISCONNECTED:
332             debug_wifi("WifiEventCallback status = WIFI_DISCONNECTED\n");
333             DispatchConnectEvent(WIFI_STATE_NOT_AVAILABLE, NULL);
334             break;
335         case NETIF_WIFI_SOFTAP_SUCCESS: /* ap */
336             debug_wifi("WifiEventCallback status = WIFI_SOFTAP_SUCCESS\n");
337             DispatchHotspotStateChangedEvent(WIFI_HOTSPOT_ACTIVE);
338             break;
339         case NETIF_WIFI_SOFTAP_FAILED:
340             debug_wifi("WifiEventCallback status = WIFI_SOFTAP_FAILED\n");
341             DispatchHotspotStateChangedEvent(WIFI_HOTSPOT_NOT_ACTIVE);
342             break;
343         case NETIF_WIFI_SOFTAP_CLOSED:
344             debug_wifi("WifiEventCallback status = WIFI_SOFTAP_CLOSED\n");
345             DispatchHotspotStateChangedEvent(WIFI_HOTSPOT_NOT_ACTIVE);
346             break;
347         default:
348             debug_wifi("WifiEventCallback invalid status: %d\n", status);
349             break;
350     }
351 }
352 
WifiHotspotEventCallback(u8 * mac,enum tls_wifi_client_event_type event)353 static void WifiHotspotEventCallback(u8 *mac, enum tls_wifi_client_event_type event)
354 {
355     StationInfo info = {0};
356     memcpy_s(info.macAddress, sizeof(info.macAddress), mac, sizeof(info.macAddress));
357 
358     switch (event) {
359         case WM_WIFI_CLIENT_EVENT_ONLINE:
360             debug_wifi("WifiHotspotEventCallback event = ONLINE\n");
361             DispatchJoinEvent(&info);
362             break;
363         case WM_WIFI_CLIENT_EVENT_OFFLINE:
364             debug_wifi("WifiHotspotEventCallback event = OFFLINE\n");
365             DispatchLeaveEvent(&info);
366             break;
367     }
368 }
369 
RegisterWifiEvent(WifiEvent * event)370 WifiErrorCode RegisterWifiEvent(WifiEvent* event)
371 {
372     int i;
373 
374     if (event == NULL) {
375         return ERROR_WIFI_INVALID_ARGS;
376     }
377 
378     if (LockWifiEventLock() != WIFI_SUCCESS) {
379         printf("[wifi_device]: RegisterWifiEvent lock wifi event lock failed.\n");
380         return ERROR_WIFI_UNKNOWN;
381     }
382 
383     for (i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
384         if (gWifiEvents[i] == event) {
385             printf("[wifi_device]: event already registered.\n");
386             if (UnlockWifiEventLock() != WIFI_SUCCESS) {
387                 return ERROR_WIFI_UNKNOWN;
388             }
389             return ERROR_WIFI_INVALID_ARGS;
390         }
391         if (gWifiEvents[i] == NULL) {
392             gWifiEvents[i] = event;
393             break;
394         }
395     }
396     if (UnlockWifiEventLock() != WIFI_SUCCESS) {
397         return ERROR_WIFI_UNKNOWN;
398     }
399 
400     err_t err = tls_wifi_netif_add_status_event(WifiEventCallback);
401     if (err != 0) {
402         printf("[wifi_device]: tls_netif_add_status_event failed.\n");
403         return ERROR_WIFI_UNKNOWN;
404     }
405 
406     tls_wifi_softap_client_event_register(WifiHotspotEventCallback);
407     return WIFI_SUCCESS;
408 }
409 
UnRegisterWifiEvent(const WifiEvent * event)410 WifiErrorCode UnRegisterWifiEvent(const WifiEvent* event)
411 {
412     int i;
413     if (event == NULL) {
414         printf("[wifi_device]: UnRegisterWifiEvent event is null.\n");
415         return ERROR_WIFI_INVALID_ARGS;
416     }
417 
418     if (LockWifiEventLock() != WIFI_SUCCESS) {
419         printf("[wifi_device]: UnRegisterWifiEvent lock wifi event lock failed.\n");
420         return ERROR_WIFI_UNKNOWN;
421     }
422 
423     for (i = 0; i < WIFI_MAX_EVENT_SIZE; ++i) {
424         if (gWifiEvents[i] == event) {
425             gWifiEvents[i] = NULL;
426             UnlockWifiEventLock();
427             return WIFI_SUCCESS;
428         }
429     }
430     UnlockWifiEventLock();
431 
432     err_t err = tls_wifi_netif_remove_status_event(WifiEventCallback);
433     if (err != 0) {
434         printf("[wifi_device]: tls_netif_add_status_event failed.\n");
435         return ERROR_WIFI_UNKNOWN;
436     }
437 
438     printf("UnRegisterWifiEvent wifi event is not registered\n");
439     return ERROR_WIFI_UNKNOWN;
440 }
441 
AdvanceScan(WifiScanParams * params)442 WifiErrorCode AdvanceScan(WifiScanParams *params)
443 {
444     if (params == NULL) {
445         return ERROR_WIFI_UNKNOWN;
446     }
447 
448     if (params->scanType == WIFI_FREQ_SCAN && params->freqs == 0) {
449         return ERROR_WIFI_UNKNOWN;
450     }
451 
452     if (params->scanType == WIFI_SSID_SCAN && (params->ssidLen == 0 || strlen(params->ssid) == 0)) {
453         printf("[wifi_service] WIFI_SSID_SCAN, but ssid empty!\n");
454         return ERROR_WIFI_UNKNOWN;
455     }
456 
457     char emptyBssid[WIFI_MAC_LEN] = {0};
458     if (params->scanType == WIFI_BSSID_SCAN && memcmp(params->bssid, emptyBssid, sizeof(emptyBssid)) == 0) {
459         printf("[wifi_service] WIFI_BSSID_SCAN, but bssid empty!\n");
460         return ERROR_WIFI_UNKNOWN;
461     }
462 
463     if (params->scanType == WIFI_BAND_SCAN && params->band == 0) {
464         printf("[wifi_service] WIFI_BAND_SCAN, but band = %d invalid!\n", params->band);
465     }
466 
467     if (params->scanType < 0 || params->scanType > WIFI_BAND_SCAN) {
468         printf("[wifi_service] scanType invalid!\n");
469     }
470 
471     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
472         return ERROR_WIFI_UNKNOWN;
473     }
474     if (gWifiStaStatus == WIFI_STA_NOT_ACTIVE) {
475         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
476             return ERROR_WIFI_UNKNOWN;
477         }
478         return ERROR_WIFI_NOT_STARTED;
479     }
480 
481     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
482         return ERROR_WIFI_UNKNOWN;
483     }
484 
485     if (LockWifiEventLock() != WIFI_SUCCESS) {
486         return ERROR_WIFI_UNKNOWN;
487     }
488     for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) {
489         if (gWifiEvents[i] == NULL) {
490             continue;
491         }
492         DispatchScanStateChangeEvent(gWifiEvents[i], WIFI_STATE_NOT_AVAILABLE);
493     }
494     if (UnlockWifiEventLock() != WIFI_SUCCESS) {
495         return ERROR_WIFI_UNKNOWN;
496     }
497 
498     return Scan();
499 }
500 
GetScanInfoList(WifiScanInfo * result,unsigned int * size)501 WifiErrorCode GetScanInfoList(WifiScanInfo* result, unsigned int* size)
502 {
503     struct tls_scan_bss_t *scanRes = NULL;
504     struct tls_bss_info_t *bssInfo;
505     u32 scanCount, i;
506 
507     if (result == NULL || size == NULL || *size == 0) {
508         return ERROR_WIFI_INVALID_ARGS;
509     }
510 
511     /*
512      * scan result already stored in gScannedBuffer
513      * from scan callbcak.
514      */
515     if (gScannedBuffer == NULL) {
516         printf("[wifi_device]: no cached scan result.\n");
517         *size = 0;
518         return WIFI_SUCCESS;
519     }
520 
521     scanRes = (struct tls_scan_bss_t *)gScannedBuffer;
522     bssInfo = scanRes->bss;
523     scanCount = scanRes->count;
524 
525     if (scanCount > *size) {
526         printf("[wifi_device]: scan count overflow.\n");
527         return ERROR_WIFI_INVALID_ARGS;
528     }
529 
530     if (scanCount > WIFI_SCAN_HOTSPOT_LIMIT) {
531         printf("[wifi_device]: too many scan results.\n");
532         printf("[wifi_device]: limit to %d\n", WIFI_SCAN_HOTSPOT_LIMIT);
533         scanCount = WIFI_SCAN_HOTSPOT_LIMIT;
534     }
535 
536     for (i = 0; i < scanCount; ++i) {
537         int cpyErr = memcpy_s(result[i].ssid, WIFI_MAX_SSID_LEN, bssInfo->ssid, bssInfo->ssid_len);
538         if (cpyErr != EOK) {
539             printf("[wifi_device]: copy ssid of scan result failed\n");
540             return ERROR_WIFI_UNKNOWN;
541         }
542 
543         cpyErr = memcpy_s(result[i].bssid, WIFI_MAC_LEN, bssInfo->bssid, ETH_ALEN);
544         if (cpyErr != EOK) {
545             printf("[wifi_device]: copy bssid from scan result failed\n");
546             return ERROR_WIFI_UNKNOWN;
547         }
548 
549         result[i].securityType = WmAuth2HoSec(bssInfo->privacy);
550         result[i].rssi = (char)bssInfo->rssi;
551 
552         result[i].frequency = bssInfo->max_data_rate;
553         bssInfo++;
554     }
555 
556     /*
557      * Free gScannedBuffer here.
558      * Since We've already copied scan result to user.
559      * This is not useful anymore. free the memory
560      * The @Scan triggered again will re-allocate the memory.
561      */
562 
563     tls_mem_free(gScannedBuffer);
564     gScannedBuffer = NULL;
565     *size = scanCount;
566 
567     return WIFI_SUCCESS;
568 }
569 
GetDeviceMacAddress(unsigned char * result)570 WifiErrorCode GetDeviceMacAddress(unsigned char* result)
571 {
572     if (result == NULL) {
573         return ERROR_WIFI_INVALID_ARGS;
574     }
575 
576     if (tls_get_mac_addr((u8 *)result) != TLS_EFUSE_STATUS_OK) {
577         printf("GetDeviceMacAddress get mac address failed");
578         return ERROR_WIFI_UNKNOWN;
579     }
580     return WIFI_SUCCESS;
581 }
582 
AddDeviceConfig(const WifiDeviceConfig * config,int * result)583 WifiErrorCode AddDeviceConfig(const WifiDeviceConfig* config, int* result)
584 {
585     int netId = WIFI_CONFIG_INVALID;
586     int i;
587     int ret = 0;
588 
589     if (config == NULL || result == NULL) {
590         printf("[wifi_device]:add device config invalid argument.\n");
591         return ERROR_WIFI_INVALID_ARGS;
592     }
593 
594     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
595         printf("[wifi_device]:Lock wifi global lock failed.\n");
596         return ERROR_WIFI_UNKNOWN;
597     }
598     for (i = 0; i < WIFI_MAX_CONFIG_SIZE; i++) {
599         if (gWifiConfigs[i].netId != i) {
600             netId = i;
601             break;
602         }
603     }
604 
605     if (netId == WIFI_CONFIG_INVALID) {
606         printf("[wifi_service]:AddDeviceConfig wifi config is full, delete one first\n");
607         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
608             return ERROR_WIFI_UNKNOWN;
609         }
610         return ERROR_WIFI_BUSY;
611     }
612 
613     UtilsSetEnv(KV_FILE_NAME);
614     memset_s(kvstring, sizeof(kvstring), 0, MAX_WIFI_KV_STRING_LEN);
615     memset_s(keystring, sizeof(keystring), 0, MAX_WIFI_KV_NAME_LEN);
616     memcpy_s(kvstring, sizeof(kvstring), config, sizeof(WifiDeviceConfig));
617     kvstring[sizeof(WifiDeviceConfig)] = '\0';
618 
619     int n = sprintf_s(keystring, sizeof(keystring), WIFI_CFG_INFO"_%d", netId);
620     if (n < 0) {
621     }
622     ret = UtilsSetValue(keystring, kvstring);
623     if (ret < 0) {
624         return ERROR_WIFI_BUSY;
625     }
626 
627     int cpyErr = memcpy_s(&gWifiConfigs[netId], sizeof(WifiDeviceConfig), config, sizeof(WifiDeviceConfig));
628     if (cpyErr != EOK) {
629         printf("[wifi_service]:AddDeviceConfig memcpy failed, err = %d\n", cpyErr);
630         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
631             printf("[wifi_device] Unlock wifi global lock failed.\n");
632         }
633         return ERROR_WIFI_UNKNOWN;
634     }
635 
636     gWifiConfigs[netId].netId = netId;
637     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
638         printf("[wifi_device] Unlock wifi global lock failed after copy config.\n");
639         return ERROR_WIFI_UNKNOWN;
640     }
641 
642     *result = netId;
643     return WIFI_SUCCESS;
644 }
645 
GetDeviceConfigs(WifiDeviceConfig * result,unsigned int * size)646 WifiErrorCode GetDeviceConfigs(WifiDeviceConfig* result, unsigned int* size)
647 {
648     unsigned int retIndex = 0;
649     int i = 0;
650     int cpyErr;
651     int validflag = -1;
652 
653     if (result == NULL || size == NULL || *size == 0) {
654         return ERROR_WIFI_INVALID_ARGS;
655     }
656 
657     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
658         printf("[wifi_device]: Unlock wifi global lock failed in get device config.\n");
659         return ERROR_WIFI_UNKNOWN;
660     }
661 
662     UtilsSetEnv(KV_FILE_NAME);
663     for (i = 0; i < WIFI_MAX_CONFIG_SIZE; i++) {
664         memset_s(keystring, sizeof(keystring), 0, MAX_WIFI_KV_NAME_LEN);
665         int n = sprintf_s(keystring, sizeof(keystring), WIFI_CFG_INFO"_%d", i);
666         if (n < 0) {
667         }
668         int ret = UtilsGetValue(keystring, &gWifiConfigs[i], sizeof(WifiDeviceConfig));
669         if (ret == 0) {
670             validflag = 1;
671         }
672     }
673 
674     if (validflag < 0) {
675         printf("\r\n read wifi cfg info fail");
676         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
677             printf("[wifi_device] Unlock wifi global lock failed in get device config.\n");
678         }
679         return ERROR_WIFI_NOT_AVAILABLE;
680     } else {
681         // printf("\r\n read wifi cfg info ok");
682     }
683 
684     for (i = 0; i < WIFI_MAX_CONFIG_SIZE; ++i) {
685         if (gWifiConfigs[i].netId != i) {
686             continue;
687         }
688 
689         cpyErr = memcpy_s(&result[retIndex], sizeof(WifiDeviceConfig), &gWifiConfigs[i], sizeof(WifiDeviceConfig));
690         if (cpyErr != EOK) {
691             printf("[wifi_service]: GetDeviceConfig memcpy failed, err = %d\n", cpyErr);
692             if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
693                 printf("[wifi_device] Unlock wifi global lock failed in get device config.\n");
694             }
695             return ERROR_WIFI_UNKNOWN;
696         }
697 
698         retIndex++;
699         if (*size < retIndex) {
700             printf("[wifi_service: wifi device config overflow.\n");
701             return UnlockWifiGlobalLock() != WIFI_SUCCESS ? ERROR_WIFI_UNKNOWN : ERROR_WIFI_INVALID_ARGS;
702         }
703     }
704 
705     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
706         printf("[wifi_service: sem unlock failed.\n");
707         return ERROR_WIFI_UNKNOWN;
708     }
709 
710     if (retIndex == 0) {
711         printf("[wifi_service: ERROR_WIFI_NOT_AVAILABLE.\n");
712         return ERROR_WIFI_NOT_AVAILABLE;
713     }
714 
715     *size = retIndex;
716     return WIFI_SUCCESS;
717 }
718 
Disconnect(void)719 WifiErrorCode Disconnect(void)
720 {
721     printf("\r\nDisconnect: g_connectStatus=%d", g_connectStatus);
722 
723     tls_wifi_disconnect();
724 
725     if (g_connectStatus != NETIF_WIFI_JOIN_SUCCESS) {
726         return ERROR_WIFI_UNKNOWN;
727     }
728     g_connectStatus = NETIF_WIFI_DISCONNECTED;
729     return WIFI_SUCCESS;
730 }
731 
RemoveDevice(int networkId)732 WifiErrorCode RemoveDevice(int networkId)
733 {
734     if (networkId >= WIFI_MAX_CONFIG_SIZE || networkId < 0) {
735         printf("[wifi_service]:removeDevice invalid param: networkId=%d\n", networkId);
736         return ERROR_WIFI_INVALID_ARGS;
737     }
738 
739     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
740         return ERROR_WIFI_UNKNOWN;
741     }
742     if (memset_s(&gWifiConfigs[networkId], sizeof(WifiDeviceConfig),
743         0, sizeof(WifiDeviceConfig)) != EOK) {
744         printf("[wifi_service]:removeDevice memset failed\n");
745     }
746     gWifiConfigs[networkId].netId = WIFI_CONFIG_INVALID;
747 
748     gWifiStaStatus = WIFI_STA_NOT_ACTIVE;
749     g_connectStatus = 0;
750     g_hasConnected = 0;
751 
752 #if 1
753     UtilsSetEnv(KV_FILE_NAME);
754     memset_s(keystring, sizeof(keystring), 0, MAX_WIFI_KV_NAME_LEN);
755     int n = sprintf_s(keystring, sizeof(keystring), WIFI_CFG_INFO"_%d", networkId);
756     if (n < 0) {
757     }
758     int ret = UtilsDeleteValue(keystring);
759     if (ret < 0) {
760         printf("\r\n clear wifi cfg info fail");
761     } else {
762     }
763 #else
764     extern void HalFlashFileDeInit(void);
765     HalFlashFileDeInit();
766 #endif
767 
768     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
769         return ERROR_WIFI_UNKNOWN;
770     }
771     return WIFI_SUCCESS;
772 }
773 
GetLinkedInfo(WifiLinkedInfo * result)774 WifiErrorCode GetLinkedInfo(WifiLinkedInfo* result)
775 {
776     struct tls_curr_bss_t *bss;
777     int cpyErr;
778     WifiErrorCode retCode = WIFI_SUCCESS;
779     if (result == NULL) {
780         return ERROR_WIFI_INVALID_ARGS;
781     }
782 
783     enum tls_wifi_states wifi_states; /* wifi states */
784 
785     wifi_states = tls_wifi_get_state();
786     bss = tls_mem_alloc(sizeof(struct tls_curr_bss_t));
787     if (!bss) {
788         printf("[wifi_device]: GetLinkedInfo allocate memory failed.\n");
789         return ERROR_WIFI_UNKNOWN;
790     }
791 
792     (void)memset_s(bss, sizeof(struct tls_curr_bss_t), 0x00, sizeof(struct tls_curr_bss_t));
793     tls_wifi_get_current_bss(bss);
794 
795     cpyErr = memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, bss->ssid, TLS_SSID_MAX_LEN + 1);
796     if (cpyErr != EOK) {
797         printf("[wifi_device]: GetLinkedInfo copy ssid failed. err = %d.\n", cpyErr);
798         tls_mem_free(bss);
799         return ERROR_WIFI_UNKNOWN;
800     }
801 
802     cpyErr = memcpy_s(result->bssid, WIFI_MAC_LEN, bss->bssid, ETH_ALEN);
803     if (cpyErr != EOK) {
804         printf("[wifi_device]: GetLinkedInfo copy bssid failed. err = %d.\n", cpyErr);
805         tls_mem_free(bss);
806         return ERROR_WIFI_UNKNOWN;
807     }
808 
809     switch (wifi_states) {
810         case WM_WIFI_DISCONNECTED:
811             result->connState = WIFI_DISCONNECTED;
812             break;
813         case WM_WIFI_JOINED:
814             result->connState = WIFI_CONNECTED;
815             result->rssi = (signed char)(0 - bss->rssi);
816             break;
817         case WM_WIFI_SCANNING: /* fall through */
818         case WM_WIFI_JOINING:
819             printf("[wifi_device]: connecting is in progroess.\n");
820             retCode = ERROR_WIFI_BUSY; /* Mark Wi-Fi is busy. Is it reasonable? */
821             break;
822         default:
823             printf("[wifi_device]: GetLinkedInfo, unknown wifi states.\n");
824             retCode = ERROR_WIFI_INVALID_ARGS;
825             break;
826     }
827 
828     tls_mem_free(bss);
829     return retCode;
830 }
831 
InitWifiConfig(void)832 static void InitWifiConfig(void)
833 {
834     u8 wireless_protocol = 0;
835     struct tls_param_ip *ip_param = NULL;
836 
837     debug_wifi("InitWifiConfig, disconnect wifi...\n");
838     tls_wifi_disconnect();
839     tls_param_get(TLS_PARAM_ID_WPROTOCOL, (void *) &wireless_protocol, TRUE);
840     if (TLS_PARAM_IEEE80211_INFRA != wireless_protocol) {
841         debug_wifi("InitWifiConfig, destroy softap...\n");
842         tls_wifi_softap_destroy();
843         osDelay(10);
844         wireless_protocol = TLS_PARAM_IEEE80211_INFRA;
845         tls_param_set(TLS_PARAM_ID_WPROTOCOL, (void *) &wireless_protocol, TRUE); // FALSE
846     }
847 
848     ip_param = tls_mem_alloc(sizeof(struct tls_param_ip));
849     if (ip_param != NULL) {
850         tls_param_get(TLS_PARAM_ID_IP, ip_param, FALSE);
851         ip_param->dhcp_enable = TRUE;
852         tls_param_set(TLS_PARAM_ID_IP, ip_param, FALSE);
853         tls_mem_free(ip_param);
854     } else {
855         debug_wifi("InitWifiConfig, alloc memory failed.\n");
856     }
857 }
858 
WifiStatusHandler(u8 status)859 static void WifiStatusHandler(u8 status)
860 {
861     printf("\r\n WifiStatusHandler status=%d", status);
862     g_connectStatus = status;
863 }
864 
ConnectTo(int networkId)865 WifiErrorCode ConnectTo(int networkId)
866 {
867     if (networkId >= WIFI_MAX_CONFIG_SIZE || networkId < 0) {
868         return ERROR_WIFI_INVALID_ARGS;
869     }
870 
871     InitWifiConfig();
872 
873     if (LockWifiGlobalLock() != WIFI_SUCCESS) {
874         printf("[wifi_device]: ConnectTo lock wifi global lock failed.\n");
875         return ERROR_WIFI_UNKNOWN;
876     }
877 
878     if (gWifiConfigs[networkId].netId != networkId) {
879         printf("[wifi_device]: Connectto network id %d is not valid.\n", networkId);
880         if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
881             printf("[wifi_device]: ConnectTo unlock wifi global lock failed.\n");
882             return ERROR_WIFI_UNKNOWN;
883         }
884         return ERROR_WIFI_NOT_AVAILABLE;
885     }
886 
887     if (gWifiConfigs[networkId].preSharedKey[0] == '\0') {
888         debug_wifi("[wifi_device]: Connectto PSK is empty, auth mode is OPEN.\n");
889     }
890     printf("wifi device connect to SSID:%s, KEY:%s\r\n", gWifiConfigs[networkId].ssid,
891            gWifiConfigs[networkId].preSharedKey);
892 
893     if (gWifiConfigs[networkId].wapiPskType == WIFI_PSK_TYPE_HEX) {
894         debug_wifi("[wifi_device]: psk type is HEX type.\n");
895     }
896 
897     WifiDeviceConfig connConfig = gWifiConfigs[networkId];
898     if (tls_wifi_connect((u8*)connConfig.ssid, strlen(connConfig.ssid),
899         (u8*)connConfig.preSharedKey, strlen(connConfig.preSharedKey)) != WM_SUCCESS) {
900 #if TLS_CONFIG_DEBUG
901         printf("[wifi_device]: connect to %s failed.\n", connConfig.ssid);
902 #endif
903         UnlockWifiGlobalLock();
904         return ERROR_WIFI_UNKNOWN;
905     }
906 
907     if (UnlockWifiGlobalLock() != WIFI_SUCCESS) {
908         return ERROR_WIFI_UNKNOWN;
909     }
910 
911     g_connectStatus = 0;
912     err_t err = tls_wifi_netif_add_status_event(WifiStatusHandler);
913     if (err != 0) {
914         printf("[wifi_device]: tls_netif_add_status_event for ConnectTo failed.\n");
915         return ERROR_WIFI_UNKNOWN;
916     }
917 
918     while (g_connectStatus == 0) {
919         osDelay(10);
920     }
921 #if TLS_CONFIG_DEBUG
922     debug_wifi("Connect to %s done, status = %d!\n", connConfig.ssid, g_connectStatus);
923 #endif
924     if (g_connectStatus == NETIF_WIFI_JOIN_SUCCESS) {
925         g_hasConnected = 1;
926         return WIFI_SUCCESS;
927     }
928 
929     err = tls_wifi_netif_remove_status_event(WifiStatusHandler);
930     if (err != 0) {
931         printf("[wifi_device]: tls_netif_remove_status_event for ConnectTo failed.\n");
932         return ERROR_WIFI_UNKNOWN;
933     }
934     printf("[wifi_device]: ConnectTo failed due to unknown reason.\n");
935     return ERROR_WIFI_UNKNOWN;
936 }
937