硬汉嵌入式论坛

 找回密码
 立即注册
查看: 230|回复: 1
收起左侧

[ThreadX全家桶] ppp拨号关于http协议

[复制链接]

70

主题

200

回帖

410

积分

高级会员

积分
410
发表于 2025-11-24 10:38:53 | 显示全部楼层 |阅读模式
本帖最后由 gck 于 2025-11-24 10:40 编辑

/* USER CODE BEGIN Header */

/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "app_netxduo.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

//#include  "nxd_http_client.h"
#include "stdbool.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
// HTTP配置
#define HTTP_SERVER_URL        "8.135.10.183"
#define HTTP_SERVER_PORT       16400

// PPP配置
#define PPP_USERNAME           " "
#define PPP_PASSWORD           " "

// 缓冲区大小
#define HTTP_BUFFER_SIZE       2048

// 新增POST配置
#define POST_API_PATH          "/api/data"      

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
NX_PPP  ppp_0;
NX_PACKET_POOL  pool_0;
NX_IP   ip_0;
ULONG   packet_pool_area[1024*40];
ULONG   error_counter;
ULONG   ppp_0_link_up_counter;
ULONG   ppp_0_link_down_counter;
ULONG   http_request_counter = 0;
extern uint8_t  ATstate;

CHAR    name_string[] = PPP_USERNAME;
CHAR    password_string[] = PPP_PASSWORD;

UINT    generate_login(CHAR *name, CHAR *password);
UCHAR   *pointer;

NX_WEB_HTTP_CLIENT         http_client;

void netx_http_client_demo(void);
//post
UINT http_client_post_request(CHAR *path, const CHAR *content_type,const CHAR *data, ULONG data_length);
//get
UINT http_client_get_request(void);

/* USER CODE END PFP */

/**
  * @brief  Application NetXDuo Initialization.
  * @param memory_ptr: memory pointer
  * @retval int
  */
UINT MX_NetXDuo_Init(VOID *memory_ptr)
{
  UINT ret = NX_SUCCESS;
  TX_BYTE_POOL *byte_pool = (TX_BYTE_POOL*)memory_ptr;
   /* USER CODE BEGIN App_NetXDuo_MEM_POOL */
  (void)byte_pool;
  /* USER CODE END App_NetXDuo_MEM_POOL */
  /* USER CODE BEGIN 0 */
        nx_system_initialize();
  /* USER CODE END 0 */

  /* USER CODE BEGIN MX_NetXDuo_Init */
        if (tx_byte_allocate(byte_pool, (VOID **) &pointer,  TX_TASK_PPP_STACK_SIZE, TX_NO_WAIT) != TX_SUCCESS)
  {
                        return TX_POOL_ERROR;
  }
        if (tx_thread_create(&app_task_ppp_tcb, "PPP Task", app_task_ppp, 0, pointer,
                                                                                        APP_CFG_TASK_PPP_STK_SIZE, APP_CFG_TASK_PPP_PRIO, APP_CFG_TASK_PPP_PRIO, TX_NO_TIME_SLICE, TX_AUTO_START) != TX_SUCCESS)
        {
                        ret = TX_THREAD_ERROR;  
        }
        
        if (tx_byte_allocate(byte_pool, (VOID **) &pointer,  TX_TASK_COM_STACK_SIZE, TX_NO_WAIT) != TX_SUCCESS)
  {
                        return TX_POOL_ERROR;
  }
        if (tx_thread_create(&app_task_comtcb, "Com Task", app_task_com, 0, pointer,
                                                                                        APP_CFG_TASK_COM_STK_SIZE, APP_CFG_TASK_COM_PRIO, APP_CFG_TASK_COM_PRIO, TX_NO_TIME_SLICE, TX_AUTO_START) != TX_SUCCESS)
        {
                        ret = TX_THREAD_ERROR;  
        }
        
  /* USER CODE END MX_NetXDuo_Init */
  return ret;
}

