四、wifi通信实验
4.1 WiFi-AP-STA 模式
AP 是 (Wireless) AccessPoint 的缩写,即 (无线) 访问接入点。简单来讲就像是无线路由器一样, 设备打开后进入 AP 模式,在手机的网络列表里面,可以搜索到类似 TPLINK_XXX 的名字(SSID)。我们的手机和笔记本电脑均可连接到创建的 AP 热点。
我们使用w800建立一个 apsta 共存状态的功能,同时作为 sta 时去连接指定的路由器,而作为 ap 时也允许其它 sta 设备通过指定的密码来连接。使用tls_wifi_softap_create API函数创建AP热点:
static int soft_ap_demo(char *apssid, char *appwd)
{
struct tls_softap_info_t apinfo;
struct tls_ip_info_t ipinfo;
u8 ret = 0;
memset(&apinfo, 0, sizeof(apinfo));
memset(&ipinfo, 0, sizeof(ipinfo));
u8 *ssid = (u8 *)"w800_apsta_demo";
u8 ssid_len = strlen("w800_apsta_demo");
if (apssid)
{
ssid_len = strlen(apssid);
MEMCPY(apinfo.ssid, apssid, ssid_len);
apinfo.ssid[ssid_len] = '\0';
}
else
{
MEMCPY(apinfo.ssid, ssid, ssid_len);
apinfo.ssid[ssid_len] = '\0';
}
apinfo.encrypt = strlen(appwd) ? IEEE80211_ENCRYT_CCMP_WPA2 : IEEE80211_ENCRYT_NONE;
apinfo.channel = 11; /*channel*/
apinfo.keyinfo.format = 1; /*format:0,hex, 1,ascii*/
apinfo.keyinfo.index = 1; /*wep index*/
apinfo.keyinfo.key_len = strlen(appwd); /*key length*/
MEMCPY(apinfo.keyinfo.key, appwd, strlen(appwd));
/*ip information:ip address,mask, DNS name*/
ipinfo.ip_addr[0] = 192;
ipinfo.ip_addr[1] = 168;
ipinfo.ip_addr[2] = 8;
ipinfo.ip_addr[3] = 1;
ipinfo.netmask[0] = 255;
ipinfo.netmask[1] = 255;
ipinfo.netmask[2] = 255;
ipinfo.netmask[3] = 0;
MEMCPY(ipinfo.dnsname, "local.wm", sizeof("local.wm"));
ret = tls_wifi_softap_create((struct tls_softap_info_t * )&apinfo, (struct tls_ip_info_t * )&ipinfo);
wm_printf("\nap create %s ! \n", (ret == WM_SUCCESS) ? "Successfully" : "Error");
return ret;
}
使用tls_wifi_connect API函数连接路由器:
static int connect_wifi_demo(char *ssid, char *pwd)
{
int ret;
ret = tls_wifi_connect((u8 *)ssid, strlen(ssid), (u8 *)pwd, strlen(pwd));
if (WM_SUCCESS == ret)
wm_printf("\nplease wait connect net......\n");
else
wm_printf("\napsta connect net failed, please check configure......\n");
return ret;
}
在main函数中初始化wifi,并传入需要连接的路由器wifi,设置AP热点名称,密码。
void UserMain(void)
{
printf("\n user task \n");
init_wifi_config();
connect_wifi_demo("@snail","ss559550");//连接路由器,名称@snail,密码ss559550
soft_ap_demo("w800_ap","12345678");//创建AP热点,名称w800_ap,密码12345678
}
程序编译下载到开发板运行,连接路由器成功打印出IP地址: