wlan_mgnt.c 49.0 KB
Newer Older
1
/*
2
 * Copyright (c) 2006-2018, RT-Thread Development Team
3
 *
4
 * SPDX-License-Identifier: Apache-2.0
5 6 7
 *
 * Change Logs:
 * Date           Author       Notes
8
 * 2018-08-06     tyx          the first version
9 10
 */

11
#include <rthw.h>
12
#include <rtthread.h>
13 14 15 16 17
#include <wlan_dev.h>
#include <wlan_cfg.h>
#include <wlan_mgnt.h>
#include <wlan_prot.h>
#include <wlan_workqueue.h>
18

19
#define DBG_ENABLE
20 21 22
#ifdef RT_WLAN_MGNT_DEBUG
#define DBG_LEVEL DBG_LOG
#else
23
#define DBG_LEVEL DBG_INFO
24
#endif
25 26 27
#define DBG_SECTION_NAME  "WLAN.mgnt"
#define DBG_COLOR
#include <rtdbg.h>
28

29 30 31
#ifndef RT_WLAN_DEVICE
#define RT_WLAN_DEVICE(__device) ((struct rt_wlan_device *)__device)
#endif
32

33 34 35 36
#define RT_WLAN_LOG_D(_fmt, ...) LOG_D("L:%d "_fmt"", __LINE__, ##__VA_ARGS__)
#define RT_WLAN_LOG_I(...) LOG_I(__VA_ARGS__)
#define RT_WLAN_LOG_W(_fmt, ...) LOG_W("F:%s L:%d "_fmt"", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#define RT_WLAN_LOG_E(_fmt, ...) LOG_E("F:%s L:%d "_fmt"", __FUNCTION__, __LINE__, ##__VA_ARGS__)
37

38 39
#define STA_DEVICE()  (_sta_mgnt.device)
#define AP_DEVICE()  (_ap_mgnt.device)
40

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#define SRESULT_LOCK()    (rt_mutex_take(&scan_result_mutex, RT_WAITING_FOREVER))
#define SRESULT_UNLOCK()  (rt_mutex_release(&scan_result_mutex))

#define STAINFO_LOCK()    (rt_mutex_take(&sta_info_mutex, RT_WAITING_FOREVER))
#define STAINFO_UNLOCK()  (rt_mutex_release(&sta_info_mutex))

#define MGNT_LOCK()       (rt_mutex_take(&mgnt_mutex, RT_WAITING_FOREVER))
#define MGNT_UNLOCK()     (rt_mutex_release(&mgnt_mutex))

#define COMPLETE_LOCK()       (rt_mutex_take(&complete_mutex, RT_WAITING_FOREVER))
#define COMPLETE_UNLOCK()     (rt_mutex_release(&complete_mutex))

#define TIME_STOP()    (rt_timer_stop(&reconnect_time))
#define TIME_START()   (rt_timer_start(&reconnect_time))

#define DISCONNECT_RESPONSE_TICK    (2000)

58 59 60 61
#if RT_WLAN_EBOX_NUM < 1
#error "event box num Too little"
#endif

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
struct rt_wlan_mgnt_des
{
    struct rt_wlan_device *device;
    struct rt_wlan_info info;
    struct rt_wlan_key key;
    rt_uint8_t state;
    rt_uint8_t flags;
};

struct rt_wlan_event_desc
{
    rt_wlan_event_handler handler;
    void *parameter;
};

struct rt_wlan_sta_list
{
    struct rt_wlan_sta_list *next;
    struct rt_wlan_info info;
};

struct rt_wlan_sta_des
{
    int num;
    struct rt_wlan_sta_list *node;
};

struct rt_wlan_msg
{
    rt_int32_t event;
    rt_int32_t len;
    void *buff;
};

struct rt_wlan_complete_des
{
    struct rt_event complete;
    rt_uint32_t event_flag;
    int index;
};

static struct rt_mutex mgnt_mutex;

static struct rt_wlan_mgnt_des _sta_mgnt;
static struct rt_wlan_mgnt_des _ap_mgnt;

static struct rt_wlan_scan_result scan_result;
static struct rt_mutex scan_result_mutex;

static struct rt_wlan_sta_des sta_info;
static struct rt_mutex sta_info_mutex;

static struct rt_wlan_event_desc event_tab[RT_WLAN_EVT_MAX];

static struct rt_wlan_complete_des *complete_tab[5];
static struct rt_mutex complete_mutex;

static struct rt_timer reconnect_time;

rt_inline int _sta_is_null(void)
{
    if (_sta_mgnt.device == RT_NULL)
    {
        return 1;
    }
    return 0;
}
129

130
rt_inline int _ap_is_null(void)
131
{
132 133 134 135 136
    if (_ap_mgnt.device == RT_NULL)
    {
        return 1;
    }
    return 0;
137 138
}

139
rt_inline rt_bool_t _is_do_connect(void)
140
{
141 142 143 144 145 146 147
    if ((rt_wlan_get_autoreconnect_mode() == RT_FALSE) ||
            (rt_wlan_is_connected() == RT_TRUE) ||
            (_sta_mgnt.state & RT_WLAN_STATE_CONNECTING))
    {
        return RT_FALSE;
    }
    return RT_TRUE;
148 149
}

150 151 152
static void rt_wlan_mgnt_work(void *parameter);

static rt_err_t rt_wlan_send_msg(rt_wlan_dev_event_t event, void *buff, int len)
153
{
154 155 156 157 158 159 160 161
    struct rt_wlan_msg *msg;

    RT_WLAN_LOG_D("F:%s is run event:%d", __FUNCTION__, event);

    /* Event packing */
    msg = rt_malloc(sizeof(struct rt_wlan_msg) + len);
    if (msg == RT_NULL)
    {
162
        RT_WLAN_LOG_E("wlan mgnt send msg err! No memory");
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        return -RT_ENOMEM;
    }
    rt_memset(msg, 0, sizeof(struct rt_wlan_msg) + len);
    msg->event = event;
    if (len != 0)
    {
        msg->buff = ((char *)msg) + sizeof(struct rt_wlan_msg);
        msg->len = len;
    }

    /* send event to wlan thread */
    if (rt_wlan_workqueue_dowork(rt_wlan_mgnt_work, msg) != RT_EOK)
    {
        rt_free(msg);
        RT_WLAN_LOG_E("wlan mgnt do work fail");
        return -RT_ERROR;
    }
    return RT_EOK;
181 182
}

