天天看点

梅科尔工作室-#14天鸿蒙设备开发实战#无线联网开发笔记HarmonyOS无线联网开发感悟

(目录)

HarmonyOS无线联网开发

AP及STA介绍参考:

  • 转 WiFi的STA和AP模式指什么? - ricks - 博客园 (cnblogs.com)
  • WiFi的STA和AP模式指什么? - 数码基础 - 第四窗口 (lilin.pro)

WiFi AP热点

参考:

  • HarmonyOS无线联网开发—WiFi AP热点_哔哩哔哩_bilibili
  • AP(无线访问接入点(WirelessAccessPoint))_百度百科 (baidu.com)
  • DHCP_百度百科 (baidu.com)

AP热点API介绍

wifi_device.h接口简介

接口名 功能描述
RegisterWifiEvent 要注册回调的事件

此处介绍一个AP热点中用到的一个api,完整介绍参见下面的STA联网部分,源码在

foundation\communication\interfaces\kits\wifi_lite\wifiservice\wifi_device.h

路径下

RegisterWifiEvent()
WifiErrorCode RegisterWifiEvent (WifiEvent * event)
           

描述:

为指定的Wi-Fi事件注册回调函数。当WifiEvent中定义的Wi-Fi事件发生时,将调用已注册的回调函数

参数:

名字 描述
event 表示要注册回调的事件

wifi_hotspot.h接口简介

这个wifi_hotspot.h中包含声明AP热点相关接口函数。

接口名 功能描述
EnableHotspot 启用AP热点模式
DisableHotspot 禁用AP热点模式
SetHotspotConfig 设置指定的热点配置
GetHotspotConfig 获取指定的热点配置
lsHotspotActive 检查AP热点模式是否启用
GetStationList 获取连接到该热点的一系列STA
GetSignalLevel 获取接收信号强度和频率

源码在

foundation\communication\interfaces\kits\wifi_lite\wifiservice\wifi_hotspot.h

路径下

EnableHotspot()
WifiErrorCode EnableHotspot (void )
           

描述:

启用Wifi热点模式

SetHotspotConfig()
WifiErrorCode SetHotspotConfig(const HotspotConfig* config)
           

描述:

设置指定的热点配置

IsHotspotActive()
int IsHotspotActive(void);
           

描述:

检查AP热点模式是否启用

GetStationList()
WifiErrorCode GetStationList(StationInfo* result, unsigned int* size)
           

描述:

获取连接到该热点的一系列STA

参数:

名字 描述
result 表示连接到该热点的STA列表
size 表示连接到该热点的STA数量

netifapi.h接口简介

源码在

vendor\hisi\hi3861\hi3861\third_party\lwip_sack\include\lwip\netifapi.h

路径下

netifapi_netif_find()
struct netif *netifapi_netif_find(const char *name);
           

参数:

名字 描述
name 网络接口名称

描述:

获取netif用于IP操作

netifapi_netif_set_addr()
netifapi_netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw);
           

参数:

名字 描述
netif 表示要更改的网络接口
ipaddr 表示新的IP地址
netmask 表示新的网络掩码
gw 表示新的默认网关IP地址

描述:

用于更改网络接口(包括网络掩码和默认网关)的IP

netifapi_dhcps_start()
netifapi_dhcps_start(struct netif *netif, char *start_ip, u16_t ip_num);
           

参数:

名字 描述
netif 表示lwIP网络接口
start_ip 表示DHCPv4地址池的起始ip地址
ip_num 表示需要在池中的ip地址数

描述:

在netif上启动DHCPv4服务器。当需要在netif上启动DHCPv4服务器时,只应调用一次

AP热点创建代码解读

补充说明:之前在梅科尔工作室-#14天鸿蒙设备开发实战#环境搭建笔记-开源基础软件社区-51CTO.COM一文,在部署环境->简易步骤中的在Ubuntu上获取源码的两种方法中,一种是从华为hpm网站上下载源码,另一种是从gitee仓库中clone下来,两种方法前者的代码更新速度要比后者的代码更新速度慢,如果通过前者获取的源码没有找到相应的案例,可以在gitee仓库上查找,或者直接使用后者获取源码,通过

git pull

命令从仓库中拉取代码进行更新。目前(2022.8.9)本文所需的案例两种方法获取的源码均有提供,因此继续使用第一种方法获取的源码进行开发(建议使用第二种方法,前面提到的那篇博文已进行补充)。

