优化接收数据的处理以及修改UDP地址
authorzwj <645281962@qq.com>
Wed, 21 Jun 2023 02:32:15 +0000 (10:32 +0800)
committerzwj <645281962@qq.com>
Wed, 21 Jun 2023 02:32:15 +0000 (10:32 +0800)
udp/inc/udp.h
udp/src/udp.c

index de3935740656254de5112c88ffa028a8efa583da..109ed34243ee66c6b80eacb7b4770e30a19903b5 100644 (file)
@@ -1,19 +1,21 @@
 #ifndef _UDP_H_
 #define _UDP_H_
+#include <stdbool.h>
 
 //端口号
 #define PORT 12020
+#define ACK_PORT 12021
 //接收报文数组大小
-#define BUFFER_SIZE 200
+#define BUFFER_SIZE 100
 //PID文件存放路径
 #define PID_FILE_PATH "/customer/tuya_key"
 //网卡名称
 #define ETH_NAME "wlan0"
 //设置mac地址长度
 #define MAC_SIZE 18
+//联网状态
+bool IS_NETWORKING;
 
-//构建JSON报文
-int build_a_response_message();
 //开启端口监听
 int open_udp_listen();
 //关闭端口监听
index 8a3555f042c81fb7b7e3ca03e43ddb4051d77588..8a76f49afe692c5990e981b7c8a10edca7569f44 100644 (file)
@@ -9,27 +9,36 @@
 #include <sys/ioctl.h>
 #include <arpa/inet.h>
 
-#include "mg_version.h"
 #include "cJSON.h"
 #include "udp.h"
 
 //套接字FD
 static int sockfd = 0;
+static int ack_sockfd = 0;
+//select选择套接字
+static int nfds = 0;
 //标志位
-static int stop = 0;
 static int FLAG = 0;
 //接收客户端报文
 static char rec_buffer[BUFFER_SIZE];
+static char rec_ack_buffer[BUFFER_SIZE];
 //存放上报msgtype
-static char msgType[30];
+static cJSON* msgType;
 //存放上报PID
-static char productId[30];
+static cJSON* productId;
+static char rec_pid[30];
+//存放上报的状态
+static cJSON* statusResult;
 //存放读取的板级PID
-static char on_board_PID[25];
+static cJSON* on_board_PID;
+static char board_pid[30];
 //存放MAC地址
 static char local_mac[18];
 //存放下发的JSON报文
 static char* res_json = NULL;
+static char* res_ack_json = NULL;
+//定义线程
+static pthread_t udp_thread;
 
 //函数声明
 static int read_the_system_PID();
@@ -102,7 +111,7 @@ static char* get_local_ip()
  * 参数:无
  * 返回值:成功 0 失败-1
  */