183
static rt_err_t rt_wlan_scan_result_cache(struct rt_wlan_info *info, int timeout)
184
{
185 186 187 188 189 190 191 192 193 194 195 196
    struct rt_wlan_info *ptable;
    rt_err_t err = RT_EOK;
    int i, insert = -1;

    if (_sta_is_null() || (info == RT_NULL)) return RT_EOK;

    RT_WLAN_LOG_D("ssid:%s len:%d mac:%02x:%02x:%02x:%02x:%02x:%02x", info->ssid.val, info->ssid.len,
                  info->bssid[0], info->bssid[1], info->bssid[2], info->bssid[3], info->bssid[4], info->bssid[5]);

    err = rt_mutex_take(&scan_result_mutex, rt_tick_from_millisecond(timeout));
    if (err != RT_EOK)
        return err;
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
    /* de-duplicatio */
    for (i = 0; i < scan_result.num; i++)
    {
        if ((info->ssid.len == scan_result.info[i].ssid.len) &&
                (rt_memcmp(&info->bssid[0], &scan_result.info[i].bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0))
        {
            rt_mutex_release(&scan_result_mutex);
            return RT_EOK;
        }
#ifdef RT_WLAN_SCAN_SORT
        if (insert >= 0)
        {
            continue;
        }
        /* Signal intensity comparison */
        if ((info->rssi < 0) && (scan_result.info[i].rssi < 0))
        {
            if (info->rssi > scan_result.info[i].rssi)
            {
                insert = i;
                continue;
            }
            else if (info->rssi < scan_result.info[i].rssi)
            {
                continue;
            }
        }

        /* Channel comparison */
        if (info->channel < scan_result.info[i].channel)
        {
            insert = i;
            continue;
        }
        else if (info->channel > scan_result.info[i].channel)
        {
            continue;
        }

        /* data rate comparison */
        if ((info->datarate > scan_result.info[i].datarate))
        {
            insert = i;
            continue;
        }
        else if (info->datarate < scan_result.info[i].datarate)
        {
            continue;
        }
247
#endif
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
    }

    /* Insert the end */
    if (insert == -1)
        insert = scan_result.num;

    if (scan_result.num >= RT_WLAN_SCAN_CACHE_NUM)
        return RT_EOK;

    /* malloc memory */
    ptable = rt_malloc(sizeof(struct rt_wlan_info) * (scan_result.num + 1));
    if (ptable == RT_NULL)
    {
        rt_mutex_release(&scan_result_mutex);
        RT_WLAN_LOG_E("wlan info malloc failed!");
        return -RT_ENOMEM;
    }
    scan_result.num ++;

    /* copy info */
    for (i = 0; i < scan_result.num; i++)
    {
        if (i < insert)
        {
            ptable[i] = scan_result.info[i];
        }
        else if (i > insert)
        {
            ptable[i] = scan_result.info[i - 1];
        }
        else if (i == insert)
        {
            ptable[i] = *info;
        }
    }
    rt_free(scan_result.info);
    scan_result.info = ptable;
    rt_mutex_release(&scan_result_mutex);
    return err;
}

static rt_err_t rt_wlan_sta_info_add(struct rt_wlan_info *info, int timeout)
{
    struct rt_wlan_sta_list *sta_list;
    rt_err_t err = RT_EOK;

    if (_ap_is_null() || (info == RT_NULL)) return RT_EOK;

    err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
    if (err == RT_EOK)
    {
        /* malloc memory */
        sta_list = rt_malloc(sizeof(struct rt_wlan_sta_list));
        if (sta_list == RT_NULL)
        {
            rt_mutex_release(&sta_info_mutex);
            RT_WLAN_LOG_E("sta list malloc failed!");
            return -RT_ENOMEM;
        }
        sta_list->next = RT_NULL;
        sta_list->info = *info;

        /* Append sta info */
        sta_list->next = sta_info.node;
        sta_info.node = sta_list;
        /* num++ */
        sta_info.num ++;
        rt_mutex_release(&sta_info_mutex);
        RT_WLAN_LOG_I("sta associated mac:%02x:%02x:%02x:%02x:%02x:%02x",
                      info->bssid[0], info->bssid[1], info->bssid[2],
                      info->bssid[3], info->bssid[4], info->bssid[5]);
    }
    return err;
}

static rt_err_t rt_wlan_sta_info_del(struct rt_wlan_info *info, int timeout)
{
    struct rt_wlan_sta_list *sta_list, *sta_prve;
    rt_err_t err = RT_EOK;

    if (_ap_is_null() || (info == RT_NULL)) return RT_EOK;

    err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
    if (err == RT_EOK)
    {
        /* traversing the list */
        for (sta_list = sta_info.node, sta_prve = RT_NULL; sta_list != RT_NULL;
                sta_prve = sta_list, sta_list = sta_list->next)
        {
            /* find mac addr */
            if (rt_memcmp(&sta_list->info.bssid[0], &info->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0)
            {
                if (sta_prve == RT_NULL)
                {
                    sta_info.node = sta_list->next;
                }
                else
                {
                    sta_prve->next = sta_list->next;
                }
                sta_info.num --;
                rt_free(sta_list);
                break;
            }
        }
        rt_mutex_release(&sta_info_mutex);
        RT_WLAN_LOG_I("sta exit mac:%02x:%02x:%02x:%02x:%02x:%02x",
                      info->bssid[0], info->bssid[1], info->bssid[2],
                      info->bssid[3], info->bssid[4], info->bssid[5]);
    }
    return err;
}

361
static rt_err_t rt_wlan_sta_info_del_all(int timeout)
362 363 364 365
{
    struct rt_wlan_sta_list *sta_list, *sta_next;
    rt_err_t err = RT_EOK;

366
    err = rt_mutex_take(&sta_info_mutex, rt_tick_from_millisecond(timeout));
367 368 369 370 371 372 373 374 375 376 377 378
    if (err == RT_EOK)
    {
        /* traversing the list */
        for (sta_list = sta_info.node; sta_list != RT_NULL; sta_list = sta_next)
        {
            sta_next = sta_list->next;
            sta_info.num --;
            rt_free(sta_list);
        }
        rt_mutex_release(&sta_info_mutex);
    }
    if (sta_info.num != 0)
379 380 381
    {
        RT_WLAN_LOG_W("\n\n!!!Program runing exception!!!\n\n");
    }
382 383 384
    sta_info.num = 0;
    sta_info.node = RT_NULL;
    return err;
385 386
}

387
static void rt_wlan_auto_connect_run(struct rt_work *work, void *parameter)
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
    static rt_uint32_t id = 0;
    struct rt_wlan_cfg_info cfg_info;
    char *password = RT_NULL;
    rt_base_t level;

    RT_WLAN_LOG_D("F:%s is run", __FUNCTION__);

    if (rt_mutex_take(&mgnt_mutex, 0) != RT_EOK)
        goto exit;

    /* auto connect status is disable or wifi is connect or connecting, exit */
    if (_is_do_connect() == RT_FALSE)
    {
        id = 0;
        RT_WLAN_LOG_D("not connection");
        goto exit;
    }

    /* Read the next configuration */
    rt_memset(&cfg_info, 0, sizeof(struct rt_wlan_cfg_info));
    if (rt_wlan_cfg_read_index(&cfg_info, id ++) == 0)
    {
        RT_WLAN_LOG_D("read cfg fail");
        id = 0;
        goto exit;
    }

    if (id >= rt_wlan_cfg_get_num()) id = 0;

    if ((cfg_info.key.len > 0) && (cfg_info.key.len < RT_WLAN_PASSWORD_MAX_LENGTH))
    {
        cfg_info.key.val[cfg_info.key.len] = '\0';
        password = (char *)(&cfg_info.key.val[0]);
    }
    rt_wlan_connect_adv(&cfg_info.info, password);
exit:
425
    rt_mutex_release(&mgnt_mutex);
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
    level = rt_hw_interrupt_disable();
    rt_memset(work, 0, sizeof(struct rt_work));
    rt_hw_interrupt_enable(level);
}

static void rt_wlan_cyclic_check(void *parameter)
{
    struct rt_workqueue *workqueue;
    static struct rt_work work;
    rt_base_t level;

    if ((_is_do_connect() == RT_TRUE) && (work.work_func == RT_NULL))
    {
        workqueue = rt_wlan_get_workqueue();
        if (workqueue != RT_NULL)
        {
            level = rt_hw_interrupt_disable();
            rt_work_init(&work, rt_wlan_auto_connect_run, RT_NULL);
            rt_hw_interrupt_enable(level);
            if (rt_workqueue_dowork(workqueue, &work) != RT_EOK)
            {
                level = rt_hw_interrupt_disable();
                rt_memset(&work, 0, sizeof(struct rt_work));
                rt_hw_interrupt_enable(level);
            }
        }
    }
}

static void rt_wlan_mgnt_work(void *parameter)
{
    struct rt_wlan_msg *msg = parameter;

    switch (msg->event)
    {
    case RT_WLAN_DEV_EVT_CONNECT:
    {
        struct rt_wlan_cfg_info cfg_info;

        /* save config */
        if (rt_wlan_is_connected() == RT_TRUE)
        {
            rt_enter_critical();
            cfg_info.info = _sta_mgnt.info;
            cfg_info.key = _sta_mgnt.key;
            rt_exit_critical();
            RT_WLAN_LOG_D("run save config! ssid:%s len%d", _sta_mgnt.info.ssid.val, _sta_mgnt.info.ssid.len);
            rt_wlan_cfg_save(&cfg_info);
        }
        break;
    }
    default :
        break;
    }

    rt_free(msg);
}

static void rt_wlan_event_dispatch(struct rt_wlan_device *device, rt_wlan_dev_event_t event, struct rt_wlan_buff *buff, void *parameter)
{
    rt_base_t level;
    void *user_parameter;
    rt_wlan_event_handler handler = RT_NULL;
    rt_err_t err = RT_NULL;
    rt_wlan_event_t user_event = RT_WLAN_EVT_MAX;
    int i;
    struct rt_wlan_buff user_buff = { 0 };

    if (buff)
    {
        user_buff = *buff;
    }
498
    /* Event Handle */
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
    switch (event)
    {
    case RT_WLAN_DEV_EVT_CONNECT:
    {
        RT_WLAN_LOG_D("event: CONNECT");
        _sta_mgnt.state |= RT_WLAN_STATE_CONNECT;
        _sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
        user_event = RT_WLAN_EVT_STA_CONNECTED;
        TIME_STOP();
        rt_wlan_send_msg(event, RT_NULL, 0);
        user_buff.data = &_sta_mgnt.info;
        user_buff.len = sizeof(struct rt_wlan_info);
        RT_WLAN_LOG_I("wifi connect success ssid:%s", &_sta_mgnt.info.ssid.val[0]);
        break;
    }
    case RT_WLAN_DEV_EVT_CONNECT_FAIL:
    {
        RT_WLAN_LOG_D("event: CONNECT_FAIL");
        _sta_mgnt.state &= ~RT_WLAN_STATE_CONNECT;
        _sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
        _sta_mgnt.state &= ~RT_WLAN_STATE_READY;
        user_event = RT_WLAN_EVT_STA_CONNECTED_FAIL;
        user_buff.data = &_sta_mgnt.info;
        user_buff.len = sizeof(struct rt_wlan_info);
        TIME_START();
        break;
    }
    case RT_WLAN_DEV_EVT_DISCONNECT:
    {
        RT_WLAN_LOG_D("event: DISCONNECT");
        _sta_mgnt.state &= ~RT_WLAN_STATE_CONNECT;
        _sta_mgnt.state &= ~RT_WLAN_STATE_READY;
        user_event = RT_WLAN_EVT_STA_DISCONNECTED;
        user_buff.data = &_sta_mgnt.info;
        user_buff.len = sizeof(struct rt_wlan_info);
        TIME_START();
        break;
    }
    case RT_WLAN_DEV_EVT_AP_START:
    {
        RT_WLAN_LOG_D("event: AP_START");
        _ap_mgnt.state |= RT_WLAN_STATE_ACTIVE;
        user_event = RT_WLAN_EVT_AP_START;
        user_buff.data = &_ap_mgnt.info;
        user_buff.len = sizeof(struct rt_wlan_info);
        break;
    }
    case RT_WLAN_DEV_EVT_AP_STOP:
    {
        RT_WLAN_LOG_D("event: AP_STOP");
        _ap_mgnt.state &= ~RT_WLAN_STATE_ACTIVE;
        user_event = RT_WLAN_EVT_AP_STOP;
551
        err = rt_wlan_sta_info_del_all(RT_WAITING_FOREVER);
552 553 554 555 556 557 558 559 560 561 562 563 564 565
        if (err != RT_NULL)
        {
            RT_WLAN_LOG_W("AP_STOP event handle fail");
        }
        user_buff.data = &_ap_mgnt.info;
        user_buff.len = sizeof(struct rt_wlan_info);
        break;
    }
    case RT_WLAN_DEV_EVT_AP_ASSOCIATED:
    {
        RT_WLAN_LOG_D("event: ASSOCIATED");
        user_event = RT_WLAN_EVT_AP_ASSOCIATED;
        if (user_buff.len != sizeof(struct rt_wlan_info))
            break;
566
        err = rt_wlan_sta_info_add(user_buff.data, RT_WAITING_FOREVER);
567 568 569 570 571 572 573 574 575 576 577 578
        if (err != RT_EOK)
        {
            RT_WLAN_LOG_W("AP_ASSOCIATED event handle fail");
        }
        break;
    }
    case RT_WLAN_DEV_EVT_AP_DISASSOCIATED:
    {
        RT_WLAN_LOG_D("event: DISASSOCIATED");
        user_event = RT_WLAN_EVT_AP_DISASSOCIATED;
        if (user_buff.len != sizeof(struct rt_wlan_info))
            break;
579
        err = rt_wlan_sta_info_del(user_buff.data, RT_WAITING_FOREVER);
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
        if (err != RT_EOK)
        {
            RT_WLAN_LOG_W("AP_DISASSOCIATED event handle fail");
        }
        break;
    }
    case RT_WLAN_DEV_EVT_AP_ASSOCIATE_FAILED:
    {
        RT_WLAN_LOG_D("event: AP_ASSOCIATE_FAILED");
        break;
    }
    case RT_WLAN_DEV_EVT_SCAN_REPORT:
    {
        RT_WLAN_LOG_D("event: SCAN_REPORT");
        user_event = RT_WLAN_EVT_SCAN_REPORT;
        if (user_buff.len != sizeof(struct rt_wlan_info))
            break;
        rt_wlan_scan_result_cache(user_buff.data, 0);
        break;
    }
    case RT_WLAN_DEV_EVT_SCAN_DONE:
    {
        RT_WLAN_LOG_D("event: SCAN_DONE");
        user_buff.data = &scan_result;
        user_buff.len = sizeof(scan_result);
        user_event = RT_WLAN_EVT_SCAN_DONE;
        break;
    }
    default :
    {
        RT_WLAN_LOG_D("event: UNKNOWN");
        return;
    }
    }

    /* send event */
    COMPLETE_LOCK();
    for (i = 0; i < sizeof(complete_tab) / sizeof(complete_tab[0]); i++)
    {
        if ((complete_tab[i] != RT_NULL))
        {
            complete_tab[i]->event_flag |= 0x1 << event;
            rt_event_send(&complete_tab[i]->complete, 0x1 << event);
            RT_WLAN_LOG_D("&complete_tab[i]->complete:0x%08x", &complete_tab[i]->complete);
        }
    }
    COMPLETE_UNLOCK();
627
    /* Get user callback */
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
    if (user_event < RT_WLAN_EVT_MAX)
    {
        level = rt_hw_interrupt_disable();
        handler = event_tab[user_event].handler;
        user_parameter = event_tab[user_event].parameter;
        rt_hw_interrupt_enable(level);
    }

    /* run user callback fun */
    if (handler)
    {
        handler(user_event, &user_buff, user_parameter);
    }
}

static struct rt_wlan_complete_des *rt_wlan_complete_create(const char *name)
{
    struct rt_wlan_complete_des *complete;
    int i;

    complete = rt_malloc(sizeof(struct rt_wlan_complete_des));
    if (complete == RT_NULL)
    {
        RT_WLAN_LOG_E("complete event create failed");
        MGNT_UNLOCK();
        return complete;
    }
    rt_event_init(&complete->complete, name, RT_IPC_FLAG_FIFO);
    complete->event_flag = 0;
    //protect
    COMPLETE_LOCK();
    for (i = 0; i < sizeof(complete_tab) / sizeof(complete_tab[0]); i++)
    {
        if (complete_tab[i] == RT_NULL)
        {
            complete->index = i;
            complete_tab[i] = complete;
            break;
        }
    }
    COMPLETE_UNLOCK();

    if (i >= sizeof(complete_tab) / sizeof(complete_tab[0]))
    {
        rt_event_detach(&complete->complete);
        rt_free(complete);
        complete = RT_NULL;
    }

    return complete;
}

static rt_err_t rt_wlan_complete_wait(struct rt_wlan_complete_des *complete, rt_uint32_t event,
                                      rt_uint32_t timeout, rt_uint32_t *recved)
{
    if (complete == RT_NULL)
    {
        return -RT_ERROR;
    }

    /* Check whether there is a waiting event */
    if (complete->event_flag & event)
    {
        *recved = complete->event_flag;
        return RT_EOK;
    }
    else
    {
        return rt_event_recv(&complete->complete, event, RT_EVENT_FLAG_OR,
                             rt_tick_from_millisecond(timeout), recved);
    }
}

static void rt_wlan_complete_delete(struct rt_wlan_complete_des *complete)
{
    if (complete == RT_NULL)
    {
        return;
    }
    COMPLETE_LOCK();
    complete_tab[complete->index] = RT_NULL;
    COMPLETE_UNLOCK();
    rt_event_detach(&complete->complete);
    rt_free(complete);
}

rt_err_t rt_wlan_set_mode(const char *dev_name, rt_wlan_mode_t mode)
{
    rt_device_t device = RT_NULL;
    rt_err_t err;
    rt_int8_t up_event_flag = 0;
    rt_wlan_dev_event_handler handler = RT_NULL;

    if ((dev_name == RT_NULL) || (mode >= RT_WLAN_MODE_MAX))
    {
        RT_WLAN_LOG_E("Parameter Wrongful name:%s mode:%d", dev_name, mode);
        return -RT_EINVAL;
    }

    RT_WLAN_LOG_D("%s is run dev_name:%s mode:%s%s%s", __FUNCTION__, dev_name,
                  mode == RT_WLAN_NONE ? "NONE" : "",
                  mode == RT_WLAN_STATION ? "STA" : "",
                  mode == RT_WLAN_AP ? "AP" : ""
                 );

    /* find device */
    device = rt_device_find(dev_name);
    if (device == RT_NULL)
    {
        RT_WLAN_LOG_E("not find device, set mode failed! name:%s", dev_name);
        return -RT_EIO;
    }
740 741

    MGNT_LOCK();
742 743 744
    if (RT_WLAN_DEVICE(device)->mode == mode)
    {
        RT_WLAN_LOG_D("L:%d this device mode is set");
745
        MGNT_UNLOCK();
746 747 748 749 750 751 752
        return RT_EOK;
    }

    if ((mode == RT_WLAN_STATION) &&
            (RT_WLAN_DEVICE(device)->flags & RT_WLAN_FLAG_AP_ONLY))
    {
        RT_WLAN_LOG_I("this device ap mode only");
753
        MGNT_UNLOCK();
754 755 756 757 758 759
        return -RT_ERROR;
    }
    else if ((mode == RT_WLAN_AP) &&
             (RT_WLAN_DEVICE(device)->flags & RT_WLAN_FLAG_STA_ONLY))
    {
        RT_WLAN_LOG_I("this device sta mode only");
760
        MGNT_UNLOCK();
761 762
        return -RT_ERROR;
    }
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
    /*
     * device == sta  and change to ap,  should deinit
     * device == ap   and change to sta, should deinit
    */
    if (((mode == RT_WLAN_STATION) && (RT_WLAN_DEVICE(device) == AP_DEVICE())) ||
            ((mode == RT_WLAN_AP) && (RT_WLAN_DEVICE(device) == STA_DEVICE())))
    {
        err = rt_wlan_set_mode(dev_name, RT_WLAN_NONE);
        if (err != RT_EOK)
        {
            RT_WLAN_LOG_E("change mode failed!");
            MGNT_UNLOCK();
            return err;
        }
    }

    /* init device */
    err = rt_wlan_dev_init(RT_WLAN_DEVICE(device), mode);
    if (err != RT_EOK)
    {
        RT_WLAN_LOG_E("F:%s L:%d wlan init failed", __FUNCTION__, __LINE__);
        MGNT_UNLOCK();
        return err;
    }

    /* the mode is none */
    if (mode == RT_WLAN_NONE)
    {
        if (_sta_mgnt.device == RT_WLAN_DEVICE(device))
        {
            _sta_mgnt.device = RT_NULL;
            _sta_mgnt.state = 0;
            up_event_flag = 1;
            handler = RT_NULL;
        }
        else if (_ap_mgnt.device == RT_WLAN_DEVICE(device))
        {
            _ap_mgnt.state = 0;
            _ap_mgnt.device = RT_NULL;
            up_event_flag = 1;
            handler = RT_NULL;
        }
    }
    /* save sta device */
    else if (mode == RT_WLAN_STATION)
    {
        up_event_flag = 1;
        handler = rt_wlan_event_dispatch;
        _sta_mgnt.device = RT_WLAN_DEVICE(device);
    }
    /* save ap device */
    else if (mode == RT_WLAN_AP)
    {
        up_event_flag = 1;
        handler = rt_wlan_event_dispatch;
        _ap_mgnt.device = RT_WLAN_DEVICE(device);
    }

    /* update dev event handle */
    if (up_event_flag == 1)
    {
        rt_wlan_dev_event_t event;
        for (event = RT_WLAN_DEV_EVT_INIT_DONE; event < RT_WLAN_DEV_EVT_MAX; event++)
        {
            if (handler)
            {
                rt_wlan_dev_register_event_handler(RT_WLAN_DEVICE(device), event, handler, RT_NULL);
            }
            else
            {
                rt_wlan_dev_unregister_event_handler(RT_WLAN_DEVICE(device), event, handler);
            }
        }
    }
    MGNT_UNLOCK();

    /* Mount protocol */
#ifdef RT_WLAN_DEFAULT_PROT
    rt_wlan_prot_attach(dev_name, RT_WLAN_DEFAULT_PROT);
843
#endif
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    return err;
}

rt_wlan_mode_t rt_wlan_get_mode(const char *dev_name)
{
    rt_device_t device = RT_NULL;
    rt_wlan_mode_t mode;

    if (dev_name == RT_NULL)
    {
        RT_WLAN_LOG_E("name is null");
        return RT_WLAN_NONE;
    }

    /* find device */
    device = rt_device_find(dev_name);
    if (device == RT_NULL)
    {
        RT_WLAN_LOG_E("device not find! name:%s", dev_name);
        return RT_WLAN_NONE;
    }

    /* get mode */
    mode = RT_WLAN_DEVICE(device)->mode;
    RT_WLAN_LOG_D("%s is run dev_name:%s mode:%s%s%s", __FUNCTION__, dev_name,
                  mode == RT_WLAN_NONE ? "NONE" : "",
                  mode == RT_WLAN_STATION ? "STA" : "",
                  mode == RT_WLAN_AP ? "AP" : "");

    return mode;
}

rt_bool_t rt_wlan_find_best_by_cache(const char *ssid, struct rt_wlan_info *info)
{
    int i, ssid_len;
    struct rt_wlan_info *info_best;
    struct rt_wlan_scan_result *result;

    ssid_len = rt_strlen(ssid);
    result = &scan_result;
    info_best = RT_NULL;

    SRESULT_LOCK();
    for (i = 0; i < result->num; i++)
    {
        /* SSID is equal. */
        if ((result->info[i].ssid.len == ssid_len) &&
                (rt_memcmp((char *)&result->info[i].ssid.val[0], ssid, ssid_len) == 0))
        {
            if (info_best == RT_NULL)
            {
                info_best = &result->info[i];
                continue;
            }
            /* Signal strength effective */
            if ((result->info[i].rssi < 0) && (info_best->rssi < 0))
            {
                /* Find the strongest signal. */
                if (result->info[i].rssi > info_best->rssi)
                {
                    info_best = &result->info[i];
                    continue;
                }
                else if (result->info[i].rssi < info_best->rssi)
                {
                    continue;
                }
            }

            /* Finding the fastest signal */
            if (result->info[i].datarate > info_best->datarate)
            {
                info_best = &result->info[i];
                continue;
            }
        }
    }
    SRESULT_UNLOCK();

    if (info_best == RT_NULL)
        return RT_FALSE;

    *info = *info_best;
    return RT_TRUE;
}

rt_err_t rt_wlan_connect(const char *ssid, const char *password)
{
    rt_err_t err = RT_EOK;
    int ssid_len = 0;
    struct rt_wlan_info info;
    struct rt_wlan_complete_des *complete;
    rt_uint32_t set = 0, recved = 0;

    /* sta dev Can't be NULL */
    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, ssid, password);
    if (ssid == RT_NULL)
    {
        RT_WLAN_LOG_E("ssid is null!");
        return -RT_EINVAL;
    }
    ssid_len = rt_strlen(ssid);
    if (ssid_len > RT_WLAN_SSID_MAX_LENGTH)
    {
        RT_WLAN_LOG_E("ssid is to long! ssid:%s len:%d", ssid, ssid_len);
        return -RT_EINVAL;
    }

    if ((rt_wlan_is_connected() == RT_TRUE) &&
            (rt_strcmp((char *)&_sta_mgnt.info.ssid.val[0], ssid) == 0))
    {
        RT_WLAN_LOG_I("wifi is connect ssid:%s", ssid);
        return RT_EOK;
    }
    /* get info from cache */
    INVALID_INFO(&info);
    MGNT_LOCK();
    if (rt_wlan_find_best_by_cache(ssid, &info) != RT_TRUE)
    {
        rt_wlan_scan_sync();
        rt_wlan_find_best_by_cache(ssid, &info);
        rt_wlan_scan_result_clean();
    }

    if (info.ssid.len <= 0)
    {
        RT_WLAN_LOG_W("not find ap! ssid:%s", ssid);
        MGNT_UNLOCK();
        return -RT_ERROR;
    }

    RT_WLAN_LOG_D("find best info ssid:%s mac: %02x %02x %02x %02x %02x %02x",
                  info.ssid.val, info.bssid[0], info.bssid[1], info.bssid[2], info.bssid[3], info.bssid[4], info.bssid[5]);

    /* create event wait complete */
    complete = rt_wlan_complete_create("join");
    if (complete == RT_NULL)
    {
        MGNT_UNLOCK();
        return -RT_ENOMEM;
    }
    /* run connect adv */
    err = rt_wlan_connect_adv(&info, password);
    if (err != RT_EOK)
    {
        rt_wlan_complete_delete(complete);
        MGNT_UNLOCK();
        return err;
    }

    /* Initializing events that need to wait */
    set |= 0x1 << RT_WLAN_DEV_EVT_CONNECT;
    set |= 0x1 << RT_WLAN_DEV_EVT_CONNECT_FAIL;
    /* Check whether there is a waiting event */
    rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
    rt_wlan_complete_delete(complete);
    /* check event */
    set = 0x1 << RT_WLAN_DEV_EVT_CONNECT;
    if (!(recved & set))
    {
        RT_WLAN_LOG_I("wifi connect failed!");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }
    MGNT_UNLOCK();
    return err;
}

