梅科尔工作室——无线联网开发

wx62e8be090d392
发布于 2022-8-2 18:10
浏览
0收藏

5.1 WiFi AP热点

1. AP热点API介绍

梅科尔工作室——无线联网开发-鸿蒙开发者社区

2. AP热点创建代码解读

打开“D4_iot_tcp_server”工程的tcp_server_demo.c文件,修改部分代码即可实现UDP服务端

static void UDPServerTask(void)
//服务端地址信息
struct sockaddr_ in server. sock;
//客户端地址信息
struct sockaddr_ in client_ sock; 
socklen _t sin_ size;
//连接Wifi
WifiConnect("Hold","0987654321");
//创建socket
if ((sock. fd = socket(AF_ INET, SOCK_ DGRAM, 0)) == -1)
perror("socket is error\r\n");
exit(1);
}
bzero(&server_ sock, sizeof(server_ sock));
server_ sock.sin family = AF. _INET;
server_ sock.sin_ addr.s_ addr ■hton1(INADDR. ANY);
server_ sock.sin_ port = htons(_ PROT_ );
//调用bind函数绑定socket和地址
if (bind(sock_ fd, (struct sockaddr *)&server. sock, sizeof(server_ sock)) == -1) 
{
perror("bind is error\r\n");
exit(1);
}
//处理目标
ssize_ t ret;
while (1)
{
sin_ size = sizeof(struct sockaddr. _in);
bzero(recvbuf, sizeof(recvbuf));
if ((ret = recvfrom(sock_ fd, recvbuf, sizeof(recvbuf), 0,(struct sockaddr *)&Client_ sock, &sin_ size)) == -1){
printf("recv error \r\n");
}
printf("recv :%s\r\n", recvbuf);
if ((ret = sendto(sock_ fd, buf, strlen(buf), 0,(struct sockaddr *)&client_ sock, sizeof(client_ sock))) = -1){
		perror("send : ");
	}
    }
}

5.2 WiFi STA联网

1. STA联网相关API介绍

梅科尔工作室——无线联网开发-鸿蒙开发者社区

2. STA联网代码解读

打开"D2_iot_wifi_sta_connect"工程的wifi_sta_connect.c文件,可在代码中查看实现STA联网业务代码。

梅科尔工作室——无线联网开发-鸿蒙开发者社区

g_ wifiEventHandler .OnWifiScanstateChanged = OnWifiScanStateChangedHandler;
g_ wifiEventHandler .0nWifiConnec tionChanged = OnWifiConnecti onChangedHandler ;
error = RegisterWi fiEvent (&g_ wifi EventHandler) ;
if (error != WIFI_ SUCCESS)
printf("register wifi event fail!\r\n");
else
printf("register wifi event succeed!\r\n");
//使能WIFI
if (EnableWifi() != WIFI_ SUCCESS)
printf( " EnableWifi failed, error = %d\n", error);
return -1;
//判断WIFI是否激活
if (IsWifiActive() == e
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();
//等待扫描结果
WaitSacnResult();
//获取扫描列表
GetScanInfolist(info, &size); 
}while(g_ _staScanSuccess != 1);

分类
标签
收藏
回复
举报
回复
    相关推荐