1 /*
2 * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <stdio.h>
17 #include <unistd.h>
18 #include <netdb.h>
19 #include <string.h>
20 #include <stdlib.h>
21
22 #include "ohos_init.h"
23 #include "cmsis_os2.h"
24
25 #include "wifi_device.h"
26 #include "lwip/netifapi.h"
27 #include "lwip/api_shell.h"
28
29 #include "lwip/sockets.h"
30 #include "wifi_connect.h"
31
32 #define TASK_STACK_SIZE (1024 * 10)
33 #define TASK_DELAY_10S 10
34 #define CONFIG_WIFI_SSID "BearPi" // 要连接的WiFi 热点账号
35 #define CONFIG_WIFI_PWD "BearPi" // 要连接的WiFi 热点密码
36 #define CONFIG_SERVER_IP "192.168.0.175" // 要连接的服务器IP
37 #define CONFIG_SERVER_PORT 8888 // 要连接的服务器端口
38
39 static const char *send_data = "Hello! I'm BearPi-HM_Nano UDP Client!\r\n";
40
UDPClientTask(void)41 static void UDPClientTask(void)
42 {
43 // 在sock_fd 进行监听,在 new_fd 接收新的链接
44 int sock_fd;
45
46 // 服务器的地址信息
47 struct sockaddr_in send_addr;
48 socklen_t addr_length = sizeof(send_addr);
49 char recvBuf[512];
50
51 // 连接Wifi
52 WifiConnect(CONFIG_WIFI_SSID, CONFIG_WIFI_PWD);
53
54 // 创建socket
55 if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
56 perror("create socket failed!\r\n");
57 exit(1);
58 }
59
60 // 初始化预连接的服务端地址
61 send_addr.sin_family = AF_INET;
62 send_addr.sin_port = htons(CONFIG_SERVER_PORT);
63 send_addr.sin_addr.s_addr = inet_addr(CONFIG_SERVER_IP);
64 addr_length = sizeof(send_addr);
65
66 // 总计发送 count 次数据
67 while (1) {
68 bzero(recvBuf, sizeof(recvBuf));
69
70 // 发送数据到服务远端
71 sendto(sock_fd, send_data, strlen(send_data), 0, (struct sockaddr *)&send_addr, addr_length);
72
73 // 线程休眠一段时间
74 sleep(TASK_DELAY_10S);
75
76 // 接收服务端返回的字符串
77 recvfrom(sock_fd, recvBuf, sizeof(recvBuf), 0, (struct sockaddr *)&send_addr, &addr_length);
78 printf("%s:%d=>%s\n", inet_ntoa(send_addr.sin_addr), ntohs(send_addr.sin_port), recvBuf);
79 }
80
81 // 关闭这个 socket
82 closesocket(sock_fd);
83 }
84
UDPClientDemo(void)85 static void UDPClientDemo(void)
86 {
87 osThreadAttr_t attr;
88
89 attr.name = "UDPClientTask";
90 attr.attr_bits = 0U;
91 attr.cb_mem = NULL;
92 attr.cb_size = 0U;
93 attr.stack_mem = NULL;
94 attr.stack_size = TASK_STACK_SIZE;
95 attr.priority = osPriorityNormal;
96
97 if (osThreadNew((osThreadFunc_t)UDPClientTask, NULL, &attr) == NULL) {
98 printf("[UDPClientDemo] Failed to create UDPClientTask!\n");
99 }
100 }
101
102 APP_FEATURE_INIT(UDPClientDemo);
103