rt_err_t rt_wlan_connect_adv(struct rt_wlan_info *info, const char *password)
{
    int password_len = 0;
    rt_err_t err = RT_EOK;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    if (info == RT_NULL)
    {
        RT_WLAN_LOG_E("info is null!");
        return -RT_EINVAL;
    }
    RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, info->ssid.val, password);
    /* Parameter checking */
    if (password != RT_NULL)
    {
        password_len = rt_strlen(password);
        if (password_len > RT_WLAN_PASSWORD_MAX_LENGTH)
        {
            RT_WLAN_LOG_E("password is to long! password:%s len:%d", password, password_len);
            return -RT_EINVAL;
        }
    }
    if (info->ssid.len == 0 || info->ssid.len > RT_WLAN_SSID_MAX_LENGTH)
    {
        RT_WLAN_LOG_E("ssid is zero or to long! ssid:%s len:%d", info->ssid.val, info->ssid.len);
        return -RT_EINVAL;
    }
    /* is connect ? */
    MGNT_LOCK();
    if (rt_wlan_is_connected())
    {
        if ((_sta_mgnt.info.ssid.len == info->ssid.len) &&
                (_sta_mgnt.key.len == password_len) &&
                (rt_memcmp(&_sta_mgnt.info.ssid.val[0], &info->ssid.val[0], info->ssid.len) == 0) &&
                (rt_memcmp(&_sta_mgnt.info.bssid[0], &info->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0) &&
                (rt_memcmp(&_sta_mgnt.key.val[0], password, password_len) == 0))
        {
            RT_WLAN_LOG_I("wifi Already Connected");
            MGNT_UNLOCK();
            return RT_EOK;
        }

        err = rt_wlan_disconnect();
        if (err != RT_EOK)
        {
            MGNT_UNLOCK();
            return err;
        }
    }

    /* save info */
    rt_enter_critical();
    _sta_mgnt.info = *info;
    rt_memcpy(&_sta_mgnt.key.val, password, password_len);
    _sta_mgnt.key.len = password_len;
    _sta_mgnt.key.val[password_len] = '\0';
    rt_exit_critical();
    /* run wifi connect */
    _sta_mgnt.state |= RT_WLAN_STATE_CONNECTING;
    err = rt_wlan_dev_connect(_sta_mgnt.device, info, password, password_len);
    if (err != RT_EOK)
    {
        rt_enter_critical();
        rt_memset(&_sta_mgnt.info, 0, sizeof(struct rt_wlan_ssid));
        rt_memset(&_sta_mgnt.key, 0, sizeof(struct rt_wlan_key));
        rt_exit_critical();
        _sta_mgnt.state &= ~RT_WLAN_STATE_CONNECTING;
        MGNT_UNLOCK();
        return err;
    }

    MGNT_UNLOCK();
    return err;
1092 1093
}