源码在

applications\BearPi\BearPi-HM_Nano\sample\D1_iot_wifi_ap\wifi_ap.c

路径 下,以下添加了部分注释:

/*当连接开发板创建热点(名字是BearPi)后,会在日志中打印相应的信息,提示连接成功,有新的Sta站加入,并会把热点的mac地址信息打印出来;当断开连接后,也会打印出相应的日志,提示连接断开,并把热点的mac地址信息打印出来*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "cmsis_os2.h"
#include "ohos_init.h"

#include "wifi_device.h"
#include "wifi_hotspot.h"
#include "wifi_error_code.h"
#include "lwip/netifapi.h"


#define AP_SSID "BearPi"
#define AP_PSK  "0987654321"

#define ONE_SECOND 1
#define DEF_TIMEOUT 15

static void OnHotspotStaJoinHandler(StationInfo *info);
static void OnHotspotStateChangedHandler(int state);
static void OnHotspotStaLeaveHandler(StationInfo *info);

static struct netif *g_lwip_netif = NULL;
static int g_apEnableSuccess = 0;
WifiEvent g_wifiEventHandler = {0};
WifiErrorCode error;

// 创建AP热点
static BOOL WifiAPTask(void)
{
    //延时2S便于查看日志,删除不影响运行
    osDelay(200);

    //注册wifi事件的回调函数
    g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;  // Sta站里加入一个事件的回调函数
    g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;  // Sta站里退出了一个事件回调函数
    g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;  // WiFi热点模式改变的事件回调函数
    error = RegisterWifiEvent(&g_wifiEventHandler);  // 注册以上3个回调函数
    if (error != WIFI_SUCCESS)
    {
        printf("RegisterWifiEvent failed, error = %d.\r\n",error);
        return -1;
    }
    printf("RegisterWifiEvent succeed!\r\n");
    //设置指定的热点配置
    HotspotConfig config = {0};

    strcpy(config.ssid, AP_SSID);  // ssid(Service Set Identifier),即服务集标识符
    strcpy(config.preSharedKey, AP_PSK);  // 秘钥
    config.securityType = WIFI_SEC_TYPE_PSK;  // 加密方式
    config.band = HOTSPOT_BAND_TYPE_2G;  // 频段
    config.channelNum = 7;  // 通道

    error = SetHotspotConfig(&config);  // 通过SetHotspotConfig接口设置指定的热点配置
    if (error != WIFI_SUCCESS)
    {
        printf("SetHotspotConfig failed, error = %d.\r\n", error);
        return -1;
    }
    printf("SetHotspotConfig succeed!\r\n");

    //启动wifi热点模式
    error = EnableHotspot(); 
    if (error != WIFI_SUCCESS)
    {
        printf("EnableHotspot failed, error = %d.\r\n", error);
        return -1;
    }
    printf("EnableHotspot succeed!\r\n");

    //检查热点模式是否使能(是否启用)
    if (IsHotspotActive() == WIFI_HOTSPOT_NOT_ACTIVE)
    {
        printf("Wifi station is not actived.\r\n");
        return -1;
    }
    printf("Wifi station is actived!\r\n");

    //启动dhcp
    g_lwip_netif = netifapi_netif_find("ap0");  // 创建一个网卡
    if (g_lwip_netif) 
    {
        ip4_addr_t bp_gw;
        ip4_addr_t bp_ipaddr;
        ip4_addr_t bp_netmask;

        IP4_ADDR(&bp_gw, 192, 168, 1, 1);           /* input your gateway for example: 192.168.1.1 ,网关*/
        IP4_ADDR(&bp_ipaddr, 192, 168, 1, 1);       /* input your IP for example: 192.168.1.1 ,IP地址*/
        IP4_ADDR(&bp_netmask, 255, 255, 255, 0);    /* input your netmask for example: 255.255.255.0 ,子网掩码*/

        err_t ret = netifapi_netif_set_addr(g_lwip_netif, &bp_ipaddr, &bp_netmask, &bp_gw);  // 对创建的g_lwip_netif网卡的网关、IP地址、子网掩码进行设置
        if(ret != ERR_OK)
        {
            printf("netifapi_netif_set_addr failed, error = %d.\r\n", ret);
            return -1;
        }
        printf("netifapi_netif_set_addr succeed!\r\n");

        ret = netifapi_dhcps_start(g_lwip_netif, 0, 0);  // 启动DHCP
        if(ret != ERR_OK)
        { 
            printf("netifapi_dhcp_start failed, error = %d.\r\n", ret);
            return -1;
        }
        printf("netifapi_dhcps_start succeed!\r\n");

    }

    /****************以下为UDP服务器代码***************/
	//在sock_fd 进行监听
    int sock_fd;
    //服务端地址信息
	struct sockaddr_in server_sock;

    //创建socket
	if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perror("socket is error.\r\n");
		return -1;
	}

	bzero(&server_sock, sizeof(server_sock));
	server_sock.sin_family = AF_INET;
	server_sock.sin_addr.s_addr = htonl(INADDR_ANY);
	server_sock.sin_port = htons(8888);

	//调用bind函数绑定socket和地址
	if (bind(sock_fd, (struct sockaddr *)&server_sock, sizeof(struct sockaddr)) == -1)
	{
		perror("bind is error.\r\n");
		return -1;
	}

    int ret;
    char recvBuf[512] = {0};
    //客户端地址信息
    struct sockaddr_in client_addr;
    int size_client_addr= sizeof(struct sockaddr_in);
    while (1)
    {
        
        printf("Waiting to receive data...\r\n");
        memset(recvBuf, 0, sizeof(recvBuf));
        ret = recvfrom(sock_fd, recvBuf, sizeof(recvBuf), 0, (struct sockaddr*)&client_addr,(socklen_t*)&size_client_addr);
        if(ret < 0)
        {
            printf("UDP server receive failed!\r\n");
            return -1;
        }
        printf("receive %d bytes of data from ipaddr = %s, port = %d.\r\n", ret, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
        printf("data is %s\r\n",recvBuf);
        ret = sendto(sock_fd, recvBuf, strlen(recvBuf), 0, (struct sockaddr *)&client_addr, sizeof(client_addr));
        if (ret < 0)
        {
            printf("UDP server send failed!\r\n");
            return -1;
        }
    }
    /*********************END********************/
}

