79 lines
2.1 KiB
C
79 lines
2.1 KiB
C
#include "main.h"
|
|
#include "cmsis_os.h"
|
|
#include "lwip.h"
|
|
|
|
/* Private includes ----------------------------------------------------------*/
|
|
/* USER CODE BEGIN Includes */
|
|
#include "string.h"
|
|
#include "stm32h7xx_hal.h"
|
|
#include "stm32h7xx_it.h"
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
#include <lwip/sockets.h>
|
|
#include "lwip/sys.h"
|
|
#include "lwip/api.h"
|
|
|
|
#include "IAP/iap.h"
|
|
#include "udpp.h"
|
|
|
|
|
|
int udpSendTo(uint8_t *buf, int len, char *addr, uint16_t port);
|
|
|
|
|
|
int udpSendBigPacket(uint8_t *buf, int len, char *addr, uint16_t port)
|
|
{
|
|
// 参数检查
|
|
if (buf == NULL || len <= 0 || len > UDP_MAX_TOTAL_SIZE || addr == NULL) {
|
|
return -1;
|
|
}
|
|
|
|
// 生成随机大包ID
|
|
uint32_t big_packet_id = (uint32_t)rand();
|
|
|
|
// 计算需要的包数量
|
|
int total_packets = (len + UDP_MAX_PAYLOAD_SIZE - 1) / UDP_MAX_PAYLOAD_SIZE;
|
|
|
|
// 分配发送缓冲区
|
|
static uint8_t send_buf[UDP_MAX_PACKET_SIZE];
|
|
|
|
int result = 0;
|
|
int offset = 0;
|
|
|
|
// 逐个发送包
|
|
for (int packet_id = 0; packet_id < total_packets; packet_id++) {
|
|
// 准备包头
|
|
udp_packet_header_t *header = (udp_packet_header_t *)send_buf;
|
|
header->magic = UDP_PACKET_MAGIC;
|
|
header->total_size = len;
|
|
header->big_packet_id = big_packet_id;
|
|
header->packet_id = packet_id;
|
|
header->total_packets = total_packets;
|
|
|
|
// 计算当前包的有效载荷长度
|
|
int remaining_data = len - offset;
|
|
int payload_len = (remaining_data > UDP_MAX_PAYLOAD_SIZE) ? UDP_MAX_PAYLOAD_SIZE : remaining_data;
|
|
header->payload_len = payload_len;
|
|
|
|
// 填充保留字段为0
|
|
memset(header->reserved, 0, sizeof(header->reserved));
|
|
|
|
// 复制数据到发送缓冲区
|
|
memcpy(send_buf + UDP_HEADER_SIZE, buf + offset, payload_len);
|
|
|
|
// 发送包
|
|
int send_len = UDP_HEADER_SIZE + payload_len;
|
|
int send_result = udpSendTo(send_buf, send_len, addr, port);
|
|
|
|
if (send_result < 0) {
|
|
result = send_result;
|
|
break;
|
|
}
|
|
|
|
offset += payload_len;
|
|
osDelay(5);
|
|
}
|
|
|
|
return result;
|
|
}
|