1094
rt_err_t rt_wlan_disconnect(void)
1095
{
1096 1097 1098
    rt_err_t err;
    struct rt_wlan_complete_des *complete;
    rt_uint32_t recved = 0, set = 0;
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    /* ap dev Can't be empty */
    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);

    /* run disconnect */
    MGNT_LOCK();
    /* create event wait complete */
    complete = rt_wlan_complete_create("disc");
    if (complete == RT_NULL)
    {
        MGNT_UNLOCK();
        return -RT_ENOMEM;
    }
    err = rt_wlan_dev_disconnect(_sta_mgnt.device);
    if (err != RT_EOK)
    {
        RT_WLAN_LOG_E("wifi disconnect fail");
        rt_wlan_complete_delete(complete);
        MGNT_UNLOCK();
        return err;
    }
    /* Initializing events that need to wait */
    set |= 0x1 << RT_WLAN_DEV_EVT_DISCONNECT;
    /* Check whether there is a waiting event */
    rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
    rt_wlan_complete_delete(complete);
    /* check event */
    set = 0x1 << RT_WLAN_DEV_EVT_DISCONNECT;
    if (!(recved & set))
    {
        RT_WLAN_LOG_E("disconnect failed!");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }
    RT_WLAN_LOG_I("disconnect success!");
    MGNT_UNLOCK();
    return err;
}