/* USER CODE BEGIN 1 */
void netx_ppp_init(void)
{
    CHAR    *pointer;      
    UINT    status;         
    printf("Initializing NetX PPP...\n");
    pointer = (CHAR *)packet_pool_area;
    // 1. 创建数据包池
    status = nx_packet_pool_create(&pool_0,
                                   "NetX Main Packet Pool",
                                   1536,  
                                   pointer,
                                   1024*30);
    if (status) {
        printf("Error creating packet pool: 0x%02x\n", status);
        error_counter++;
        return;
    }
    pointer += 1024*30;  

    // 2. 创建 PPP 实例(2KB 大小)
    status = nx_ppp_create(&ppp_0, "NetX PPP Instance", &ip_0, pointer, 4096, 2,
                          &pool_0, invalid_packet_handler, ppp_0_serial_byte_output);
    if (status) {
        printf("Error creating PPP instance: 0x%02x\n", status);
        error_counter++;
        return;
    }
    pointer += 4096;  // 指针偏移 2KB

    // 3. 配置 PPP IP
    status = nx_ppp_ip_address_assign(&ppp_0, IP_ADDRESS(0,0,0,0), IP_ADDRESS(0,0,0,0));
    if (status) {
        printf("Error assigning PPP IP address: 0x%02x\n", status);
        error_counter++;
        return;
    }

    // 4. 设置 PPP 回调
    status = nx_ppp_link_up_notify(&ppp_0, link_up_callback);   
    status += nx_ppp_link_down_notify(&ppp_0, link_down_callback);
    if (status) {
        printf("Error setting PPP callbacks: 0x%02x\n", status);
        error_counter++;
        return;
    }

    // 5. 启用 PAP 认证
    status = nx_ppp_pap_enable(&ppp_0, generate_login, NX_NULL);
    if (status) {
        printf("Error enabling PPP PAP: 0x%02x\n", status);
        error_counter++;
        return;
    }

    // 6. 创建 IP 实例(2KB 大小)
    status = nx_ip_create(&ip_0, "NetX IP Instance", IP_ADDRESS(0,0,0,0),
                         0xFFFFFF00UL, &pool_0, nx_ppp_driver, pointer, 2048, 1);
    if (status) {
        printf("Error creating IP instance: 0x%02x\n", status);
        error_counter++;
        return;
    }
    pointer += 2048;  // 指针偏移 2KB

    // 启用网络协议
    status = nx_icmp_enable(&ip_0);
    if (status) printf("Error enabling ICMP: 0x%02x\n", status);
               
    status = nx_udp_enable(&ip_0);
    if (status) printf("Error enabling UDP: 0x%02x\n", status);
               
    status = nx_tcp_enable(&ip_0);
    if (status) printf("Error enabling TCP: 0x%02x\n", status);
    printf("NetX PPP initialization completed successfully\n");
}

void app_task_com(ULONG thread_input)
{
    UCHAR byte;               
    uint8_t read_result;      
    ULONG bytes_processed;     
    static ULONG total_ppp_bytes = 0;  

    while(1) {  
        if(ATstate == 1) {  
            bytes_processed = 0;
            while (bytes_processed < 128) {  
                read_result = at_buffer_read(&byte);  
                if (read_result == 1) {
                    nx_ppp_byte_receive(&ppp_0, byte);  
                    bytes_processed++;
                    total_ppp_bytes++;
                } else {
                    break;  
                }
            }
            if (bytes_processed >= 64) {
                tx_thread_sleep(1);
            }
        }
        tx_thread_sleep(1);  
    }
}

void app_task_ppp(ULONG thread_input)
{
    (void)thread_input;   
    ecxx_deal();        
    netx_ppp_init();      
    while(1) {
        netx_http_client_demo();     
        tx_thread_sleep(10000);  
    }
}

void ppp_0_serial_byte_output(UCHAR byte)
{
    at_send_byte(byte);  
}

void invalid_packet_handler(NX_PACKET *packet_ptr)
{
    nx_packet_release(packet_ptr);
}