-int build_a_response_message()
+static int build_a_response_message()
 {
     get_local_mac();
     read_the_system_PID();
@@ -113,8 +122,8 @@ int build_a_response_message()
 
     cJSON* device = cJSON_CreateObject();
     cJSON_AddStringToObject(device, "mac", local_mac);
-    cJSON_AddStringToObject(device, "productId", on_board_PID);
-    cJSON_AddStringToObject(device, "version", SW_VERSION);
+    cJSON_AddStringToObject(device, "productId", board_pid);
+    cJSON_AddStringToObject(device, "version", "v1.0.1");
     cJSON_AddStringToObject(device, "ip", get_local_ip());
     cJSON_AddNumberToObject(device, "status", 0);
     cJSON_AddStringToObject(device, "qrCode", "http://iot.tuya.com/X7XJyjos");
@@ -136,47 +145,54 @@ int build_a_response_message()
  */
 static void string_interception(char* buffer)
 {
-    char* msgType_start = strstr(buffer, "\"msgType\":");//定位到msgType:位置
-    if (msgType_start != NULL) {
-        char* msgType_end = strchr(msgType_start, ',');
-        if (msgType_end != NULL) {
-            msgType_start += strlen("\"msgType\":");
-            msgType_end--;
-            while (*msgType_start == ' ' || *msgType_start == '\"') {
-                msgType_start++;
-            }
-            while (*msgType_end == ' ' || *msgType_end == '\"') {
-                msgType_end--;
-            }
-            int msgType_length = msgType_end - msgType_start + 1;
-            strncpy(msgType, msgType_start, msgType_length);
-            msgType[msgType_length] = '\0';
-            printf("msgType: %s\n", msgType);
-        }
-    }
-    if(!(strcmp(msgType,"SEARCH_REQ"))) {
-        char *productId_start = strstr(buffer, "\"productId\":");
-        if (productId_start != NULL) {
-            char *productId_end = strchr(productId_start, ',');
-            if (productId_end != NULL) {
-                productId_start += strlen("\"productId\":");
-                productId_end--;
-                while (*productId_start == ' ' || *productId_start == '\"') {
-                    productId_start++;
-                }
-                while (*productId_end == ' ' || *productId_end == '\"') {
-                    productId_end--;
-                }
-                int productId_length = productId_end - productId_start + 1;
-                strncpy(productId, productId_start, productId_length);
-                productId[productId_length] = '\0';
-                printf("productId: %s\n", productId);
-            }
-        }
-        else{
+    cJSON *root = cJSON_Parse(buffer);
+    msgType = cJSON_GetObjectItem(root, "msgType");
+    if (msgType == NULL)
+        printf("msgType not found\n");
+
+    if(!(strcmp(msgType->valuestring,"SEARCH_REQ")))
+    {
+        productId = cJSON_GetObjectItem(root, "productId");
+        if (productId == NULL)
             FLAG = 1;
-        }
+        strcpy(rec_pid,productId->valuestring);
     }
+    cJSON_Delete(root);
+}
+
+/*
+ *截取ACK内容
+ */
+static void get_statusResult(char* buffer)
+{
+    cJSON *root = cJSON_Parse(buffer);
+    statusResult = cJSON_GetObjectItem(root, "statusResult");
+
+    if (statusResult == NULL)
+        printf("statusResult not found\n");
+    else if (statusResult->valueint == 1)
+        IS_NETWORKING = true;
+    else
+        IS_NETWORKING = false;
+
+    cJSON_Delete(root);
+}
+
+/*
+ * 构建应答报文
+ */
+static int build_ACK_message()
+{
+    cJSON* root = cJSON_CreateObject();
+
+    cJSON_AddStringToObject(root, "msgType", "SUCCESS_ACK");
+
+    // 将 cJSON 对象转换为 JSON 字符串
+    res_ack_json = cJSON_Print(root);
+    if(res_ack_json == NULL)
+        return -1;
+    cJSON_Delete(root);
+    return 0;
 }
 
 /*
@@ -186,18 +202,14 @@ static void string_interception(char* buffer)
  */
 static void extract_product_id(const char* input_string)
 {
-    const char* start_delimiter = "\"productID\"";
-    const char* end_delimiter = "\",";
-    const char* start_position = strstr(input_string, start_delimiter);
-    if (start_position != NULL) {
-        start_position += strlen(start_delimiter) + 7;  // 跳过冒号和空格
-        const char* end_position = strstr(start_position, end_delimiter);
-        if (end_position != NULL) {
-            size_t length = end_position - start_position;
-            strncpy(on_board_PID, start_position, length);
-            on_board_PID[length] = '\0';
-        }
+    cJSON *root = cJSON_Parse(input_string);
+    on_board_PID = cJSON_GetObjectItem(root, "productID");
+
+    if (on_board_PID == NULL) {
+        printf("on_board_PID not found\n");
     }
+    strcpy(board_pid,on_board_PID->valuestring);
+    cJSON_Delete(root);
 }
 
 /*
@@ -239,32 +251,62 @@ static void* udp_task(void*data)
     int ret = 0;
     struct sockaddr_in client_addr;
     socklen_t client_addr_len;
-    while (stop) {
+    struct sockaddr_in ack_client_addr;
+    socklen_t ack_client_addr_len;
+    fd_set readfds;
+    while (1) {
+        usleep(500);
         client_addr_len = sizeof( client_addr );
-        // 接收数据报文存放到rec_buffer
-        ssize_t recv_len = recvfrom(sockfd, rec_buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr,
-                &client_addr_len);
-        if (recv_len < 0) {
-            perror("Error in recvfrom!\n");
+        ack_client_addr_len = sizeof( ack_client_addr );
+        //用于存储多个socket
+        FD_ZERO(&readfds);//初始化select对象,用来清空readfds集合,即readfds集合不再包含任何文件句柄。
+        //把创建的两个套接字文件描述符加入集合中
+        FD_SET(sockfd, &readfds);
+        FD_SET(ack_sockfd, &readfds);
+        //确定select对象中最大的文件描述符值加1
+        nfds = ack_sockfd + 1;
+        // 使用select监测多个UDP socket
+        if (select(nfds, &readfds, NULL, NULL, NULL) < 0) {
+            perror("select");
+
         }
-        //解析数据
-        string_interception(rec_buffer);
-
-        //准备下发数据
-        ret = strcmp(productId,on_board_PID);
-        if(ret == 0 || FLAG == 1){
-            FLAG = 0;
-            //下发构建好的JSON报文
-            ssize_t send_len = sendto(sockfd, res_json, strlen(res_json), 0,
-                                      (struct sockaddr*)&client_addr, client_addr_len);
+        if (FD_ISSET(sockfd, &readfds)) {//使用FD_ISSET判断是否就绪也就有无数据
+            // 接收数据报文存放到rec_buffer
+            ssize_t recv_len = recvfrom(sockfd, rec_buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr,
+                                        &client_addr_len);
+            printf("%s: %s",__func__ ,rec_buffer);
+            if (recv_len < 0 ) {
+                perror("Error in recvfrom!\n");
+            }
+            //解析数据
+            string_interception(rec_buffer);
+            build_a_response_message();
+            ret = strcmp(board_pid,rec_pid);
+            if(ret == 0 || FLAG == 1){
+                FLAG = 0;
+                //下发构建好的JSON报文
+                ssize_t send_len = sendto(sockfd, res_json, strlen(res_json), 0,
+                                          (struct sockaddr*)&client_addr, client_addr_len);
+                memset(rec_buffer,0,sizeof(rec_buffer));
+            }
         }
-        else{
-            //上报的PID不同时执行
-            sendto(sockfd, "Please check your PID!", strlen("Please check your PID!"), 0,
-                   (struct sockaddr *) &client_addr, client_addr_len);
+        if (FD_ISSET(ack_sockfd, &readfds)) {
+            ssize_t ack_recv_len = recvfrom(ack_sockfd, rec_ack_buffer, BUFFER_SIZE, 0,
+                                            (struct sockaddr*)&ack_client_addr,&ack_client_addr_len);
+            printf("%s: %s",__func__ ,rec_ack_buffer);
+            if (ack_recv_len < 0 )
+                perror("Error in recvfrom!\n");
+            //解析数据
+            get_statusResult(rec_ack_buffer);
+            //构建应答json报文
+            build_ACK_message();
+            ssize_t send_len = sendto(ack_sockfd, res_ack_json, strlen(res_ack_json), 0,
+                                      (struct sockaddr*)&ack_client_addr, ack_client_addr_len);
+            memset(rec_ack_buffer,0,sizeof(rec_ack_buffer));
         }
+
     }
-    return NULL;
+    pthread_exit(NULL);
 }
 
 /*
@@ -274,35 +316,47 @@ static void* udp_task(void*data)
  */
 int open_udp_listen()
 {
-    pthread_t udp_thread;
     struct sockaddr_in server_addr;
-    stop =1;
+    struct sockaddr_in ack_server_addr;
     // 创建套接字
     sockfd = socket(AF_INET, SOCK_DGRAM, 0);
-    if (sockfd < 0) {
+    ack_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
+    if (sockfd < 0 || ack_sockfd < 0) {
         perror("Error in socket!\n");
         goto error;
     }
-
     // 设置服务器地址和端口
     server_addr.sin_family = AF_INET;
-    server_addr.sin_addr.s_addr = INADDR_BROADCAST;
+    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
     server_addr.sin_port = htons(PORT);
 
+    // 设置服务器地址和端口
+    ack_server_addr.sin_family = AF_INET;
+    ack_server_addr.sin_addr.s_addr = inet_addr(get_local_ip());
+    ack_server_addr.sin_port = htons(ACK_PORT);
+
     // 绑定套接字到地址和端口
     if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
         perror("Error in bind!\n");
         goto error;
     }
 
-    printf("Server listening on port %d\n", PORT);
+    // 绑定套接字到地址和端口
+    if (bind(ack_sockfd, (struct sockaddr*)&ack_server_addr, sizeof(ack_server_addr)) < 0) {
+        perror("Error in bind!\n");
+        goto error;
+    }
+
+    printf("Server listening on port %d and %d\n", PORT,ACK_PORT);
     if( pthread_create( &udp_thread, NULL, udp_task, NULL) != 0 ){
         perror("create udp task!");
         goto error;
     }
+
     return 0;
     error :
     close(sockfd);
+    close(ack_sockfd);
     return -1;
 }
 
@@ -313,7 +367,14 @@ int open_udp_listen()
  */
 int close_udp_listen()
 {
-    stop = 0;
+    int ret = 0;
     close(sockfd);
+    close(ack_sockfd);
+    ret = pthread_cancel(udp_thread);
+    if(ret != 0)
+        return -1;
+    ret = pthread_join(udp_thread,NULL);
+    if(ret != 0)
+        return -1;
     return 0;
 }