1142
rt_bool_t rt_wlan_is_connected(void)
1143
{
1144
    rt_bool_t _connect;
1145 1146 1147

    if (_sta_is_null())
    {
1148
        return RT_FALSE;
1149
    }
1150
    _connect = _sta_mgnt.state & RT_WLAN_STATE_CONNECT ? RT_TRUE : RT_FALSE;
1151 1152 1153 1154
    RT_WLAN_LOG_D("%s is run : %s", __FUNCTION__, _connect ? "connect" : "disconnect");
    return _connect;
}

1155
rt_bool_t rt_wlan_is_ready(void)
1156
{
1157
    rt_bool_t _ready;
1158 1159 1160

    if (_sta_is_null())
    {
1161
        return RT_FALSE;
1162
    }
1163
    _ready = _sta_mgnt.state & RT_WLAN_STATE_READY ? RT_TRUE : RT_FALSE;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    RT_WLAN_LOG_D("%s is run : %s", __FUNCTION__, _ready ? "ready" : "not ready");
    return _ready;
}

rt_err_t rt_wlan_set_mac(rt_uint8_t mac[6])
{
    rt_err_t err = RT_EOK;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x",
                  __FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    MGNT_LOCK();
    err = rt_wlan_dev_set_mac(STA_DEVICE(), mac);
    if (err != RT_EOK)
    {
        RT_WLAN_LOG_E("set sta mac addr fail");
        MGNT_UNLOCK();
        return err;
    }
    MGNT_UNLOCK();
    return err;
}