void link_up_callback(NX_PPP *ppp_ptr)
{
    if (ppp_ptr == &ppp_0) {
        ppp_0_link_up_counter++;  
        printf("[PPP] Link up success! Counter: %lu\n", ppp_0_link_up_counter);  

        ULONG ip_address, network_mask;
        nx_ip_address_get(&ip_0, &ip_address, &network_mask);
        printf("[PPP] Local IP: %lu.%lu.%lu.%lu\n",
               (ip_address >> 24) & 0xFF, (ip_address >> 16) & 0xFF,
               (ip_address >> 8) & 0xFF, ip_address & 0xFF);

        ULONG dns_server;
        nx_ppp_dns_address_get(&ppp_0, &dns_server);
        if (dns_server != 0) {
            printf("[PPP] DNS Server: %lu.%lu.%lu.%lu\n",
                   (dns_server >> 24) & 0xFF, (dns_server >> 16) & 0xFF,
                   (dns_server >> 8) & 0xFF, dns_server & 0xFF);
        }
    }
}

void link_down_callback(NX_PPP *ppp_ptr)
{
    if (ppp_ptr == &ppp_0) {
        ppp_0_link_down_counter++;  
        printf("[PPP] Link down! Counter: %lu\n", ppp_0_link_down_counter);  
    }
    nx_ppp_restart(ppp_ptr);  
}

UINT generate_login(CHAR *name, CHAR *password)
{
    strncpy(name, name_string, NX_PPP_NAME_SIZE - 1);
    strncpy(password, password_string, NX_PPP_PASSWORD_SIZE - 1);
    name[NX_PPP_NAME_SIZE - 1] = '\0';
    password[NX_PPP_PASSWORD_SIZE - 1] = '\0';
    return NX_SUCCESS;
}

// GET请求
UINT http_client_get_request(void)
{
    UINT        status;
    NXD_ADDRESS server_address;
    NX_PACKET   *response_packet;
    UCHAR       receive_buffer[1024];
    ULONG       bytes;
    ULONG       total_bytes = 0;
    UINT        timeout_count = 0;
    const UINT  max_timeout_count = 3;
    ULONG       start_time, current_time;

    server_address.nxd_ip_address.v4 = IP_ADDRESS(8,135,10,183);
    server_address.nxd_ip_version = NX_IP_VERSION_V4;

    printf("[GET] Creating HTTP client...\n");
    status = nx_web_http_client_create(&http_client, "EC200M HTTP Client", &ip_0, &pool_0, 16384);
    if (status != NX_SUCCESS) {
        printf("[GET] Error creating HTTP client: 0x%02x\n", status);
        return status;
    }
    printf("[GET] HTTP client created successfully\n");
    printf("[GET] Starting GET request to %s:%d\n", HTTP_SERVER_URL, HTTP_SERVER_PORT);

    // 显示本地IP
    ULONG local_ip, netmask;
    nx_ip_address_get(&ip_0, &local_ip, &netmask);
    printf("[GET] Local IP: %lu.%lu.%lu.%lu\n",
           (local_ip >> 24) & 0xFF, (local_ip >> 16) & 0xFF,
           (local_ip >> 8) & 0xFF, local_ip & 0xFF);
    start_time = tx_time_get();

    // 使用GET启动函数
    status = nx_web_http_client_get_start(&http_client,
                                         &server_address,
                                         HTTP_SERVER_PORT,
                                         "/",  
                                         HTTP_SERVER_URL,
                                         NX_NULL,
                                         NX_NULL,
                                         10000);  
    if (status != NX_SUCCESS) {
        printf("[GET] Error starting GET request: 0x%02x\n", status);
        nx_web_http_client_delete(&http_client);
        return status;
    }
    printf("[GET] GET request started successfully\n");

    // 接收响应
    while(timeout_count < max_timeout_count)
                {
        current_time = tx_time_get();
        if ((current_time - start_time) > 30000) // 检查总超时(30秒)
                                {
            printf("[GET] Overall timeout after 30 seconds\n");
            status = NX_WEB_HTTP_TIMEOUT;
            break;
        }

        // 接收数据,使用较短超时
        status = nx_web_http_client_response_body_get(&http_client, &response_packet, 3000);
        if (status == NX_WEB_HTTP_GET_DONE) {
            printf("[GET] GET request completed successfully\n");
            status = NX_SUCCESS;
            break;
        }
        else if (status == NX_SUCCESS)
                                {
            timeout_count = 0;
            if (response_packet != NX_NULL) {
                status = nx_packet_data_extract_offset(response_packet,0,receive_buffer,sizeof(receive_buffer)-1,&bytes);
                if(status == NX_SUCCESS && bytes > 0) {
                    receive_buffer[bytes] = 0;
                    total_bytes += bytes;
                    printf("[GET] Received %lu bytes (total: %lu)\n", bytes, total_bytes);
                    printf("=== Response ===\n%s\n=== End Response ===\n", receive_buffer);
                }
                                                                else {
                    printf("[GET] Received empty packet\n");
                }
                nx_packet_release(response_packet);
            }
        }
        else if (status == NX_NO_PACKET)
                                {
            timeout_count++;
            printf("[GET] No packet received (%u/%u), elapsed: %lu ms\n",timeout_count, max_timeout_count, current_time - start_time);
            tx_thread_sleep(500);
        }
        else
                                {
            printf("[GET] Error getting response: 0x%02x, elapsed: %lu ms\n",status, current_time - start_time);
            break;
        }
    }
               
    if (timeout_count >= max_timeout_count) {
        printf("[GET] Timeout after %d retries, total time: %lu ms\n",max_timeout_count, tx_time_get() - start_time);
        status = NX_WEB_HTTP_TIMEOUT;
    }
    printf("[GET] Completed. Total received: %lu bytes, Status: 0x%02x\n", total_bytes, status);
    nx_web_http_client_delete(&http_client);
    return status;
}