static void HotspotStaJoinTask(void)
{
    static char macAddress[32] = {0};
    StationInfo stainfo[WIFI_MAX_STA_NUM] = {0};
    StationInfo *sta_list_node = NULL;
    unsigned int size = WIFI_MAX_STA_NUM;

    error = GetStationList(stainfo, &size);
    if (error != WIFI_SUCCESS) {
        printf("HotspotStaJoin:get list fail, error is %d.\r\n", error);
        return;
    }
    sta_list_node = stainfo;
    for (uint32_t i = 0; i < size; i++, sta_list_node++) {
    unsigned char* mac = sta_list_node->macAddress;
    snprintf(macAddress, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    printf("HotspotSta[%d]: macAddress=%s.\r\n",i, macAddress);
    }
    g_apEnableSuccess++;
}
static void OnHotspotStaJoinHandler(StationInfo *info)
{
    if (info == NULL) {
    printf("HotspotStaJoin:info is null.\r\n");
    } 
    else {
        printf("New Sta Join\n");
        // 创建一个任务
        osThreadAttr_t attr;
        attr.name = "HotspotStaJoinTask";
        attr.attr_bits = 0U;
        attr.cb_mem = NULL;
        attr.cb_size = 0U;
        attr.stack_mem = NULL;
        attr.stack_size = 2048;
        attr.priority = 24;
        if (osThreadNew((osThreadFunc_t)HotspotStaJoinTask, NULL, &attr) == NULL) {
            printf("HotspotStaJoin:create task fail!\r\n");
        }
    }
    return;
}

static void OnHotspotStaLeaveHandler(StationInfo *info)
{
    if (info == NULL) {
        printf("HotspotStaLeave:info is null.\r\n");
    } 
    else {
        static char macAddress[32] = {0};
        unsigned char* mac = info->macAddress;
        snprintf(macAddress, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        printf("HotspotStaLeave: macAddress=%s, reason=%d.\r\n", macAddress, info->disconnectedReason);
        g_apEnableSuccess--;
    }
    return;
}

static void OnHotspotStateChangedHandler(int state)
{
    printf("HotspotStateChanged:state is %d.\r\n", state);
    if (state == WIFI_HOTSPOT_ACTIVE) {
        printf("wifi hotspot active.\r\n");
    } else {
        printf("wifi hotspot noactive.\r\n");
    }
}

static void Wifi_AP_Demo(void)
{
    // 创建一个任务
    osThreadAttr_t attr;

    attr.name = "WifiAPTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)WifiAPTask, NULL, &attr) == NULL)
    {
        printf("Falied to create WifiAPTask!\r\n");
    }
}

APP_FEATURE_INIT(Wifi_AP_Demo);
           

修改

applications\BearPi\BearPi-HM_Nano\sample

路径下的BUILD.gn文件,指定

wifi_ap

,编译、烧录(与之前不同的是为了提高烧录速度,波特率设置2000000或3000000,设置大了可能不稳定但是能提高下载速度),之后打印日志

日志结果如下:

梅科尔工作室-#14天鸿蒙设备开发实战#无线联网开发笔记HarmonyOS无线联网开发感悟

如果无法打印出站点信息,则需要将

vendor\hisi\hi3861\hi3861_adapter\hals\communication\wifi_lite\wifiservice\source\wifi_hotspot.c

目录下的178行staNum的值改为WIFI_MAX_STA_NUM或者直接写6(原值是0),即

unsigned int staNum = WIFI_MAX_STA_NUM;

,之后才能通过GetStationList打印出站点信息。 通过hpm官网下载的源码需要修改,通过gitee仓库下载的源码是已经修改过的。

WiFi STA联网

参考:

  • HarmonyOS无线联网开发—WiFi STA联网_哔哩哔哩_bilibili
  • STA_百度百科 (baidu.com)

STA联网相关API介绍

wifi_device.h接口简介

这个wifi_device.h中包含声明STA联网相关接口函数。

接口名 功能描述
RegisterWifiEvent 要注册回调的事件
EnableWifi 启用Wifi STA模式
DisableWifi 禁用Wifi STA模式
lsWifiActive 检查Wifi STA模式是否启用
Scan 扫描热点信息
GetScanInfoList 获取所有扫描到的热点列表
AddDeviceConfig 配置连接到热点信息
GetDeviceConfigs 获取配置连接到热点信息
RemoveDevice 删除指定的热点配置信息
ConnectTo 连接到指定的热点
Disconnect 断开Wifi连接
GetLinkedInfo 获取热点连接信息
GetDeviceMacAddress 获取设备的MAC地址

源码在

foundation\communication\interfaces\kits\wifi_lite\wifiservice\wifi_device.h

路径下

RegisterWifiEvent()
WifiErrorCode RegisterWifiEvent (WifiEvent * event)
           

描述:

为指定的Wi-Fi事件注册回调函数。当WifiEvent中定义的Wi-Fi事件发生时,将调用已注册的回调函数

参数:

名字 描述
event 表示要注册回调的事件
EnableWifi()
WifiErrorCode EnableWifi (void )
           

描述:

启用STA模式

AddDeviceConfig()
WifiErrorCode AddDeviceConfig (const WifiDeviceConfig * config, int * result )
           

描述:

添加用于配置连接到热点信息,此函数生成一个networkId

参数:

名字 描述
config 表示要连接的热点信息.
result 表示生成的networkId。每个networkId匹配一个热点配置
ConnectTo()
WifiErrorCode ConnectTo (int networkId)
           

描述:

连接到指定networkId的热点

参数:

名字 描述
networkId 表示与目标热点匹配的网络id.

dhcp.h接口简介

dhcp_start()
err_t dhcp_start(n)
           

描述:

启动DHCP, 获取IP

STA联网代码解读

源码在

applications\BearPi\BearPi-HM_Nano\sample\D2_iot_wifi_sta_connect\wifi_sta_connect.c

路径下,一下添加了部分注释:

/*日志中打印出来了相关信息,如果打印出了ip信息,则证明联网成功,可以进行业务代码的编写*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "lwip/netif.h"
#include "lwip/netifapi.h"
#include "lwip/ip4_addr.h"
#include "lwip/api_shell.h"

#include "cmsis_os2.h"
#include "hos_types.h"
#include "wifi_device.h"
#include "wifiiot_errno.h"
#include "ohos_init.h"

#define DEF_TIMEOUT 15
#define ONE_SECOND 1

static void WiFiInit(void);
static void WaitSacnResult(void);
static int WaitConnectResult(void);
static void OnWifiScanStateChangedHandler(int state, int size);
static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info);
static void OnHotspotStaJoinHandler(StationInfo *info);
static void OnHotspotStateChangedHandler(int state);
static void OnHotspotStaLeaveHandler(StationInfo *info);

static int g_staScanSuccess = 0;
static int g_ConnectSuccess = 0;
static int ssid_count = 0;
WifiEvent g_wifiEventHandler = {0};
WifiErrorCode error;

#define SELECT_WLAN_PORT "wlan0"

#define SELECT_WIFI_SSID "BearPi"
#define SELECT_WIFI_PASSWORD "0987654321"
#define SELECT_WIFI_SECURITYTYPE WIFI_SEC_TYPE_PSK

static BOOL WifiSTATask(void)
{
    WifiScanInfo *info = NULL;
    unsigned int size = WIFI_SCAN_HOTSPOT_LIMIT;
    static struct netif *g_lwip_netif = NULL;
    WifiDeviceConfig select_ap_config = {0};

    // 延时2S便于查看日志,删除不影响运行
    osDelay(200);
    printf("<--System Init-->\r\n");

    //初始化WIFI,进行了一些时间回调函数的注册
    WiFiInit();

    //使能WIFI(启用Wifi STA模式)
    if (EnableWifi() != WIFI_SUCCESS)
    {
        printf("EnableWifi failed, error = %d\n", error);
        return -1;
    }

    //判断WIFI是否激活
    if (IsWifiActive() == 0)
    {
        printf("Wifi station is not actived.\n");
        return -1;
    }

    //分配空间,保存WiFi信息
    info = malloc(sizeof(WifiScanInfo) * WIFI_SCAN_HOTSPOT_LIMIT);
    if (info == NULL)
    {
        return -1;
    }

    //轮询查找WiFi列表
    do{
        //重置标志位
        ssid_count = 0;
        g_staScanSuccess = 0;

        //开始扫描
        Scan();  // 扫描成功后执行在WiFiInit()注册扫描状态的回调函数OnWifiScanStateChangedHandler,将热点个数赋值给ssid_count,并将g_staScanSuccess置为1,用以退出WaitSacnResult(),而不会打印出超时

        //等待扫描结果
        WaitSacnResult();

        //获取扫描列表
        error = GetScanInfoList(info, &size);

    }while(g_staScanSuccess != 1);

    //打印WiFi列表
    printf("********************\r\n");
    for(uint8_t i = 0; i < ssid_count; i++)
    {
        printf("no:%03d, ssid:%-30s, rssi:%5d\r\n", i+1, info[i].ssid, info[i].rssi/100);
    }
    printf("********************\r\n");

    
    //连接指定的WiFi热点
    for(uint8_t i = 0; i < ssid_count; i++)
    {
        if (strcmp(SELECT_WIFI_SSID, info[i].ssid) == 0)  // 检索所有的代码中是否有我们要连接的热点,此处要连接的热点为BearPi
        {
            int result;

            printf("Select:%3d wireless, Waiting...\r\n", i+1);

            //拷贝要连接的热点信息
            strcpy(select_ap_config.ssid, info[i].ssid);
            strcpy(select_ap_config.preSharedKey, SELECT_WIFI_PASSWORD);
            select_ap_config.securityType = SELECT_WIFI_SECURITYTYPE;

            if (AddDeviceConfig(&select_ap_config, &result) == WIFI_SUCCESS)  // 配置连接到热点信息
            {
                if (ConnectTo(result) == WIFI_SUCCESS && WaitConnectResult() == 1)  // ConnectTo用于连接到指定的热点,WaitConnectResult用于判断是否在指定时间内连接
                {
                    printf("WiFi connect succeed!\r\n");
                    g_lwip_netif = netifapi_netif_find(SELECT_WLAN_PORT);  // 创建一个网卡
                    break;
                }
            }
        }

        if(i == ssid_count-1)
        {
            printf("ERROR: No wifi as expected\r\n");
            while(1) osDelay(100);
        }
    }

    //启动DHCP
    if (g_lwip_netif)
    {
        dhcp_start(g_lwip_netif);  // 启动DHCP,连接热点后还要启动DHCP,这样才能上网
        printf("begain to dhcp\r\n");
    }


    //等待DHCP
    for(;;)
    {
        if(dhcp_is_bound(g_lwip_netif) == ERR_OK)  // 判断DHCP是否绑定成功
        {
            printf("<-- DHCP state:OK -->\r\n");

            //打印获取到的IP信息
            netifapi_netif_common(g_lwip_netif, dhcp_clients_info_show, NULL);
            break;
        }

        printf("<-- DHCP state:Inprogress -->\r\n");
        osDelay(100);
    }

    //执行其他操作,在此处书写自己的业务代码
    for(;;)
    {
        osDelay(100);
    }

}

static void WiFiInit(void)
{
    printf("<--Wifi Init-->\r\n");
    g_wifiEventHandler.OnWifiScanStateChanged = OnWifiScanStateChangedHandler;  // 扫描状态的回调函数
    g_wifiEventHandler.OnWifiConnectionChanged = OnWifiConnectionChangedHandler;  // 连接状态的回调函数
    g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;  // Sta站里加入一个事件的回调函数
    g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;  // Sta站里退出了一个事件回调函数
    g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;  // WiFi热点模式改变的事件回调函数
    error = RegisterWifiEvent(&g_wifiEventHandler);  // 注册以上5个回调函数,后面的3个回调函数不进行注册也可以
    if (error != WIFI_SUCCESS)
    {
        printf("register wifi event fail!\r\n");
    }
    else
    {
        printf("register wifi event succeed!\r\n");
    }
}

static void OnWifiScanStateChangedHandler(int state, int size)
{
    (void)state;
    if (size > 0)
    {
        ssid_count = size;
        g_staScanSuccess = 1;
    }
    return;
}

static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info)
{
    (void)info;

    if (state > 0)
    {
        g_ConnectSuccess = 1;
        printf("callback function for wifi connect\r\n");
    }
    else
    {
        printf("connect error,please check password\r\n");
    }
    return;
}

static void OnHotspotStaJoinHandler(StationInfo *info)
{
    (void)info;
    printf("STA join AP\n");
    return;
}

static void OnHotspotStaLeaveHandler(StationInfo *info)
{
    (void)info;
    printf("HotspotStaLeave:info is null.\n");
    return;
}

static void OnHotspotStateChangedHandler(int state)
{
    printf("HotspotStateChanged:state is %d.\n", state);
    return;
}

static void WaitSacnResult(void)
{
    int scanTimeout = DEF_TIMEOUT;
    while (scanTimeout > 0)
    {
        sleep(ONE_SECOND);
        scanTimeout--;
        if (g_staScanSuccess == 1)
        {
            printf("WaitSacnResult:wait success[%d]s\n", (DEF_TIMEOUT - scanTimeout));
            break;
        }
    }
    if (scanTimeout <= 0)
    {
        printf("WaitSacnResult:timeout!\n");
    }
}

static int WaitConnectResult(void)
{
    int ConnectTimeout = DEF_TIMEOUT;
    while (ConnectTimeout > 0)
    {
        sleep(1);
        ConnectTimeout--;
        if (g_ConnectSuccess == 1)
        {
            printf("WaitConnectResult:wait success[%d]s\n", (DEF_TIMEOUT - ConnectTimeout));
            break;
        }
    }
    if (ConnectTimeout <= 0)
    {
        printf("WaitConnectResult:timeout!\n");
        return 0;
    }

    return 1;
}

static void WifiClientSTA(void)
{
    // 创建一个任务
    osThreadAttr_t attr;

    attr.name = "WifiSTATask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = 24;

    if (osThreadNew((osThreadFunc_t)WifiSTATask, NULL, &attr) == NULL)
    {
        printf("Falied to create WifiSTATask!\n");
    }
}

APP_FEATURE_INIT(WifiClientSTA);
           

修改

applications\BearPi\BearPi-HM_Nano\sample

路径下的BUILD.gn文件,指定

wifi_sta_connect

,编译、烧录(与之前不同的是为了提高烧录速度,波特率设置2000000或3000000,设置大了可能不稳定但是能提高下载速度),之后打印日志

日志结果如下:

梅科尔工作室-#14天鸿蒙设备开发实战#无线联网开发笔记HarmonyOS无线联网开发感悟

本章学习中的两个案例源码见附件。

感悟

本章的学习内容较少,整体的难度也不是很大,但是对于其中涉及到的一些相关概念花了不少时间去理解,现在也是似懂非懂的,毕竟是零基础学习,基础概念是一大拦路虎,好在大多都能在网上找到相关解释,看来学习过程打牢基础是很有必要的。截至目前鸿蒙设备开发实战的学习还有最后两章,学习速度需要加快,继续加油!!!

附件链接:https://ost.51cto.com/resource/2247

继续阅读