rt_err_t rt_wlan_get_mac(rt_uint8_t mac[6])
{
    rt_err_t err = RT_EOK;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    MGNT_LOCK();
    err = rt_wlan_dev_get_mac(STA_DEVICE(), mac);
    if (err != RT_EOK)
    {
        RT_WLAN_LOG_E("get sta mac addr fail");
        MGNT_UNLOCK();
        return err;
    }
    RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x",
                  __FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    MGNT_UNLOCK();
    return err;
1211 1212
}

1213 1214 1215 1216 1217 1218 1219
rt_err_t rt_wlan_get_info(struct rt_wlan_info *info)
{
    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
1220

1221 1222 1223 1224 1225 1226 1227
    rt_enter_critical();
    *info = _sta_mgnt.info;
    rt_exit_critical();
    return RT_EOK;
}

int rt_wlan_get_rssi(void)
1228
{
1229 1230 1231 1232 1233 1234
    int rssi = 0;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
1235

1236 1237 1238 1239 1240
    MGNT_LOCK();
    rssi = rt_wlan_dev_get_rssi(STA_DEVICE());
    RT_WLAN_LOG_D("%s is run rssi:%d", __FUNCTION__, rssi);
    MGNT_UNLOCK();
    return rssi;
1241 1242
}

1243
rt_err_t rt_wlan_start_ap(const char *ssid, const char *password)
1244
{
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    rt_err_t err = RT_EOK;
    int ssid_len = 0;
    struct rt_wlan_info info;
    struct rt_wlan_complete_des *complete;
    rt_uint32_t set = 0, recved = 0;

    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    if (ssid == RT_NULL) return -RT_EINVAL;

    rt_memset(&info, 0, sizeof(struct rt_wlan_info));
    RT_WLAN_LOG_D("%s is run ssid:%s password:%s", __FUNCTION__, ssid, password);
    if (password)
    {
        info.security = SECURITY_WPA2_AES_PSK;
    }
    ssid_len = rt_strlen(ssid);
    if (ssid_len > RT_WLAN_SSID_MAX_LENGTH)
    {
        RT_WLAN_LOG_E("ssid is to long! len:%d", ssid_len);
    }

    /* copy info */
    rt_memcpy(&info.ssid.val, ssid, ssid_len);
    info.ssid.len = ssid_len;
    info.channel = 6;

    /* Initializing events that need to wait */
    MGNT_LOCK();
    /* create event wait complete */
    complete = rt_wlan_complete_create("start_ap");
    if (complete == RT_NULL)
    {
        MGNT_UNLOCK();
        return -RT_ENOMEM;
    }

    /* start ap */
    err = rt_wlan_start_ap_adv(&info, password);
    if (err != RT_EOK)
    {
        rt_wlan_complete_delete(complete);
        RT_WLAN_LOG_I("start ap failed!");
        MGNT_UNLOCK();
        return err;
    }

    /* Initializing events that need to wait */
    set |= 0x1 << RT_WLAN_DEV_EVT_AP_START;
    set |= 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
    /* Check whether there is a waiting event */
    rt_wlan_complete_wait(complete, set, RT_WLAN_START_AP_WAIT_MS, &recved);
    rt_wlan_complete_delete(complete);
    /* check event */
    set = 0x1 << RT_WLAN_DEV_EVT_AP_START;
    if (!(recved & set))
    {
        RT_WLAN_LOG_I("start ap failed!");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }
    RT_WLAN_LOG_I("start ap successs!");
    MGNT_UNLOCK();
    return err;
1311 1312
}

1313
rt_err_t rt_wlan_start_ap_adv(struct rt_wlan_info *info, const char *password)
1314
{
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    rt_err_t err = RT_EOK;
    int password_len = 0;

    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
    password_len = rt_strlen(password);
    if (password_len > RT_WLAN_PASSWORD_MAX_LENGTH)
    {
        RT_WLAN_LOG_E("key is to long! len:%d", password_len);
        return -RT_EINVAL;
    }
    /* is start up ? */
    MGNT_LOCK();
    if (rt_wlan_ap_is_active())
    {
        if ((_ap_mgnt.info.ssid.len == info->ssid.len) &&
                (_ap_mgnt.info.security == info->security) &&
                (_ap_mgnt.info.channel == info->channel) &&
                (_ap_mgnt.info.hidden == info->hidden) &&
                (_ap_mgnt.key.len == password_len) &&
                (rt_memcmp(&_ap_mgnt.info.ssid.val[0], &info->ssid.val[0], info->ssid.len) == 0) &&
                (rt_memcmp(&_ap_mgnt.key.val[0], password, password_len)))
        {
            RT_WLAN_LOG_D("wifi Already Start");
            MGNT_UNLOCK();
            return RT_EOK;
        }
    }

    err = rt_wlan_dev_ap_start(AP_DEVICE(), info, password, password_len);
    if (err != RT_EOK)
    {
        MGNT_UNLOCK();
        return err;
    }
    rt_memcpy(&_ap_mgnt.info, info, sizeof(struct rt_wlan_info));
    rt_memcpy(&_ap_mgnt.key.val, password, password_len);
    _ap_mgnt.key.len = password_len;

    MGNT_UNLOCK();
    return err;
1359 1360
}

1361
int rt_wlan_ap_is_active(void)
1362
{
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    int _active = 0;

    if (_ap_is_null())
    {
        return 0;
    }

    _active = _ap_mgnt.state & RT_WLAN_STATE_ACTIVE ? 1 : 0;
    RT_WLAN_LOG_D("%s is run active:%s", __FUNCTION__, _active ? "Active" : "Inactive");
    return _active;
1373 1374
}