// POST请求
UINT http_client_simple_post(CHAR *path, const CHAR *content_type, const CHAR *data, ULONG data_length)
{
    UINT status;
    NXD_ADDRESS server_address;
    NX_PACKET *request_packet;
    ULONG start_time;

    printf("[POST] Starting simple POST...\n");
        
    // 设置服务器地址
    server_address.nxd_ip_address.v4 = IP_ADDRESS(8,135,10,183);
    server_address.nxd_ip_version = NX_IP_VERSION_V4;

    // 创建HTTP客户端
    status = nx_web_http_client_create(&http_client, "EC200M HTTP Client",&ip_0, &pool_0, 16384);
    if (status != NX_SUCCESS) {
        printf("[POST] Error creating client: 0x%02x\n", status);
        return status;
    }

    // 连接到服务器
    status = nx_web_http_client_connect(&http_client, &server_address, HTTP_SERVER_PORT, 10000);
    if (status != NX_SUCCESS) {
        printf("[POST] Error connecting to server: 0x%02x\n", status);
        nx_web_http_client_delete(&http_client);
        return status;
    }

    // 构建头部
    CHAR additional_headers[128];
    snprintf(additional_headers, sizeof(additional_headers),
             "Content-Type: %s\r\nContent-Length: %lu",
             content_type, data_length);

    // 创建数据包
    status = nx_packet_allocate(&pool_0, &request_packet, NX_TCP_PACKET, NX_WAIT_FOREVER);
    if (status != NX_SUCCESS) {
        printf("[POST] Error allocating packet: 0x%02x\n", status);
        nx_web_http_client_delete(&http_client);
        return status;
    }

    // 填充数据
    status = nx_packet_data_append(request_packet, (VOID *)data, data_length, &pool_0, NX_WAIT_FOREVER);
    if (status != NX_SUCCESS) {
        printf("[POST] Error appending data: 0x%02x\n", status);
        nx_packet_release(request_packet);
        nx_web_http_client_delete(&http_client);
        return status;
    }

    // 初始化POST请求
    status = nx_web_http_client_request_initialize(&http_client,
                                                  NX_WEB_HTTP_METHOD_POST,
                                                  path,
                                                  HTTP_SERVER_URL,
                                                  data_length,
                                                  NX_FALSE,
                                                  NX_NULL,
                                                  NX_NULL,
                                                  NX_WAIT_FOREVER);
    if (status != NX_SUCCESS) {
        printf("[POST] Error initializing request: 0x%02x\n", status);
        nx_packet_release(request_packet);
        nx_web_http_client_delete(&http_client);
        return status;
    }
               
    start_time = tx_time_get();

    // 发送请求头部
    status = nx_web_http_client_request_send(&http_client, 10000);
    if (status != NX_SUCCESS) {
        printf("[POST] Error sending headers: 0x%02x\n", status);
        nx_packet_release(request_packet);
        nx_web_http_client_delete(&http_client);
        return status;
    }

    // 发送数据包
    status = nx_web_http_client_request_packet_send(&http_client, request_packet, NX_FALSE, NX_WAIT_FOREVER);
    if (status != NX_SUCCESS) {
        printf("[POST] Error sending data: 0x%02x\n", status);
        nx_packet_release(request_packet);
        nx_web_http_client_delete(&http_client);
        return status;
    }
    printf("[POST] Request sent, waiting for response...\n");

    // 获取响应
    NX_PACKET *response_packet = NX_NULL;
    UCHAR buffer[512];
    ULONG bytes = 0;
    UINT timeout_count = 0;

    while (timeout_count < 3)
                {
        status = nx_web_http_client_response_body_get(&http_client, &response_packet,NX_WAIT_FOREVER);
        if (status == NX_WEB_HTTP_GET_DONE) {
            printf("[POST] Request completed successfully\n");
            status = NX_SUCCESS;
            break;
        } else if (status == NX_SUCCESS && response_packet != NX_NULL) {
            nx_packet_data_extract_offset(response_packet, 0, buffer, sizeof(buffer)-1, &bytes);
            if (bytes > 0) {
                buffer[bytes] = '\0';
                printf("[POST] Response (%lu bytes): %s\n", bytes, buffer);
            }
            nx_packet_release(response_packet);
            status = NX_SUCCESS;
            break;
        } else if (status == NX_NO_PACKET) {
            timeout_count++;
            printf("[POST] No response (%u/3)\n", timeout_count);
            tx_thread_sleep(1000);
        } else {
            printf("[POST] Error: 0x%02x\n", status);
            break;
        }

        if ((tx_time_get() - start_time) > 30000) {
            printf("[POST] Overall timeout\n");
            status = NX_WEB_HTTP_TIMEOUT;
            break;
        }
    }
               
    if (timeout_count >= 3) {
        printf("[POST] Response timeout\n");
        status = NX_WEB_HTTP_TIMEOUT;
    }

    nx_web_http_client_delete(&http_client);
    printf("[POST] Completed with status: 0x%02x\n", status);
    return status;
}