1375
rt_err_t rt_wlan_ap_stop(void)
1376
{
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    rt_err_t err = RT_EOK;
    struct rt_wlan_complete_des *complete;
    rt_uint32_t set = 0, recved = 0;

    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);

    MGNT_LOCK();
    /* create event wait complete */
    complete = rt_wlan_complete_create("stop_ap");
    if (complete == RT_NULL)
    {
        MGNT_UNLOCK();
        return -RT_ENOMEM;
    }
    err = rt_wlan_dev_ap_stop(AP_DEVICE());
    if (err != RT_EOK)
    {
        RT_WLAN_LOG_E("ap stop fail");
        rt_wlan_complete_delete(complete);
        MGNT_UNLOCK();
        return err;
    }
    /* Initializing events that need to wait */
    set |= 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
    /* Check whether there is a waiting event */
    rt_wlan_complete_wait(complete, set, RT_WLAN_START_AP_WAIT_MS, &recved);
    rt_wlan_complete_delete(complete);
    /* check event */
    set = 0x1 << RT_WLAN_DEV_EVT_AP_STOP;
    if (!(recved & set))
    {
        RT_WLAN_LOG_I("ap stop failed!");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }
    RT_WLAN_LOG_I("ap stop success!");
    MGNT_UNLOCK();
    return err;
}
1420

1421 1422 1423 1424 1425 1426 1427
rt_err_t rt_wlan_ap_get_info(struct rt_wlan_info *info)
{
    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
1428

1429
    *info = _ap_mgnt.info;
1430 1431
    return RT_EOK;
}
1432

1433
/* get sta number  */
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
int rt_wlan_ap_get_sta_num(void)
{
    int sta_num = 0;

    STAINFO_LOCK();
    sta_num = sta_info.num;
    STAINFO_UNLOCK();
    RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, sta_num);
    return sta_num;
}

1445
/* get sta info */
1446 1447 1448 1449 1450 1451
int rt_wlan_ap_get_sta_info(struct rt_wlan_info *info, int num)
{
    int sta_num = 0, i = 0;
    struct rt_wlan_sta_list *sta_list;

    STAINFO_LOCK();
1452
    /* sta_num = min(sta_info.num, num) */
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    sta_num = sta_info.num > num ? num : sta_info.num;
    for (sta_list = sta_info.node; sta_list != RT_NULL && i < sta_num; sta_list = sta_list->next)
    {
        info[i] = sta_list->info;
        i ++;
    }
    STAINFO_UNLOCK();
    RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, i);
    return i;
}

1464
/* deauth sta */
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
rt_err_t rt_wlan_ap_deauth_sta(rt_uint8_t *mac)
{
    rt_err_t err = RT_EOK;
    struct rt_wlan_sta_list *sta_list;
    rt_bool_t find_flag = RT_FALSE;

    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run mac: %02x:%02x:%02x:%02x:%02x:%02x:%d",
                  __FUNCTION__, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    if (mac == RT_NULL)
    {
        RT_WLAN_LOG_E("mac addr is null");
        return -RT_EINVAL;
    }

    MGNT_LOCK();
    if (sta_info.node == RT_NULL || sta_info.num == 0)
    {
        RT_WLAN_LOG_E("No AP");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }

    STAINFO_LOCK();
1493
    /* Search for MAC address from sta list */
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    for (sta_list = sta_info.node; sta_list != RT_NULL; sta_list = sta_list->next)
    {
        if (rt_memcmp(&sta_list->info.bssid[0], &mac[0], RT_WLAN_BSSID_MAX_LENGTH) == 0)
        {
            find_flag = RT_TRUE;
            break;
        }
    }
    STAINFO_UNLOCK();

1504
    /* No MAC address was found. return */
1505 1506 1507 1508 1509 1510 1511
    if (find_flag != RT_TRUE)
    {
        RT_WLAN_LOG_E("Not find mac addr");
        MGNT_UNLOCK();
        return -RT_ERROR;
    }

1512
    /* Kill STA */
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    err = rt_wlan_dev_ap_deauth(AP_DEVICE(), mac);
    if (err != RT_NULL)
    {
        RT_WLAN_LOG_E("deauth sta failed");
        MGNT_UNLOCK();
        return err;
    }

    MGNT_UNLOCK();
    return err;
}

rt_err_t rt_wlan_ap_set_country(rt_country_code_t country_code)
{
    rt_err_t err = RT_EOK;

    if (_ap_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run country:%d", __FUNCTION__, country_code);
    MGNT_LOCK();
    err = rt_wlan_dev_set_country(AP_DEVICE(), country_code);
    MGNT_UNLOCK();
    return err;
}

rt_country_code_t rt_wlan_ap_get_country(void)
{
    rt_country_code_t country_code = RT_COUNTRY_UNKNOWN;

    if (_ap_is_null())
    {
        return country_code;
    }
    MGNT_LOCK();
    country_code = rt_wlan_dev_get_country(AP_DEVICE());
    RT_WLAN_LOG_D("%s is run country:%d", __FUNCTION__, country_code);
    MGNT_UNLOCK();
    return country_code;
}

void rt_wlan_config_autoreconnect(rt_bool_t enable)
{
    RT_WLAN_LOG_D("%s is run enable:%d", __FUNCTION__, enable);

    MGNT_LOCK();
    if (enable)
    {
        _sta_mgnt.flags |= RT_WLAN_STATE_AUTOEN;
    }
    else
    {
        _sta_mgnt.flags &= ~RT_WLAN_STATE_AUTOEN;
    }
    MGNT_UNLOCK();
}

rt_bool_t rt_wlan_get_autoreconnect_mode(void)
{
    rt_bool_t enable = 0;

    enable = _sta_mgnt.flags & RT_WLAN_STATE_AUTOEN ? 1 : 0;
    RT_WLAN_LOG_D("%s is run enable:%d", __FUNCTION__, enable);
    return enable;
}

/* Call the underlying scan function, which is asynchronous.
The hotspots scanned are returned by callbacks */
rt_err_t rt_wlan_scan(void)
{
    rt_err_t err = RT_EOK;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);

    MGNT_LOCK();
    err = rt_wlan_dev_scan(STA_DEVICE(), RT_NULL);
    MGNT_UNLOCK();
    return err;
}

struct rt_wlan_scan_result *rt_wlan_scan_sync(void)
{
    struct rt_wlan_scan_result *result;

    /* Execute synchronous scan function */
    MGNT_LOCK();
    result = rt_wlan_scan_with_info(RT_NULL);
    MGNT_UNLOCK();
    return result;
}

struct rt_wlan_scan_result *rt_wlan_scan_with_info(struct rt_wlan_info *info)
{
    rt_err_t err = RT_EOK;
    struct rt_wlan_complete_des *complete;
    rt_uint32_t set = 0, recved = 0;