// 主测试函数
void netx_http_client_demo(void)
{
    UINT status;
    tx_thread_sleep(10000);
    http_request_counter++;
    if (http_request_counter % 2 == 0)
                {
        printf("\n=== Testing GET Request ===\n");
        status = http_client_get_request();
        if (status == NX_SUCCESS) {
            printf("GET request completed successfully\n");
        } else {
            printf("GET request failed: 0x%02x\n", status);
        }
    }
                else
                {
        printf("\n=== Testing POST Request ===\n");
        CHAR json_data[128];
        snprintf(json_data, sizeof(json_data),"{\"device\":\"EC200M\",\"temp\":25.5,\"counter\":%lu}",http_request_counter);
        status = http_client_simple_post(POST_API_PATH, "application/json",json_data, strlen(json_data));
        if (status == NX_SUCCESS) {
            printf("POST request completed successfully\n");
        } else {
            printf("POST request failed: 0x%02x\n", status);
        }
    }
    tx_thread_sleep(5000);
}

/* USER CODE END 1 *//* USER CODE END 1 */
咨询http接收问题,接收不到返回的内容



回复

使用道具 举报

1万

主题

7万

回帖

12万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
120448
QQ
发表于 2025-11-24 10:42:09 | 显示全部楼层
帮顶
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|手机版|硬汉嵌入式论坛

GMT+8, 2026-1-10 17:29 , Processed in 0.050125 second(s), 25 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表