    if (_sta_is_null())
    {
        return RT_NULL;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
    if (info != RT_NULL && info->ssid.len > RT_WLAN_SSID_MAX_LENGTH)
    {
        RT_WLAN_LOG_E("ssid is to long!");
        return RT_NULL;
    }

    /* Create an event that needs to wait. */
    MGNT_LOCK();
    complete = rt_wlan_complete_create("scan");
    if (complete == RT_NULL)
    {
        MGNT_UNLOCK();
        return &scan_result;
    }

1635
    /* run scan */
1636 1637 1638 1639
    err = rt_wlan_dev_scan(STA_DEVICE(), info);
    if (err != RT_EOK)
    {
        rt_wlan_complete_delete(complete);
1640
        RT_WLAN_LOG_E("scan sync fail");
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
        MGNT_UNLOCK();
        return RT_NULL;
    }

    /* Initializing events that need to wait */
    set |= 0x1 << RT_WLAN_DEV_EVT_SCAN_DONE;
    /* Check whether there is a waiting event */
    rt_wlan_complete_wait(complete, set, RT_WLAN_CONNECT_WAIT_MS, &recved);
    rt_wlan_complete_delete(complete);
    /* check event */
    set = 0x1 << RT_WLAN_DEV_EVT_SCAN_DONE;
    if (!(recved & set))
    {
1654
        RT_WLAN_LOG_E("scan wait timeout!");
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
        MGNT_UNLOCK();
        return &scan_result;
    }

    MGNT_UNLOCK();
    return &scan_result;
}

int rt_wlan_scan_get_info_num(void)
{
    int num = 0;

    num = scan_result.num;
    RT_WLAN_LOG_D("%s is run num:%d", __FUNCTION__, num);
    return num;
}

int rt_wlan_scan_get_info(struct rt_wlan_info *info, int num)
{
    int _num = 0;

    SRESULT_LOCK();
    if (scan_result.num && num > 0)
    {
        _num = scan_result.num > num ? num : scan_result.num;
        rt_memcpy(info, scan_result.info, _num * sizeof(struct rt_wlan_info));
    }
    SRESULT_UNLOCK();
    return _num;
}

struct rt_wlan_scan_result *rt_wlan_scan_get_result(void)
{
    return &scan_result;
}

void rt_wlan_scan_result_clean(void)
{
    MGNT_LOCK();
    SRESULT_LOCK();

    /* If there is data */
    if (scan_result.num)
    {
        scan_result.num = 0;
        rt_free(scan_result.info);
        scan_result.info = RT_NULL;
    }
    SRESULT_UNLOCK();
    MGNT_UNLOCK();
}

int rt_wlan_scan_find_cache(struct rt_wlan_info *info, struct rt_wlan_info *out_info, int num)
{
    int i = 0, count = 0;
    struct rt_wlan_info *scan_info;
    rt_bool_t is_equ = 1;
    rt_uint8_t bssid_zero[RT_WLAN_BSSID_MAX_LENGTH] = { 0 };

    if ((out_info == RT_NULL) || (info == RT_NULL) || (num <= 0))
    {
        return 0;
    }
    SRESULT_LOCK();
    /* Traversing the cache to find a qualified hot spot information */
    for (i = 0; (i < scan_result.num) && (count < num); i++)
    {
        scan_info = &scan_result.info[i];

        if (is_equ && (info->security != SECURITY_UNKNOWN))
        {
            is_equ &= info->security == scan_info->security;
        }
        if (is_equ && ((info->ssid.len > 0) && (info->ssid.len == scan_info->ssid.len)))
        {
            is_equ &= rt_memcmp(&info->ssid.val[0], &scan_info->ssid.val[0], scan_info->ssid.len) == 0;
        }
        if (is_equ && (rt_memcmp(&info->bssid[0], bssid_zero, RT_WLAN_BSSID_MAX_LENGTH)))
        {
            is_equ &= rt_memcmp(&info->bssid[0], &scan_info->bssid[0], RT_WLAN_BSSID_MAX_LENGTH) == 0;
        }
        if (is_equ && info->datarate)
        {
            is_equ &= info->datarate == scan_info->datarate;
        }
        if (is_equ && (info->channel >= 0))
        {
            is_equ &= info->channel == scan_info->channel;
        }
        if (is_equ && (info->rssi < 0))
        {
            is_equ &= info->rssi == scan_info->rssi;
        }
        /* Determine whether to find */
        if (is_equ)
        {
            rt_memcpy(&out_info[count], scan_info, sizeof(struct rt_wlan_info));
            count ++;
        }
    }
    SRESULT_UNLOCK();

    return count;
}

1760
rt_err_t rt_wlan_set_powersave(int level)
1761 1762 1763 1764 1765 1766 1767 1768 1769
{
    rt_err_t err = RT_EOK;

    if (_sta_is_null())
    {
        return -RT_EIO;
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
    MGNT_LOCK();
1770
    err = rt_wlan_dev_set_powersave(STA_DEVICE(), level);
1771 1772 1773 1774
    MGNT_UNLOCK();
    return err;
}

1775
int rt_wlan_get_powersave(void)
1776
{
1777
    int level;
1778 1779 1780

    if (_sta_is_null())
    {
1781
        return -1;
1782 1783 1784
    }
    RT_WLAN_LOG_D("%s is run", __FUNCTION__);
    MGNT_LOCK();
1785
    level = rt_wlan_dev_get_powersave(STA_DEVICE());
1786
    MGNT_UNLOCK();
1787
    return level;
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
}

rt_err_t rt_wlan_register_event_handler(rt_wlan_event_t event, rt_wlan_event_handler handler, void *parameter)
{
    rt_base_t level;

    if (event >= RT_WLAN_EVT_MAX)
    {
        return RT_EINVAL;
    }
    RT_WLAN_LOG_D("%s is run event:%d", __FUNCTION__, event);

    MGNT_UNLOCK();
    /* Registering Callbacks */
    level = rt_hw_interrupt_disable();
    event_tab[event].handler = handler;
    event_tab[event].parameter = parameter;
    rt_hw_interrupt_enable(level);
    MGNT_UNLOCK();
    return RT_EOK;
}

rt_err_t rt_wlan_unregister_event_handler(rt_wlan_event_t event)
{
    rt_base_t level;

    if (event >= RT_WLAN_EVT_MAX)
    {
        return RT_EINVAL;
    }
    RT_WLAN_LOG_D("%s is run event:%d", __FUNCTION__, event);
    MGNT_LOCK();
    /* unregister*/
    level = rt_hw_interrupt_disable();
    event_tab[event].handler = RT_NULL;
    event_tab[event].parameter = RT_NULL;
    rt_hw_interrupt_enable(level);
    MGNT_UNLOCK();
    return RT_EOK;
}

void rt_wlan_mgnt_lock(void)
{
    MGNT_LOCK();
}

void rt_wlan_mgnt_unlock(void)
{
    MGNT_UNLOCK();
}

int rt_wlan_prot_ready_event(struct rt_wlan_device *wlan, struct rt_wlan_buff *buff)
{
    rt_base_t level;
    void *user_parameter;
    rt_wlan_event_handler handler = RT_NULL;

    if ((wlan == RT_NULL) || (_sta_mgnt.device != wlan) ||
            (!(_sta_mgnt.state & RT_WLAN_STATE_CONNECT)))
    {
        return -1;
    }
    if (_sta_mgnt.state & RT_WLAN_STATE_READY)
    {
        return 0;
    }
    level = rt_hw_interrupt_disable();
    _sta_mgnt.state |= RT_WLAN_STATE_READY;
    handler = event_tab[RT_WLAN_EVT_READY].handler;
    user_parameter = event_tab[RT_WLAN_EVT_READY].parameter;
    rt_hw_interrupt_enable(level);
    if (handler)
    {
        handler(RT_WLAN_EVT_READY, buff, user_parameter);
    }
    return 0;
}

int rt_wlan_init(void)
{
    static rt_int8_t _init_flag = 0;

    /* Execute only once */
    if (_init_flag == 0)
    {
        rt_memset(&_sta_mgnt, 0, sizeof(struct rt_wlan_mgnt_des));
        rt_memset(&_ap_mgnt, 0, sizeof(struct rt_wlan_mgnt_des));
        rt_memset(&scan_result, 0, sizeof(struct rt_wlan_scan_result));
        rt_memset(&sta_info, 0, sizeof(struct rt_wlan_sta_des));
        rt_mutex_init(&mgnt_mutex, "mgnt", RT_IPC_FLAG_FIFO);
        rt_mutex_init(&scan_result_mutex, "scan", RT_IPC_FLAG_FIFO);
        rt_mutex_init(&sta_info_mutex, "sta", RT_IPC_FLAG_FIFO);
        rt_mutex_init(&complete_mutex, "complete", RT_IPC_FLAG_FIFO);
        rt_timer_init(&reconnect_time, "wifi_tim", rt_wlan_cyclic_check, RT_NULL, DISCONNECT_RESPONSE_TICK, RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_SOFT_TIMER);
        rt_timer_start(&reconnect_time);
        _init_flag = 1;
    }
    return 0;
}
INIT_PREV_EXPORT(rt_wlan_init);