初始提交
This commit is contained in:
@@ -0,0 +1,766 @@
|
||||
#include "cmsis_os.h"
|
||||
#include "adc.h"
|
||||
#include "GPIO_HAL/gpioHal.h"
|
||||
#include "main.h"
|
||||
#include "Param/param.h"
|
||||
#include "IAP/iap.h"
|
||||
|
||||
#include <lwip/sockets.h>
|
||||
#include "lwip/sys.h"
|
||||
#include "lwip/api.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "UDP/udpp.h"
|
||||
|
||||
extern TIM_HandleTypeDef htim3;
|
||||
extern TIM_HandleTypeDef htim1;
|
||||
extern ADC_HandleTypeDef hadc1;
|
||||
extern ADC_HandleTypeDef hadc2;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
WORK_MODE_IDLE = 0,
|
||||
WORK_MODE_CMD_SAMPLE,
|
||||
WORK_MODE_PIN_SAMPLE,
|
||||
WORK_MODE_SEND_DATA,
|
||||
WORK_MODE_WAIT,
|
||||
} WORK_MODE_DEF;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
ADC_TRIG_NONE = 0,
|
||||
ADC_TRIG_TIM3,
|
||||
ADC_TRIG_TIM1_1,
|
||||
ADC_TRIG_TIM1_2,
|
||||
} ADC_TRIG_DEF;
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __transferPacketDef
|
||||
{
|
||||
uint16_t usHeaderA;
|
||||
uint16_t usHeaderB;
|
||||
uint16_t usQueueRemainDataLen;
|
||||
uint16_t usLen;
|
||||
adcDataUnitDef atData[PACKET_DATA_UNIT_NUM];
|
||||
} transferPacketDef;
|
||||
#pragma pack()
|
||||
|
||||
static transferPacketDef _gtTmpPkt;
|
||||
|
||||
uint32_t _gaulAdcValue[2];
|
||||
int _gaiFlag[2];
|
||||
|
||||
volatile uint32_t _gulSamplePosUm = 0;
|
||||
volatile uint32_t _gulSampleTimeUs = 0;
|
||||
volatile adcDataQueueDef gtAdcDataQueue;
|
||||
volatile uint32_t gulAdcSampleIndex;
|
||||
volatile uint32_t ulSampleStartTime = 0;
|
||||
volatile uint32_t ulSampleDuration = 0;
|
||||
volatile int _iWorkMode = WORK_MODE_IDLE;
|
||||
|
||||
typedef struct {
|
||||
uint32_t ulTick;
|
||||
uint32_t ulCnt;
|
||||
} tickTimeDef;
|
||||
|
||||
|
||||
volatile int32_t _gslEncCnt = 0;
|
||||
tickTimeDef _gtLastTrigTime;
|
||||
int _giEncoderTrigFlag = 0;
|
||||
uint32_t gulEncoderSpeed = 0; /// 0.1mm/s
|
||||
|
||||
int giScanDirection = 0;
|
||||
|
||||
uint32_t gulPacketIndex = 0;
|
||||
uint32_t gulPacketAck = 0;
|
||||
|
||||
static void resetAdcDataQueue(void);
|
||||
int net_print(const char *format, ...);
|
||||
static int sendDataPacket(uint8_t *pucData, uint16_t usLen);
|
||||
|
||||
//#define NET_PRINT(fmt, args...) net_print(fmt, ##args)
|
||||
#define NET_PRINT(fmt, args...)
|
||||
|
||||
static uint32_t getEncoderPos(uint32_t ulVal)
|
||||
{
|
||||
uint32_t ulPos = ulVal;
|
||||
if (ulPos >= 10000) {
|
||||
ulPos -= 10000;
|
||||
} else {
|
||||
ulPos = 10000 - ulPos;
|
||||
}
|
||||
|
||||
ulPos += (_gslEncCnt * 1000);
|
||||
|
||||
return ulPos;
|
||||
}
|
||||
|
||||
static void _readChannel(void)
|
||||
{
|
||||
uint32_t ulTime = _gulSampleTimeUs;
|
||||
uint32_t ulData1 = _gaulAdcValue[0];
|
||||
uint32_t ulData2 = _gaulAdcValue[1];
|
||||
|
||||
adcDataUnitDef *ptData = >AdcDataQueue.atQueue[gtAdcDataQueue.ulWritePos];
|
||||
|
||||
gulAdcSampleIndex++;
|
||||
|
||||
if (gulAdcSampleIndex >= 5) {
|
||||
ptData->aulData[0] = ulData1;
|
||||
ptData->aulData[1] = ulData2;
|
||||
// ptData->ulTime = ulTime;
|
||||
// ptData->ulPos = _gulSamplePosUm;
|
||||
|
||||
gtAdcDataQueue.ulWritePos++;
|
||||
if (gtAdcDataQueue.ulWritePos >= ADC_QUEUE_LEN) {
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void tim3PeriodInit(uint32_t ulPeriod)
|
||||
{
|
||||
htim3.Init.Period = ulPeriod - 1;
|
||||
|
||||
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
}
|
||||
|
||||
static void resetAdcDataQueue(void)
|
||||
{
|
||||
gtAdcDataQueue.ulReadPos = 0;
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
|
||||
static uint16_t getBufferedDataLength(void)
|
||||
{
|
||||
uint16_t ulLength = 0;
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos == gtAdcDataQueue.ulReadPos) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos > gtAdcDataQueue.ulReadPos)
|
||||
{
|
||||
ulLength = gtAdcDataQueue.ulWritePos - gtAdcDataQueue.ulReadPos;
|
||||
}
|
||||
else
|
||||
{
|
||||
ulLength = ADC_QUEUE_LEN - gtAdcDataQueue.ulReadPos + gtAdcDataQueue.ulWritePos;
|
||||
}
|
||||
|
||||
return ulLength;
|
||||
}
|
||||
|
||||
static void base64_encode(const unsigned char *input, size_t input_len, char *output)
|
||||
{
|
||||
static const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
int i = 0, j = 0;
|
||||
unsigned char char_array_3[3], char_array_4[4];
|
||||
|
||||
while (input_len--)
|
||||
{
|
||||
char_array_3[i++] = *(input++);
|
||||
if (i == 3)
|
||||
{
|
||||
char_array_4[0] = (char_array_3[0] >> 2) & 0x3F;
|
||||
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) | (char_array_3[1] >> 4);
|
||||
char_array_4[2] = ((char_array_3[1] & 0x0F) << 2) | (char_array_3[2] >> 6);
|
||||
char_array_4[3] = char_array_3[2] & 0x3F;
|
||||
|
||||
for (i = 0; i < 4; i++)
|
||||
{
|
||||
output[j++] = base64_table[char_array_4[i]];
|
||||
}
|
||||
i = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (i)
|
||||
{
|
||||
for (int k = i; k < 3; k++)
|
||||
{
|
||||
char_array_3[k] = '\0';
|
||||
}
|
||||
|
||||
char_array_4[0] = (char_array_3[0] >> 2) & 0x3F;
|
||||
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) | (char_array_3[1] >> 4);
|
||||
char_array_4[2] = ((char_array_3[1] & 0x0F) << 2) | (char_array_3[2] >> 6);
|
||||
char_array_4[3] = char_array_3[2] & 0x3F;
|
||||
|
||||
for (int k = 0; k < i + 1; k++)
|
||||
{
|
||||
output[j++] = base64_table[char_array_4[k]];
|
||||
}
|
||||
|
||||
while (i++ < 3)
|
||||
{
|
||||
output[j++] = '=';
|
||||
}
|
||||
}
|
||||
output[j] = '\0'; // Null-terminate the output string
|
||||
}
|
||||
|
||||
int tcpSendTo(uint8_t *buf, int len, char *addr, uint16_t port) {
|
||||
int sockfd;
|
||||
struct sockaddr_in tcpToAddr;
|
||||
int res;
|
||||
|
||||
// 创建 TCP 套接字
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd < 0) {
|
||||
perror("socket creation failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 设置目标地址
|
||||
memset(&tcpToAddr, 0, sizeof(tcpToAddr));
|
||||
tcpToAddr.sin_family = AF_INET;
|
||||
inet_pton(AF_INET, addr, &tcpToAddr.sin_addr.s_addr);
|
||||
tcpToAddr.sin_port = htons(port);
|
||||
|
||||
// 建立连接
|
||||
if (connect(sockfd, (struct sockaddr *)&tcpToAddr, sizeof(tcpToAddr)) < 0) {
|
||||
perror("connection failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 发送数据
|
||||
res = send(sockfd, buf, len, 0);
|
||||
if (res < 0) {
|
||||
perror("send failed");
|
||||
close(sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 关闭连接
|
||||
close(sockfd);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// net_print 函数实现
|
||||
int net_print(const char *format, ...) {
|
||||
// 定义一个足够大的缓冲区来存放格式化后的字符串
|
||||
char buffer[1024]; // 根据需要调整大小
|
||||
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
|
||||
// 使用 vsnprintf 格式化输出到 buffer
|
||||
int len = vsnprintf(buffer, sizeof(buffer), format, args);
|
||||
va_end(args);
|
||||
|
||||
// 检查输出长度是否超出缓冲区
|
||||
if (len < 0 || len >= sizeof(buffer)) {
|
||||
// 格式化失败或输出过长
|
||||
return -1;
|
||||
}
|
||||
if (buffer[len - 1] != '\n') {
|
||||
buffer[len] = '\n';
|
||||
len++;
|
||||
}
|
||||
|
||||
printf(buffer);
|
||||
// 发送数据包
|
||||
udpSendTo((uint8_t *)buffer, (uint16_t)len,
|
||||
"192.168.100.100",
|
||||
50009);
|
||||
}
|
||||
|
||||
void adcDataPacketAck(uint32_t ulPid)
|
||||
{
|
||||
gulPacketAck = ulPid;
|
||||
}
|
||||
|
||||
static int sendDataPacket(uint8_t *pucData, uint16_t usLen)
|
||||
{
|
||||
char *dir = "unknown";
|
||||
static char aucBase64Buf[45 * 1024];
|
||||
static char aucUdpBuf[63 * 1024];
|
||||
|
||||
if (usLen <= 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (usLen > 41 * 1024)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
gulPacketIndex++;
|
||||
|
||||
memset(aucBase64Buf, 0, sizeof(aucBase64Buf));
|
||||
memset(aucUdpBuf, 0, sizeof(aucUdpBuf));
|
||||
|
||||
base64_encode(pucData, usLen, aucBase64Buf);
|
||||
if (giScanDirection == 10) {
|
||||
dir = "up";
|
||||
} else if (giScanDirection == -10) {
|
||||
dir = "down";
|
||||
}
|
||||
snprintf(aucUdpBuf, sizeof(aucUdpBuf),
|
||||
"{\"type\":\"data_points\",\"name\":\"daq\",\"ip\":\"%s\",\"direction\":\"%s\",\"pid\":%u,\"data\":\"%s\"}",
|
||||
gptSysParam->acIp,
|
||||
dir, gulPacketIndex,
|
||||
aucBase64Buf);
|
||||
|
||||
gulPacketAck = 0;
|
||||
|
||||
if (gptSysParam->ucTestMode) {
|
||||
NET_PRINT("to send data:%d\n", strlen(aucUdpBuf) + 1);
|
||||
udpSendTo(aucUdpBuf, strlen(aucUdpBuf) + 1,
|
||||
"192.168.100.100",
|
||||
50009);
|
||||
osDelay(100);
|
||||
}
|
||||
|
||||
udpSendBigPacket(aucUdpBuf, strlen(aucUdpBuf) + 1,
|
||||
"192.168.100.10",
|
||||
50009);
|
||||
|
||||
osDelay(500);
|
||||
|
||||
if (gulPacketAck != gulPacketIndex) {
|
||||
printf("noack retry \r\n");
|
||||
udpSendBigPacket(aucUdpBuf, strlen(aucUdpBuf) + 1,
|
||||
"192.168.100.10",
|
||||
50009);
|
||||
} else {
|
||||
printf("send ok \r\n");
|
||||
}
|
||||
|
||||
return usLen;
|
||||
}
|
||||
|
||||
static int makeDataPacket(void)
|
||||
{
|
||||
uint16_t ulPos = 0;
|
||||
uint16_t i = 0;
|
||||
uint16_t ulLen = getBufferedDataLength();
|
||||
uint16_t send_size = 0;
|
||||
|
||||
if (ulLen < 5)
|
||||
{
|
||||
NET_PRINT("not enouth len:%d\r\n", ulLen);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = 0; i < ulLen; ++i)
|
||||
{
|
||||
ulPos = gtAdcDataQueue.ulReadPos + i;
|
||||
if (ulPos >= ADC_QUEUE_LEN)
|
||||
{
|
||||
ulPos -= ADC_QUEUE_LEN;
|
||||
}
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[ulPos];
|
||||
memcpy(&_gtTmpPkt.atData[i], (uint8_t *)ptData, sizeof(adcDataUnitDef));
|
||||
}
|
||||
|
||||
_gtTmpPkt.usHeaderA = 0xAA55;
|
||||
_gtTmpPkt.usHeaderB = 0x55CC;
|
||||
_gtTmpPkt.usQueueRemainDataLen = 0x00;
|
||||
_gtTmpPkt.usLen = ulLen;
|
||||
NET_PRINT("_gtTmpPkt.usLen : %d , _gtTmpPkt.usQueueRemainDataLen : %d \r\n", _gtTmpPkt.usLen, _gtTmpPkt.usQueueRemainDataLen);
|
||||
|
||||
send_size = 8 + sizeof(adcDataUnitDef) * ulLen;
|
||||
|
||||
return send_size;
|
||||
}
|
||||
|
||||
void adcTriggerSelect(ADC_TRIG_DEF trigger)
|
||||
{
|
||||
switch (trigger) {
|
||||
case ADC_TRIG_NONE:
|
||||
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
|
||||
hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
|
||||
break;
|
||||
case ADC_TRIG_TIM3:
|
||||
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T3_TRGO;
|
||||
hadc2.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T3_TRGO;
|
||||
break;
|
||||
case ADC_TRIG_TIM1_1:
|
||||
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO;
|
||||
hadc2.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO;
|
||||
break;
|
||||
case ADC_TRIG_TIM1_2:
|
||||
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO2;
|
||||
hadc2.Init.ExternalTrigConv = ADC_EXTERNALTRIG_T1_TRGO2;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
HAL_ADC_Init(&hadc1);
|
||||
HAL_ADC_Init(&hadc2);
|
||||
}
|
||||
|
||||
|
||||
void _sampleStart(void)
|
||||
{
|
||||
__disable_irq();
|
||||
resetAdcDataQueue();
|
||||
|
||||
gulAdcSampleIndex = 0;
|
||||
ulSampleStartTime = osKernelGetTickCount();
|
||||
__enable_irq();
|
||||
_gslEncCnt = 0;
|
||||
|
||||
if (gptSysParam->usDdc112Period > 300) {
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_4);
|
||||
HAL_TIM_Base_Start_IT(&htim3);
|
||||
} else {
|
||||
HAL_TIM_Base_Stop_IT(&htim3);
|
||||
TIM1->CNT = 10000;
|
||||
HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_4);
|
||||
printf("start encoder\n");
|
||||
}
|
||||
}
|
||||
|
||||
void _sampleStop(void)
|
||||
{
|
||||
if (gptSysParam->usDdc112Period > 300) {
|
||||
HAL_TIM_Base_Stop_IT(&htim3);
|
||||
} else {
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_4);
|
||||
_giEncoderTrigFlag = 0;
|
||||
}
|
||||
if (gptSysParam->ucTestMode == 0) {
|
||||
HAL_GPIO_WritePin(RELAY_GPIO_Port, RELAY_Pin, GPIO_PIN_RESET);
|
||||
}
|
||||
}
|
||||
|
||||
void mcuAdcInit(void)
|
||||
{
|
||||
adcUpdateParam();
|
||||
|
||||
// HAL_ADC_Start_DMA(&hadc1, (uint32_t *)(&ADCxValues[64]), 128);
|
||||
// HAL_ADC_Start_DMA(&hadc2, (uint32_t *)(&ADCxValues[80]), 128);
|
||||
|
||||
HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED);
|
||||
HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET_LINEARITY, ADC_SINGLE_ENDED);
|
||||
|
||||
HAL_ADCEx_Calibration_Start(&hadc2, ADC_CALIB_OFFSET, ADC_SINGLE_ENDED);
|
||||
HAL_ADCEx_Calibration_Start(&hadc2, ADC_CALIB_OFFSET_LINEARITY, ADC_SINGLE_ENDED);
|
||||
|
||||
// HAL_ADC_Start(&hadc1);
|
||||
// HAL_ADC_Start(&hadc2);
|
||||
|
||||
// HAL_ADC_Start_IT(&hadc1);
|
||||
// HAL_ADC_Start_IT(&hadc2);
|
||||
|
||||
printf("adc start\r\n");
|
||||
}
|
||||
|
||||
int adcSampleStart(uint16_t delay, uint32_t ulDuration, uint8_t dir)
|
||||
{
|
||||
if (_iWorkMode == WORK_MODE_IDLE) {
|
||||
HAL_GPIO_WritePin(RELAY_GPIO_Port, RELAY_Pin, GPIO_PIN_SET);
|
||||
if (delay > 0) {
|
||||
osDelay(delay);
|
||||
}
|
||||
if (dir == 1) {
|
||||
giScanDirection = 10;
|
||||
} else if (dir == 2) {
|
||||
giScanDirection = -10;
|
||||
} else {
|
||||
giScanDirection = 0;
|
||||
}
|
||||
_sampleStart();
|
||||
_iWorkMode = WORK_MODE_CMD_SAMPLE;
|
||||
printf("ddc112Start\r\n");
|
||||
ulSampleDuration = ulDuration;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int adcSampleStop(void)
|
||||
{
|
||||
if (_iWorkMode == 1)
|
||||
{
|
||||
_iWorkMode = 0;
|
||||
_sampleStop();
|
||||
printf("ddc112Stop\r\n");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int giAdcThreadStatus = 0;
|
||||
static void sample_task(void *arg)
|
||||
{
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
|
||||
osDelay(500);
|
||||
|
||||
while (1)
|
||||
{
|
||||
switch (_iWorkMode)
|
||||
{
|
||||
case WORK_MODE_IDLE: // 空闲状态
|
||||
if (gptSysParam->usPinSampleTime > 0) {
|
||||
if (HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_8) == GPIO_PIN_RESET)
|
||||
{
|
||||
HAL_GPIO_WritePin(RELAY_GPIO_Port, RELAY_Pin, GPIO_PIN_SET);
|
||||
if (gptSysParam->usPinSampleDelay > 0) {
|
||||
osDelay(gptSysParam->usPinSampleDelay);
|
||||
}
|
||||
ulSampleDuration = gptSysParam->usPinSampleTime;
|
||||
if (ulSampleDuration > 8000) {
|
||||
ulSampleDuration = 8000;
|
||||
}
|
||||
_sampleStart();
|
||||
_iWorkMode = WORK_MODE_PIN_SAMPLE;
|
||||
}
|
||||
}
|
||||
giAdcThreadStatus = 0;
|
||||
break;
|
||||
case WORK_MODE_CMD_SAMPLE: // 命令采样状态
|
||||
case WORK_MODE_PIN_SAMPLE: // 引脚采样状态
|
||||
if ((getBufferedDataLength() >= ulSampleDuration) || (osKernelGetTickCount() > ulSampleStartTime + ulSampleDuration * 2))
|
||||
{
|
||||
_sampleStop();
|
||||
_iWorkMode = WORK_MODE_SEND_DATA;
|
||||
NET_PRINT("sample timeout \r\n");
|
||||
NET_PRINT("sample data length: %d\r\n", getBufferedDataLength());
|
||||
}
|
||||
else if (getBufferedDataLength() > PACKET_DATA_UNIT_NUM)
|
||||
{
|
||||
_sampleStop();
|
||||
_iWorkMode = WORK_MODE_SEND_DATA;
|
||||
NET_PRINT("sample data length: %d\r\n", getBufferedDataLength());
|
||||
}
|
||||
break;
|
||||
case WORK_MODE_SEND_DATA: // 发送数据状态
|
||||
{
|
||||
int ret = makeDataPacket();
|
||||
if (ret > 0)
|
||||
{
|
||||
sendDataPacket((uint8_t *)&_gtTmpPkt, ret);
|
||||
}
|
||||
resetAdcDataQueue();
|
||||
_iWorkMode = WORK_MODE_WAIT;
|
||||
giScanDirection = 0;
|
||||
}
|
||||
break;
|
||||
case WORK_MODE_WAIT: // 发送数据状态
|
||||
{
|
||||
if (gptSysParam->usPinSampleTime == 0) {
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
} else if (HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_8) == GPIO_PIN_SET) {
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
osDelay(1);
|
||||
}
|
||||
}
|
||||
|
||||
void aimSpeedSet(uint16_t usPeriod)
|
||||
{
|
||||
TIM_OC_InitTypeDef sConfigOC = {0};
|
||||
sConfigOC.OCMode = TIM_OCMODE_TIMING;
|
||||
sConfigOC.Pulse = 10000 - usPeriod;
|
||||
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
|
||||
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
sConfigOC.Pulse = 10000 + usPeriod;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
TIM1->CNT = 10000;
|
||||
}
|
||||
|
||||
void adcUpdateParam(void)
|
||||
{
|
||||
if (gptSysParam->usDdc112Period < 300) {
|
||||
aimSpeedSet(gptSysParam->usDdc112Period);
|
||||
} else {
|
||||
tim3PeriodInit(gptSysParam->usDdc112Period);
|
||||
}
|
||||
}
|
||||
|
||||
void sampleInit(void)
|
||||
{
|
||||
htim1.Instance->CNT = 10000;
|
||||
HAL_TIM_Base_Start(&htim1);
|
||||
|
||||
mcuAdcInit();
|
||||
printf("adc period: %d\r\n", gptSysParam->usDdc112Period);
|
||||
|
||||
// 创建任务
|
||||
const osThreadAttr_t sample_task_attributes = {
|
||||
.name = "sample_task",
|
||||
.stack_size = 4096 * 4,
|
||||
.priority = (osPriority_t)osPriorityNormal,
|
||||
};
|
||||
if (osThreadNew(sample_task, NULL, &sample_task_attributes) == NULL)
|
||||
{
|
||||
printf("failed to create sample_task\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("create sample_task success\n");
|
||||
}
|
||||
|
||||
|
||||
// HAL_TIM_Base_Stop_IT(&htim3);
|
||||
TIM1->CNT = 10000;
|
||||
HAL_TIM_Encoder_Start(&htim1, TIM_CHANNEL_ALL);
|
||||
// HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_3);
|
||||
// HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_4);
|
||||
}
|
||||
|
||||
void TIM3_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
// printf("TIM3 %d %d\n", uwTick, TIM13->CNT);
|
||||
HAL_ADC_Start_IT(&hadc1);
|
||||
HAL_ADC_Start_IT(&hadc2);
|
||||
_gaiFlag[0] = 0;
|
||||
_gaiFlag[1] = 0;
|
||||
}
|
||||
|
||||
uint32_t getDeltaTime(tickTimeDef *last, tickTimeDef *now)
|
||||
{
|
||||
if (last->ulTick == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (now->ulTick < last->ulTick) {
|
||||
return 0;
|
||||
} else if (now->ulTick == last->ulTick) {
|
||||
if (now->ulCnt < last->ulCnt) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return (now->ulTick - last->ulTick) * 1000 + (now->ulCnt - last->ulCnt);
|
||||
}
|
||||
|
||||
void channelHandler(uint32_t ulVal)
|
||||
{
|
||||
tickTimeDef tim;
|
||||
_gulSampleTimeUs = TIM13->CNT;
|
||||
_gulSampleTimeUs += uwTick * 1000;
|
||||
_gulSamplePosUm = getEncoderPos(ulVal);
|
||||
|
||||
if (ulVal > 10000) {
|
||||
if (gptSysParam->ucFilterMode == 0) {
|
||||
if ((giScanDirection >= 0) && (giScanDirection < 10)) {
|
||||
giScanDirection++;
|
||||
}
|
||||
} else {
|
||||
if ((giScanDirection <= 0) && (giScanDirection > -10)) {
|
||||
giScanDirection--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ulVal < 10000) {
|
||||
if (gptSysParam->ucFilterMode == 0) {
|
||||
if ((giScanDirection <= 0) && (giScanDirection > -10)) {
|
||||
giScanDirection--;
|
||||
}
|
||||
} else {
|
||||
if ((giScanDirection >= 0) && (giScanDirection < 10)) {
|
||||
giScanDirection++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (1/*_giEncoderTrigFlag > 10*/) {
|
||||
_gaiFlag[0] = 0;
|
||||
_gaiFlag[1] = 0;
|
||||
HAL_ADC_Start_IT(&hadc1);
|
||||
HAL_ADC_Start_IT(&hadc2);
|
||||
}
|
||||
|
||||
tim.ulCnt = TIM13->CNT;
|
||||
tim.ulTick = uwTick;
|
||||
|
||||
uint32_t ulTim = getDeltaTime(&_gtLastTrigTime, &tim);
|
||||
|
||||
if (ulTim > 0) {
|
||||
gulEncoderSpeed = gptSysParam->usDdc112Period * 10000 / ulTim;
|
||||
}
|
||||
|
||||
if (gulEncoderSpeed >= gptSysParam->usDdc112Period * 10 * 8 / 10) {
|
||||
if (_giEncoderTrigFlag < 100) {
|
||||
_giEncoderTrigFlag++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// printf("pulse 40, %u, flag %d\n", gulEncoderSpeed, _giEncoderTrigFlag);
|
||||
|
||||
_gtLastTrigTime = tim;
|
||||
}
|
||||
|
||||
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
if (htim->Instance == TIM1) {
|
||||
uint32_t ulVal = TIM1->CNT;
|
||||
#if 0
|
||||
uint32_t ulTmp = 10000;
|
||||
if (ulVal >= (10000 + gptSysParam->usDdc112Period)) {
|
||||
ulTmp = ulVal - gptSysParam->usDdc112Period;
|
||||
} else if (ulVal <= (10000 - gptSysParam->usDdc112Period)) {
|
||||
ulTmp = gptSysParam->usDdc112Period + ulVal;
|
||||
} else {
|
||||
printf("%d, %u\n", htim->Channel ,ulVal);
|
||||
return;
|
||||
}
|
||||
TIM1->CNT = ulTmp;
|
||||
#else
|
||||
TIM1->CNT = 10000;
|
||||
++_gslEncCnt;
|
||||
#endif
|
||||
channelHandler(ulVal);
|
||||
} else if (htim == &htim3) {
|
||||
// gulAdcSampleIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
|
||||
{
|
||||
// uint32_t ulVal = TIM1->CNT;
|
||||
if (hadc == &hadc1) {
|
||||
// HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_10);
|
||||
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);
|
||||
_gaulAdcValue[0] = HAL_ADC_GetValue(&hadc1);
|
||||
_gaiFlag[0] = 1;
|
||||
} else if (hadc == &hadc2) {
|
||||
// HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_10);
|
||||
// HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);
|
||||
_gaulAdcValue[1] = HAL_ADC_GetValue(&hadc2);
|
||||
_gaiFlag[1] = 1;
|
||||
}
|
||||
|
||||
if (_gaiFlag[0] && _gaiFlag[1]) {
|
||||
_readChannel();
|
||||
// printf("%d, %u\n", _gslEncCnt * 40, ulVal);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef ADC_H
|
||||
#define ADC_H
|
||||
|
||||
#include "main.h"
|
||||
|
||||
#define ADC_CHANNEL_NUM 2
|
||||
#define ADC_QUEUE_LEN 10000
|
||||
#define PACKET_DATA_UNIT_NUM 6000
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __adcDataUnitDef {
|
||||
uint16_t aulData[ADC_CHANNEL_NUM];
|
||||
// uint32_t ulTime;
|
||||
// uint32_t ulPos;
|
||||
} adcDataUnitDef;
|
||||
|
||||
typedef struct __adcDataQueueDef {
|
||||
uint32_t ulReadPos;
|
||||
uint32_t ulWritePos;
|
||||
adcDataUnitDef atQueue[ADC_QUEUE_LEN];
|
||||
} adcDataQueueDef;
|
||||
#pragma pack()
|
||||
|
||||
void sampleInit(void);
|
||||
int adcSampleStart(uint16_t delay, uint32_t ulDuration, uint8_t dir);
|
||||
int adcSampleStop(void);
|
||||
void adcUpdateParam(void);
|
||||
|
||||
#endif // ADC_H
|
||||
@@ -0,0 +1,287 @@
|
||||
#include "cmsis_os.h"
|
||||
#include "ads8321.h"
|
||||
|
||||
#include "main.h"
|
||||
#include "Param/param.h"
|
||||
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
|
||||
#define DPRINT(fmt, args...) printf(fmt, ##args)
|
||||
//#define DPRINT(fmt, args...)
|
||||
|
||||
extern UART_HandleTypeDef huart4;
|
||||
extern TIM_HandleTypeDef htim3;
|
||||
extern TIM_HandleTypeDef htim1;
|
||||
|
||||
extern SPI_HandleTypeDef hspi3;
|
||||
extern SPI_HandleTypeDef hspi2;
|
||||
|
||||
|
||||
int _giSampleInProgress = 0;
|
||||
|
||||
uint32_t _gaulAdcValue[2];
|
||||
int _gaiFlag[2];
|
||||
|
||||
volatile uint32_t _gulSamplePosUm = 0;
|
||||
volatile uint32_t _gulSampleTimeUs = 0;
|
||||
volatile adcDataQueueDef gtAdcDataQueue;
|
||||
volatile uint32_t gulAdcSampleIndex;
|
||||
volatile uint32_t ulSampleStartTime = 0;
|
||||
volatile uint32_t ulSampleDuration = 0;
|
||||
|
||||
typedef struct {
|
||||
uint32_t ulTick;
|
||||
uint32_t ulCnt;
|
||||
} tickTimeDef;
|
||||
|
||||
volatile int32_t _gslEncCnt = 0;
|
||||
tickTimeDef _gtLastTrigTime;
|
||||
int _giEncoderTrigFlag = 0;
|
||||
uint32_t gulEncoderSpeed = 0; /// 0.1mm/s
|
||||
|
||||
int giScanDirection = 0;
|
||||
|
||||
uint32_t gulPacketIndex = 0;
|
||||
uint32_t gulPacketAck = 0;
|
||||
|
||||
static uint32_t _gaulAdcBuf[100];
|
||||
static uint32_t _gaulAdcBuf2[100];
|
||||
static uint32_t _gulAdcIndex = 0;
|
||||
static uint32_t _gulAdcSampleCount = 0;
|
||||
|
||||
static void adcDataQueueReset(void);
|
||||
void adcUpdateParam(void);
|
||||
|
||||
int getAdcValue(uint32_t adc_val)
|
||||
{
|
||||
uint32_t rxDataOK = adc_val >> 2;
|
||||
int16_t val;
|
||||
memcpy(&val, &rxDataOK, sizeof(val));
|
||||
|
||||
int ret = val + 32767;
|
||||
if (ret < 0) {
|
||||
ret = 0;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static void spiTransmitReceiveOnce(int index)
|
||||
{
|
||||
static uint32_t dummy = 0;
|
||||
_gaiFlag[0] = 0;
|
||||
_gaiFlag[1] = 0;
|
||||
HAL_SPI_Receive_IT(&hspi2, (uint8_t *)&_gaulAdcBuf[index], 1);
|
||||
HAL_SPI_TransmitReceive_IT(&hspi3, (uint8_t *)&dummy, (uint8_t *)&_gaulAdcBuf2[index], 1);
|
||||
}
|
||||
|
||||
static void data_average()
|
||||
{
|
||||
uint32_t ulData1 = 0;
|
||||
uint32_t ulData2 = 0;
|
||||
for (int i = 0; i < _gulAdcSampleCount; i++) {
|
||||
ulData1 += getAdcValue(_gaulAdcBuf[i]);
|
||||
ulData2 += getAdcValue(_gaulAdcBuf2[i]);
|
||||
}
|
||||
_gaulAdcValue[0] = ulData1 / _gulAdcSampleCount;
|
||||
_gaulAdcValue[1] = ulData2 / _gulAdcSampleCount;
|
||||
}
|
||||
|
||||
static void adcDataQueuePut(void);
|
||||
|
||||
static void checkDataReady()
|
||||
{
|
||||
if (_gaiFlag[0] && _gaiFlag[1]) {
|
||||
_gulAdcIndex++;
|
||||
if (_gulAdcIndex < _gulAdcSampleCount) {
|
||||
spiTransmitReceiveOnce(_gulAdcIndex);
|
||||
return;
|
||||
} else if (_gulAdcIndex == _gulAdcSampleCount) {
|
||||
data_average();
|
||||
adcDataQueuePut();
|
||||
// printf("%d\r\n", adcDataQueueLen());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
|
||||
{
|
||||
if (hspi == &hspi2) {
|
||||
_gaiFlag[0] = 1;
|
||||
checkDataReady();
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
|
||||
{
|
||||
if (hspi == &hspi3) {
|
||||
_gaiFlag[1] = 1;
|
||||
checkDataReady();
|
||||
}
|
||||
}
|
||||
|
||||
static void adcStart(int avrg_count)
|
||||
{
|
||||
_gtLastTrigTime.ulCnt = TIM13->CNT;
|
||||
_gtLastTrigTime.ulTick = uwTick;
|
||||
|
||||
if (avrg_count > 100) {
|
||||
avrg_count = 100;
|
||||
}
|
||||
|
||||
_gulAdcSampleCount = avrg_count;
|
||||
_gulAdcIndex = 0;
|
||||
|
||||
spiTransmitReceiveOnce(_gulAdcIndex);
|
||||
}
|
||||
|
||||
static void adcDataQueuePut(void)
|
||||
{
|
||||
uint32_t ulData1 = _gaulAdcValue[0];
|
||||
uint32_t ulData2 = _gaulAdcValue[1];
|
||||
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[gtAdcDataQueue.ulWritePos];
|
||||
|
||||
gulAdcSampleIndex++;
|
||||
|
||||
if (gulAdcSampleIndex >= 5) {
|
||||
ptData->aulData[0] = (uint16_t)ulData1;
|
||||
ptData->aulData[1] = (uint16_t)ulData2;
|
||||
|
||||
gtAdcDataQueue.ulWritePos++;
|
||||
if (gtAdcDataQueue.ulWritePos >= ADC_QUEUE_LEN) {
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setTimerPeriod(uint32_t ulPeriod)
|
||||
{
|
||||
htim3.Init.Period = ulPeriod - 1;
|
||||
|
||||
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
}
|
||||
|
||||
void adcDataQueueReset(void)
|
||||
{
|
||||
gtAdcDataQueue.ulReadPos = 0;
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
|
||||
uint16_t adcDataQueueLen(void)
|
||||
{
|
||||
uint16_t ulLength = 0;
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos == gtAdcDataQueue.ulReadPos) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos > gtAdcDataQueue.ulReadPos)
|
||||
{
|
||||
ulLength = gtAdcDataQueue.ulWritePos - gtAdcDataQueue.ulReadPos;
|
||||
}
|
||||
else
|
||||
{
|
||||
ulLength = ADC_QUEUE_LEN - gtAdcDataQueue.ulReadPos + gtAdcDataQueue.ulWritePos;
|
||||
}
|
||||
|
||||
return ulLength;
|
||||
}
|
||||
|
||||
void adcSampleStart(void)
|
||||
{
|
||||
if (_giSampleInProgress) {
|
||||
return;
|
||||
}
|
||||
printf("sample start \r\n");
|
||||
adcUpdateParam();
|
||||
__disable_irq();
|
||||
adcDataQueueReset();
|
||||
|
||||
gulAdcSampleIndex = 0;
|
||||
ulSampleStartTime = osKernelGetTickCount();
|
||||
__enable_irq();
|
||||
_gslEncCnt = 0;
|
||||
|
||||
if (gptSysParam->ucUseEncoder == 0) {
|
||||
printf("time sample \r\n");
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_4);
|
||||
HAL_TIM_Base_Start_IT(&htim3);
|
||||
} else {
|
||||
HAL_TIM_Base_Stop_IT(&htim3);
|
||||
TIM1->CNT = 10000;
|
||||
HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Start_IT(&htim1, TIM_CHANNEL_4);
|
||||
printf("start encoder\n");
|
||||
}
|
||||
|
||||
_giSampleInProgress = 1;
|
||||
}
|
||||
|
||||
void adcSampleStop(void)
|
||||
{
|
||||
if (!_giSampleInProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
printf("sample stop \r\n");
|
||||
|
||||
HAL_TIM_Base_Stop_IT(&htim3);
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Stop_IT(&htim1, TIM_CHANNEL_4);
|
||||
_giEncoderTrigFlag = 0;
|
||||
|
||||
_giSampleInProgress = 0;
|
||||
}
|
||||
|
||||
void setEncoderInterval(uint16_t usPeriod)
|
||||
{
|
||||
TIM_OC_InitTypeDef sConfigOC = {0};
|
||||
sConfigOC.OCMode = TIM_OCMODE_TIMING;
|
||||
sConfigOC.Pulse = 10000 - usPeriod;
|
||||
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
|
||||
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
sConfigOC.Pulse = 10000 + usPeriod;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
TIM1->CNT = 10000;
|
||||
}
|
||||
|
||||
void adcUpdateParam(void)
|
||||
{
|
||||
setEncoderInterval(gptSysParam->usAdcinterval);
|
||||
|
||||
setTimerPeriod(gptSysParam->usAdcPeriod);
|
||||
}
|
||||
|
||||
void TIM3_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
adcStart(gptSysParam->ucAverageCount);
|
||||
}
|
||||
|
||||
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
if (htim->Instance == TIM1) {
|
||||
/**
|
||||
* @brief 编码器中断
|
||||
*/
|
||||
TIM1->CNT = 10000;
|
||||
adcStart(gptSysParam->ucAverageCount);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef ADS8321_H
|
||||
#define ADS8321_H
|
||||
|
||||
#include "main.h"
|
||||
|
||||
#define ADC_CHANNEL_NUM 2
|
||||
#define ADC_QUEUE_LEN 6000
|
||||
#define PACKET_DATA_UNIT_NUM 6000
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __adcDataUnitDef {
|
||||
uint16_t aulData[ADC_CHANNEL_NUM];
|
||||
} adcDataUnitDef;
|
||||
|
||||
typedef struct __adcDataQueueDef {
|
||||
uint32_t ulReadPos;
|
||||
uint32_t ulWritePos;
|
||||
adcDataUnitDef atQueue[ADC_QUEUE_LEN];
|
||||
} adcDataQueueDef;
|
||||
#pragma pack()
|
||||
|
||||
extern volatile adcDataQueueDef gtAdcDataQueue;
|
||||
|
||||
uint16_t adcDataQueueLen(void);
|
||||
void adcSampleStart(void);
|
||||
void adcSampleStop(void);
|
||||
|
||||
#endif // ADS8321_H
|
||||
@@ -0,0 +1,213 @@
|
||||
#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 <lwip/sockets.h>
|
||||
#include "lwip/sys.h"
|
||||
#include "lwip/api.h"
|
||||
|
||||
#include "YMODEM/ymodem.h"
|
||||
#include "W25QXX/w25qxx.h"
|
||||
#include "Param/param.h"
|
||||
#include "ADC/adc.h"
|
||||
|
||||
#include "IAP/iap.h"
|
||||
|
||||
#define UDP_APP_PORT (6133UL)
|
||||
#define LOCAL_PORT (6133UL)
|
||||
#define UDP_APP_IP "192.168.8.142"
|
||||
|
||||
static char gacVersionBuf[32];
|
||||
|
||||
static struct sockaddr_in udpBroAddr;
|
||||
static struct sockaddr_in udpFromAddr;
|
||||
static int udp_sockfd = -1;
|
||||
|
||||
static int sendData(uint8_t *pucData, uint16_t usLen)
|
||||
{
|
||||
printf("udp send %d bytes\n", usLen);
|
||||
|
||||
if(udp_sockfd < 0)
|
||||
{
|
||||
printf("[APP]UDP SEND error , sockfd : %d \r\n",udp_sockfd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr = udpFromAddr;
|
||||
if (udpFromAddr.sin_addr.s_addr == 0) {
|
||||
return -1;
|
||||
}
|
||||
addr.sin_port = htons(LOCAL_PORT);
|
||||
if(sendto(udp_sockfd, pucData, usLen, 0, (struct sockaddr *)&addr, sizeof(addr)) != usLen)
|
||||
{
|
||||
printf("[APP]UDP SEND error \r\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("send ok \r\n");
|
||||
|
||||
return usLen;
|
||||
}
|
||||
|
||||
void systemReboot(void);
|
||||
void adcDataPacketAck(uint32_t ulPid);
|
||||
|
||||
static void handleCmd(uint8_t *pucBuf, uint16_t usLen)
|
||||
{
|
||||
if (usLen < 7) {
|
||||
return;
|
||||
}
|
||||
|
||||
//dump(pucBuf, usLen);
|
||||
|
||||
if ((pucBuf[0] == 0xAA) && (pucBuf[1] == 0xCC)) {
|
||||
switch (pucBuf[2]) {
|
||||
case 0x01: ///< start
|
||||
uint16_t ausValue[2];
|
||||
memcpy(ausValue, &pucBuf[3], 4);
|
||||
|
||||
printf("delay : %d, ulSampTime : %d\r\n", ausValue[0], ausValue[1]);
|
||||
|
||||
if (usLen >=8) {
|
||||
adcSampleStart(ausValue[0], ausValue[1], pucBuf[7]);
|
||||
} else {
|
||||
adcSampleStart(ausValue[0], ausValue[1], 0);
|
||||
}
|
||||
|
||||
break;
|
||||
case 0x02: ///< stop
|
||||
adcSampleStop();
|
||||
printf("[cmd]end ... \r\n");
|
||||
break;
|
||||
case 0x03: ///< data packet ack
|
||||
uint32_t ulPid;
|
||||
memcpy(&ulPid, &pucBuf[3], 4);
|
||||
|
||||
printf("recv ack %u\r\n", ulPid);
|
||||
|
||||
adcDataPacketAck(ulPid);
|
||||
|
||||
break;
|
||||
case 0x0A: ///< set param
|
||||
if (usLen >= sizeof(sysParamDef) + 3) {
|
||||
memcpy(gptSysParam, &pucBuf[3], sizeof(sysParamDef));
|
||||
saveSysParam();
|
||||
adcUpdateParam();
|
||||
}
|
||||
break;
|
||||
case 0x0B: ///< get param
|
||||
{
|
||||
int i = 0;
|
||||
uint8_t aucBuf[sizeof(sysParamDef) + 3];
|
||||
|
||||
aucBuf[i++] = 0xAA;
|
||||
aucBuf[i++] = 0xCC;
|
||||
aucBuf[i++] = 0x8B;
|
||||
|
||||
memcpy(&aucBuf[i], gptSysParam, sizeof(sysParamDef));
|
||||
|
||||
sendData(aucBuf, sizeof(aucBuf));
|
||||
|
||||
printf("send param\n");
|
||||
}
|
||||
break;
|
||||
case 0x0C: ///< reboot
|
||||
{
|
||||
systemReboot();
|
||||
}
|
||||
break;
|
||||
case 0x0D: ///< get version
|
||||
{
|
||||
int i = 0;
|
||||
uint8_t aucBuf[sizeof(gacVersionBuf) + 3];
|
||||
|
||||
aucBuf[i++] = 0xAA;
|
||||
aucBuf[i++] = 0xCC;
|
||||
aucBuf[i++] = 0x8D;
|
||||
|
||||
memcpy(&aucBuf[i], gacVersionBuf, sizeof(gacVersionBuf));
|
||||
|
||||
sendData(aucBuf, sizeof(aucBuf));
|
||||
|
||||
printf("send version\n");
|
||||
dump(aucBuf, sizeof(aucBuf));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
int giCmdThreadStatus= 0;
|
||||
static void cmdThread(void *arg)
|
||||
{
|
||||
struct sockaddr_in myaddr;
|
||||
static unsigned char recv_buf[1024] = {0};
|
||||
int recv_len = 0;
|
||||
socklen_t from_len = sizeof(udpFromAddr);
|
||||
|
||||
udp_sockfd = socket(AF_INET, SOCK_DGRAM ,0);
|
||||
if (udp_sockfd < 0) {
|
||||
printf("[UDPAPP][ERROR]alloc socket fd failed , again... \r\n");
|
||||
while (1) {
|
||||
osDelay(100);
|
||||
}
|
||||
}
|
||||
|
||||
myaddr.sin_family = AF_INET;
|
||||
myaddr.sin_addr.s_addr = INADDR_ANY;
|
||||
myaddr.sin_port = htons(UDP_APP_PORT);
|
||||
bind(udp_sockfd, (struct sockaddr*)&myaddr, sizeof(myaddr));
|
||||
|
||||
struct timeval tv = {0, 100 * 1000};
|
||||
setsockopt(udp_sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
|
||||
|
||||
memset(&udpBroAddr, 0, sizeof(udpBroAddr));
|
||||
udpBroAddr.sin_family = AF_INET;
|
||||
udpBroAddr.sin_port = htons(UDP_APP_PORT);
|
||||
inet_pton(AF_INET, UDP_APP_IP, &udpBroAddr.sin_addr.s_addr);
|
||||
|
||||
|
||||
while (1) {
|
||||
recv_len = recvfrom(udp_sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr *)&udpFromAddr, &from_len);
|
||||
giCmdThreadStatus = 0;
|
||||
|
||||
if (recv_len > 0) {
|
||||
debug("[UDPAPP]recv from: %s.%d\r\n", ip4addr_ntoa(&udpFromAddr.sin_addr.s_addr), ntohs(udpFromAddr.sin_port));
|
||||
debug("[UDPAPP]len : %d , data buf :",recv_len);
|
||||
dump(recv_buf, recv_len);
|
||||
debug("");
|
||||
|
||||
if (recv_len >= 7) {
|
||||
debug("[UDPAPP] exec handleUsbCmd");
|
||||
handleCmd(recv_buf, recv_len);
|
||||
}
|
||||
}
|
||||
osDelay(20);
|
||||
}
|
||||
}
|
||||
|
||||
void cmdInit(void)
|
||||
{
|
||||
sprintf(gacVersionBuf, "%s@%s_%s", SW_VER, __TIME__, __DATE__);
|
||||
// 创建任务
|
||||
const osThreadAttr_t cmd_task_attributes = {
|
||||
.name = "cmd_task",
|
||||
.stack_size = 4096 * 2,
|
||||
.priority = (osPriority_t) osPriorityNormal,
|
||||
};
|
||||
if (osThreadNew(cmdThread, NULL, &cmd_task_attributes) == NULL)
|
||||
{
|
||||
printf("failed to create cmd_task\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("create cmd_task success\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#ifndef CMD_H
|
||||
#define CMD_H
|
||||
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "main.h"
|
||||
/* Exported types ------------------------------------------------------------*/
|
||||
|
||||
|
||||
void cmdInit(void);
|
||||
|
||||
#endif // CMD_H
|
||||
@@ -0,0 +1,417 @@
|
||||
#include "main.h"
|
||||
#include "cmsis_os.h"
|
||||
#include "cpy_prot.h"
|
||||
#include "Param/param.h"
|
||||
#include "ADS8321/ads8321.h"
|
||||
#include "IAP/iap.h"
|
||||
|
||||
char gacVersionBuf[32];
|
||||
|
||||
int giCpyProtThreadStatus= 0;
|
||||
|
||||
extern UART_HandleTypeDef huart4;
|
||||
|
||||
static uint16_t gusMaxDataLen = 16 * 1024;
|
||||
|
||||
|
||||
static daq_packet_t *tx_packet_buf = NULL;
|
||||
static daq_packet_t *rx_packet_buf = NULL;
|
||||
static int rx_packet_ready = 0;
|
||||
static int tx_packet_busy = 0;
|
||||
|
||||
//函数声明
|
||||
static int daq_recv_packet(uint16_t data_len);
|
||||
|
||||
|
||||
static uint16_t crc16(const uint8_t *data, uint16_t len) {
|
||||
uint16_t crc = 0xFFFF;
|
||||
for (uint16_t i = 0; i < len; i++) {
|
||||
crc ^= data[i];
|
||||
for (uint8_t j = 0; j < 8; j++) {
|
||||
if (crc & 0x0001) {
|
||||
crc >>= 1;
|
||||
crc ^= 0xA001;
|
||||
} else {
|
||||
crc >>= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
static int check_packet(daq_packet_t *packet) {
|
||||
if (packet->header != DAQ_HEADER) {
|
||||
printf("header error, 0x%04X\r\n", packet->header);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (packet->len > gusMaxDataLen) {
|
||||
printf("len error, %d > %d\r\n", packet->len, gusMaxDataLen);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int packet_len = DATA_LEN_2_PACKET_LEN(packet->len);
|
||||
|
||||
uint16_t crc = crc16((const uint8_t *)packet, packet_len - CRC_LEN);
|
||||
uint16_t *pcrc = (uint16_t *)((uint8_t *)packet + packet_len - CRC_LEN);
|
||||
|
||||
if (crc != *pcrc) {
|
||||
printf("crc error, 0x%04X != 0x%04X\r\n", crc, *pcrc);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
|
||||
{
|
||||
if (huart->Instance == huart4.Instance) {
|
||||
rx_packet_ready = -1;
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
|
||||
{
|
||||
if ((huart->Instance == huart4.Instance) && (huart->RxEventType == HAL_UART_RXEVENT_IDLE)) {
|
||||
//SCB_InvalidateDCache_by_Addr((volatile void *)rx_packet_buf, Size);
|
||||
printf("rx packet %d\r\n", Size);
|
||||
// for (int i = 0; i < Size; i++) {
|
||||
// printf("%02X ", ((uint8_t *)rx_packet_buf)[i]);
|
||||
// }
|
||||
// printf("\r\n");
|
||||
if (check_packet(rx_packet_buf)) {
|
||||
rx_packet_ready = 1;
|
||||
} else {
|
||||
// printf("check packet failed, restart to recv\r\n");
|
||||
rx_packet_ready = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
|
||||
{
|
||||
if (huart->Instance == huart4.Instance) {
|
||||
tx_packet_busy = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int daq_send(const char *data, size_t len) {
|
||||
//SCB_CleanDCache_by_Addr((volatile void *)data, len);
|
||||
return HAL_UART_Transmit_DMA(&huart4, (uint8_t *)data, len);
|
||||
}
|
||||
|
||||
static int daq_recv(char *data, size_t len) {
|
||||
if (huart4.gState != HAL_UART_STATE_READY) {
|
||||
HAL_UART_AbortReceive(&huart4);
|
||||
}
|
||||
|
||||
return HAL_UARTEx_ReceiveToIdle_DMA(&huart4, (uint8_t *)data, len);
|
||||
}
|
||||
|
||||
|
||||
int daq_send_packet(uint8_t cmd, const uint8_t *data, uint16_t len) {
|
||||
uint16_t packet_len = DATA_LEN_2_PACKET_LEN(len);
|
||||
daq_packet_t *packet = tx_packet_buf;
|
||||
packet->header = DAQ_HEADER;
|
||||
packet->cmd = cmd;
|
||||
packet->len = len;
|
||||
if (data) {
|
||||
memcpy(packet->data, data, len);
|
||||
}
|
||||
|
||||
uint16_t crc = crc16((const uint8_t *)packet, packet_len - CRC_LEN);
|
||||
|
||||
uint16_t *pcrc = (uint16_t *)((uint8_t *)packet + packet_len - CRC_LEN);
|
||||
*pcrc = crc;
|
||||
|
||||
int ret = daq_send((const char *)packet, packet_len);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
static int daq_recv_packet(uint16_t data_len) {
|
||||
daq_packet_t *rx_packet = rx_packet_buf;
|
||||
|
||||
return daq_recv((char *)rx_packet, DATA_LEN_2_PACKET_LEN(data_len));
|
||||
}
|
||||
|
||||
|
||||
static int makeDataPacket(uint8_t *data)
|
||||
{
|
||||
uint16_t ulPos = 0;
|
||||
uint16_t i = 0;
|
||||
uint16_t ulLen = adcDataQueueLen();
|
||||
|
||||
if (ulLen < 5)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
adcDataUnitDef *ptRetData = (adcDataUnitDef *)(data + 4);
|
||||
|
||||
for (i = 0; i < ulLen; ++i)
|
||||
{
|
||||
ulPos = gtAdcDataQueue.ulReadPos + i;
|
||||
if (ulPos >= ADC_QUEUE_LEN)
|
||||
{
|
||||
ulPos -= ADC_QUEUE_LEN;
|
||||
}
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[ulPos];
|
||||
memcpy(&ptRetData[i], (uint8_t *)ptData, sizeof(adcDataUnitDef));
|
||||
}
|
||||
|
||||
uint16_t usDataLen = ulLen * sizeof(adcDataUnitDef);
|
||||
|
||||
*((uint16_t *)(data + 0)) = usDataLen; ///< 长度
|
||||
*((uint16_t *)(data + 2)) = crc16(data + 4, usDataLen); ///< 校验
|
||||
|
||||
return usDataLen + 4;
|
||||
}
|
||||
|
||||
|
||||
int cpyProtPacketHandle(uint8_t cmd, const uint8_t *data, uint16_t len) {
|
||||
// 处理接收到的数据包
|
||||
// printf("recv packet: cmd=0x%02X, len=%d\r\n", cmd, len);
|
||||
|
||||
switch (cmd)
|
||||
{
|
||||
case CPY_PROT_CMD_HEARTBEAT:
|
||||
{
|
||||
extern uint16_t gusTempVal;
|
||||
uint8_t aucRspData[10];
|
||||
*((uint32_t *)&aucRspData[0]) = osKernelGetTickCount();
|
||||
*((uint16_t *)&aucRspData[4]) = gusTempVal;
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, aucRspData, sizeof(aucRspData));
|
||||
}
|
||||
break;
|
||||
|
||||
case CPY_PROT_CMD_VERSION:
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)gacVersionBuf, strlen(gacVersionBuf));
|
||||
break;
|
||||
|
||||
case CPY_PROT_CMD_PARAM_READ:
|
||||
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)gptSysParam, sizeof(sysParamDef));
|
||||
break;
|
||||
|
||||
case CPY_PROT_CMD_PARAM_WRITE:
|
||||
if (len != sizeof(sysParamDef)) {
|
||||
const char *err_msg = "param write len error";
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
break;
|
||||
}
|
||||
memcpy(gptSysParam, data, sizeof(sysParamDef));
|
||||
saveSysParam();
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)gptSysParam, sizeof(sysParamDef));
|
||||
break;
|
||||
|
||||
case CPY_PROT_CMD_SAMPLE_LEN:
|
||||
{
|
||||
uint16_t usLen = adcDataQueueLen();
|
||||
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)&usLen, sizeof(uint16_t));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case CPY_PROT_CMD_SAMPLE_DATA:
|
||||
{
|
||||
uint16_t usLen = adcDataQueueLen();
|
||||
if (usLen == 0) {
|
||||
const char *err_msg = "no sample data";
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
break;
|
||||
}
|
||||
|
||||
static uint8_t data[PACKET_DATA_UNIT_NUM * sizeof(adcDataUnitDef)];
|
||||
usLen = makeDataPacket(data);
|
||||
if (usLen == 0) {
|
||||
const char *err_msg = "make data packet failed";
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
break;
|
||||
}
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)data, usLen);
|
||||
}
|
||||
break;
|
||||
case CPY_PROT_CMD_IAP:
|
||||
iapPacketHandler(data);
|
||||
break;
|
||||
#ifdef BOOTLOADER
|
||||
case CPY_PROT_CMD_BOOT_BLOCKING:
|
||||
blockInBootloader(data[0]);
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, NULL, 0);
|
||||
printf("CPY_PROT_CMD_BOOT_BLOCKING\r\n");
|
||||
break;
|
||||
case CPY_PROT_CMD_JUMP_APP:
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, NULL, 0);
|
||||
osDelay(100);
|
||||
blockInBootloader(0);
|
||||
break;
|
||||
#endif
|
||||
case CPY_PROT_CMD_RESET:
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, NULL, 0);
|
||||
osDelay(100);
|
||||
systemReboot();
|
||||
break;
|
||||
case CPY_PROT_CMD_OTP_READ:
|
||||
{
|
||||
const sysOtpInfoDef *otpInfo = loadOtpInfo();
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)otpInfo, sizeof(sysOtpInfoDef));
|
||||
}
|
||||
break;
|
||||
case CPY_PROT_CMD_OTP_WRITE:
|
||||
{
|
||||
if (len != sizeof(sysOtpInfoDef)) {
|
||||
const char *err_msg = "otp write len error";
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ERROR, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
break;
|
||||
}
|
||||
const sysOtpInfoDef *otpInfo = (const sysOtpInfoDef *)data;
|
||||
int ret = saveOtpInfo(otpInfo);
|
||||
if (ret < 0) {
|
||||
char err_msg[64];
|
||||
sprintf(err_msg, "otp write failed: %d", ret);
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ERROR, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
break;
|
||||
}
|
||||
otpInfo = loadOtpInfo();
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)otpInfo, sizeof(sysOtpInfoDef));
|
||||
}
|
||||
break;
|
||||
case CPY_PROT_CMD_RESET_FACTORY:
|
||||
{
|
||||
systemResetFactory();
|
||||
const char *err_msg = "reset factory ok";
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
{
|
||||
const char *err_msg = "unknown cmd";
|
||||
printf("%s\n", err_msg);
|
||||
daq_send_packet(cmd | CPY_PROT_CMD_ACK, (const uint8_t *)err_msg, strlen(err_msg));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int waitTxComplete(int timeout_ms)
|
||||
{
|
||||
while (tx_packet_busy)
|
||||
{
|
||||
osDelay(1);
|
||||
timeout_ms--;
|
||||
if (timeout_ms <= 0) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void ioCheck(void)
|
||||
{
|
||||
static int ioRelay = 0;
|
||||
static int ioSample = 0;
|
||||
|
||||
if (DI_REALY_ASSERTED()) {
|
||||
if (ioRelay < 0) {
|
||||
ioRelay = 0;
|
||||
}
|
||||
ioRelay++;
|
||||
if (ioRelay >= 3) {
|
||||
ioRelay = 3;
|
||||
DO_RELAY_ASSERT();
|
||||
}
|
||||
} else {
|
||||
if (ioRelay > 0) {
|
||||
ioRelay = 0;
|
||||
}
|
||||
ioRelay--;
|
||||
if (ioRelay <= -3) {
|
||||
ioRelay = -3;
|
||||
DO_RELAY_ASSERT();
|
||||
}
|
||||
}
|
||||
|
||||
if (DI_SIMPLE_ASSERTED()) {
|
||||
if (ioSample < 0) {
|
||||
ioSample = 0;
|
||||
}
|
||||
ioSample++;
|
||||
if (ioSample >= 3) {
|
||||
ioSample = 3;
|
||||
adcSampleStart();
|
||||
}
|
||||
} else {
|
||||
if (ioSample > 0) {
|
||||
ioSample = 0;
|
||||
}
|
||||
ioSample--;
|
||||
if (ioSample <= -3) {
|
||||
ioSample = -3;
|
||||
adcSampleStop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void cpyProtThread(void *arg)
|
||||
{
|
||||
int iCnt = 0;
|
||||
daq_recv_packet(gusMaxDataLen);
|
||||
|
||||
while (1) {
|
||||
iCnt++;
|
||||
if (rx_packet_ready == 1) {
|
||||
rx_packet_ready = 0;
|
||||
// 处理接收的数据包
|
||||
cpyProtPacketHandle(rx_packet_buf->cmd, rx_packet_buf->data, rx_packet_buf->len);
|
||||
|
||||
// int ret = waitTxComplete(100);
|
||||
// if (ret < 0) {
|
||||
// printf("wait tx complete timeout\n");
|
||||
// }
|
||||
// tx_packet_busy = 0;
|
||||
daq_recv_packet(gusMaxDataLen);
|
||||
} else if (rx_packet_ready == -1) {
|
||||
rx_packet_ready = 0;
|
||||
daq_recv_packet(gusMaxDataLen);
|
||||
}
|
||||
|
||||
ioCheck();
|
||||
|
||||
osDelay(1);
|
||||
if (iCnt > 1000) {
|
||||
iCnt = 0;
|
||||
// daq_send("hello", 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void cpyProtInit(void)
|
||||
{
|
||||
sprintf(gacVersionBuf, "%s@%s_%s", SW_VER, __TIME__, __DATE__);
|
||||
|
||||
tx_packet_buf = pvPortMalloc(DATA_LEN_2_PACKET_LEN(gusMaxDataLen));
|
||||
rx_packet_buf = pvPortMalloc(DATA_LEN_2_PACKET_LEN(gusMaxDataLen));
|
||||
|
||||
if (tx_packet_buf == NULL || rx_packet_buf == NULL) {
|
||||
printf("failed to malloc packet buf\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建任务
|
||||
const osThreadAttr_t cpyProt_task_attributes = {
|
||||
.name = "cpyProt_task",
|
||||
.stack_size = 4096 * 2,
|
||||
.priority = (osPriority_t) osPriorityNormal,
|
||||
};
|
||||
if (osThreadNew(cpyProtThread, NULL, &cpyProt_task_attributes) == NULL)
|
||||
{
|
||||
printf("failed to create cpyProt_task\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("create cpyProt_task success\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#ifndef CPY_PROT_H
|
||||
#define CPY_PROT_H
|
||||
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "main.h"
|
||||
/* Exported types ------------------------------------------------------------*/
|
||||
|
||||
#define DAQ_HEADER 0x55AA
|
||||
#define DAQ_DATA_MIN_LEN 10
|
||||
#define CRC_LEN 2
|
||||
|
||||
|
||||
typedef enum {
|
||||
CPY_PROT_CMD_HEARTBEAT = 0x01,
|
||||
CPY_PROT_CMD_VERSION,
|
||||
CPY_PROT_CMD_PARAM_READ,
|
||||
CPY_PROT_CMD_PARAM_WRITE,
|
||||
CPY_PROT_CMD_SAMPLE_LEN,
|
||||
CPY_PROT_CMD_SAMPLE_DATA,
|
||||
CPY_PROT_CMD_IAP,
|
||||
CPY_PROT_CMD_BOOT_BLOCKING,
|
||||
CPY_PROT_CMD_JUMP_APP,
|
||||
CPY_PROT_CMD_RESET,
|
||||
CPY_PROT_CMD_OTP_READ,
|
||||
CPY_PROT_CMD_OTP_WRITE,
|
||||
CPY_PROT_CMD_RESET_FACTORY,
|
||||
|
||||
CPY_PROT_CMD_ACK = 0x80,
|
||||
CPY_PROT_CMD_ERROR = 0xC0,
|
||||
} cpy_prot_cmd_t;
|
||||
|
||||
//1字节对齐
|
||||
#pragma pack(1)
|
||||
typedef struct {
|
||||
uint16_t header;
|
||||
uint8_t cmd;
|
||||
uint16_t len;
|
||||
uint8_t data[DAQ_DATA_MIN_LEN];
|
||||
} daq_packet_t;
|
||||
#pragma pack()
|
||||
|
||||
#define DATA_LEN_2_PACKET_LEN(data_len) ((data_len) < DAQ_DATA_MIN_LEN ? (sizeof(daq_packet_t) + CRC_LEN) : ((data_len) + sizeof(daq_packet_t) - DAQ_DATA_MIN_LEN + CRC_LEN))
|
||||
|
||||
|
||||
void cpyProtInit(void);
|
||||
int daq_send_packet(uint8_t cmd, const uint8_t *data, uint16_t len);
|
||||
|
||||
|
||||
#endif // CPY_PROT_H
|
||||
@@ -0,0 +1,853 @@
|
||||
#include "cmsis_os.h"
|
||||
#include "ddc112.h"
|
||||
#include "GPIO_HAL/gpioHal.h"
|
||||
#include "main.h"
|
||||
#include "Param/param.h"
|
||||
#include "IAP/iap.h"
|
||||
|
||||
#define EXTERN_CAP_VALUE 270 ///< pF
|
||||
#define REF_VOLTAGE 4.096 ///< V
|
||||
|
||||
extern TIM_HandleTypeDef htim3;
|
||||
extern TIM_HandleTypeDef htim2;
|
||||
extern TIM_HandleTypeDef htim4;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
IO_ID_RANGE0 = 0,
|
||||
IO_ID_RANGE1,
|
||||
IO_ID_RANGE2,
|
||||
|
||||
IO_ID_DXMIT,
|
||||
IO_ID_DCLK,
|
||||
IO_ID_DOUT,
|
||||
IO_ID_DVALID,
|
||||
|
||||
IO_ID_CONV,
|
||||
IO_ID_TEST,
|
||||
|
||||
} IO_INDEX_DEF;
|
||||
|
||||
typedef struct __moduleIoTypeDef
|
||||
{
|
||||
gpioHalDef tPort; ///< 端口
|
||||
gpioHalModeDef eMode; ///< 端口配置模式
|
||||
uint8_t ucInitLevel; ///< 初始电平
|
||||
} moduleIoTypeDef;
|
||||
|
||||
static const moduleIoTypeDef _gatIoArray[] = {
|
||||
{{GPIOD, GPIO_PIN_4}, GPIO_Mode_Out_PP, 0}, ///< RANGE0
|
||||
{{GPIOD, GPIO_PIN_3}, GPIO_Mode_Out_PP, 0}, ///< RANGE1
|
||||
{{GPIOD, GPIO_PIN_2}, GPIO_Mode_Out_PP, 0}, ///< RANGE2
|
||||
|
||||
{{GPIOB, GPIO_PIN_7}, GPIO_Mode_Out_PP, 1}, ///< DXMIT,active low
|
||||
{{GPIOC, GPIO_PIN_10}, GPIO_Mode_Out_PP, 0}, ///< DCLK,normaly low
|
||||
{{GPIOC, GPIO_PIN_11}, GPIO_Mode_IPU, 0}, ///< DOUT
|
||||
{{GPIOC, GPIO_PIN_12}, GPIO_Mode_IPU, 0}, ///< DVALID,active low
|
||||
|
||||
{{GPIOB, GPIO_PIN_5}, GPIO_Mode_IPU, 0}, ///< CONV,output for mastrt,input for slave
|
||||
{{GPIOD, GPIO_PIN_5}, GPIO_Mode_Out_PP, 0}, ///< High for master to output sync,Low for slave to input sync
|
||||
|
||||
{NULL, 0},
|
||||
};
|
||||
|
||||
struct
|
||||
{
|
||||
uint32_t ulAdcClk;
|
||||
uint32_t ulConvPeriod; ///< us
|
||||
DDC_RANG_DEF eRange;
|
||||
float fCapValue; ///< pF
|
||||
} _gtModuleInfo;
|
||||
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __transferPacketDef
|
||||
{
|
||||
uint16_t usHeaderA;
|
||||
uint16_t usHeaderB;
|
||||
uint16_t usQueueRemainDataLen;
|
||||
uint16_t usLen;
|
||||
adcDataUnitDef atData[PACKET_DATA_UNIT_NUM];
|
||||
} transferPacketDef;
|
||||
#pragma pack()
|
||||
|
||||
static transferPacketDef _gtTmpPkt;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
WORK_MODE_IDLE = 0,
|
||||
WORK_MODE_CMD_SAMPLE,
|
||||
WORK_MODE_PIN_SAMPLE,
|
||||
WORK_MODE_SEND_DATA,
|
||||
WORK_MODE_WAIT,
|
||||
} DDC112_WORK_MODE_DEF;
|
||||
|
||||
volatile adcDataQueueDef gtAdcDataQueue;
|
||||
volatile uint32_t gulAdcSampleIndex;
|
||||
volatile uint32_t ulSampleStartTime = 0;
|
||||
volatile uint32_t ulSampleDuration = 0;
|
||||
volatile int _iWorkMode = WORK_MODE_IDLE;
|
||||
|
||||
typedef struct {
|
||||
uint32_t ulTick;
|
||||
uint32_t ulCnt;
|
||||
} tickTimeDef;
|
||||
|
||||
tickTimeDef _gtLastTrigTime;
|
||||
int _giEncoderTrigFlag = 0;
|
||||
uint32_t gulEncoderSpeed = 0; /// 0.1mm/s
|
||||
|
||||
static void resetAdcDataQueue(void);
|
||||
|
||||
static void _delay()
|
||||
{
|
||||
__asm("nop");
|
||||
__asm("nop");
|
||||
__asm("nop");
|
||||
__asm("nop");
|
||||
__asm("nop");
|
||||
__asm("nop");
|
||||
}
|
||||
|
||||
static void _ioInit(void)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
static void _dvalidInterruptInit(void)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
static void _readChannel(void)
|
||||
{
|
||||
uint8_t ucVal;
|
||||
uint8_t i;
|
||||
uint32_t ulData1 = 0, ulData2 = 0;
|
||||
static uint32_t ulData1_old = 0, ulData2_old = 0;
|
||||
|
||||
// printf("readChannel start\n");
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_DCLK].tPort);
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_DXMIT].tPort);
|
||||
_delay();
|
||||
|
||||
for (i = 0; i < 20; i++)
|
||||
{
|
||||
ulData1 <<= 1;
|
||||
_delay();
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_DCLK].tPort);
|
||||
_delay();
|
||||
ucVal = GPIO_HAL_READ(&_gatIoArray[IO_ID_DOUT].tPort);
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_DCLK].tPort);
|
||||
if (ucVal)
|
||||
{
|
||||
++ulData1;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < 20; i++)
|
||||
{
|
||||
ulData2 <<= 1;
|
||||
_delay();
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_DCLK].tPort);
|
||||
_delay();
|
||||
ucVal = GPIO_HAL_READ(&_gatIoArray[IO_ID_DOUT].tPort);
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_DCLK].tPort);
|
||||
if (ucVal)
|
||||
{
|
||||
++ulData2;
|
||||
}
|
||||
}
|
||||
|
||||
_delay();
|
||||
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_DXMIT].tPort);
|
||||
|
||||
if (gulAdcSampleIndex >= 10)
|
||||
{
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[gtAdcDataQueue.ulWritePos];
|
||||
|
||||
if (gptSysParam->ucFilterMode == 0)
|
||||
{
|
||||
ptData->aulData[0] = (uint16_t)(ulData1 / 16);
|
||||
ptData->aulData[1] = (uint16_t)(ulData2 / 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
ptData->aulData[0] = (uint16_t)((ulData1 + ulData1_old) / 2 / 16);
|
||||
ptData->aulData[1] = (uint16_t)((ulData2 + ulData2_old) / 2 / 16);
|
||||
}
|
||||
|
||||
gtAdcDataQueue.ulWritePos++;
|
||||
if (gtAdcDataQueue.ulWritePos >= ADC_QUEUE_LEN)
|
||||
{
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
ulData1_old = ulData1;
|
||||
ulData2_old = ulData2;
|
||||
}
|
||||
|
||||
void ddc112SetRange(DDC_RANG_DEF eRange)
|
||||
{
|
||||
if (eRange & 0x01)
|
||||
{
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_RANGE0].tPort);
|
||||
}
|
||||
else
|
||||
{
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_RANGE0].tPort);
|
||||
}
|
||||
|
||||
if (eRange & 0x02)
|
||||
{
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_RANGE1].tPort);
|
||||
}
|
||||
else
|
||||
{
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_RANGE1].tPort);
|
||||
}
|
||||
|
||||
if (eRange & 0x04)
|
||||
{
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_RANGE2].tPort);
|
||||
}
|
||||
else
|
||||
{
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_RANGE2].tPort);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief ddc112ValueToCurrent
|
||||
* @param ulValue
|
||||
* @return 电流,单位uA
|
||||
*/
|
||||
float ddc112ValueToCurrent(uint32_t ulValue)
|
||||
{
|
||||
double lfVol;
|
||||
double lfTmp;
|
||||
#define ZERO_VALUE 0x1000
|
||||
#define FULL_VALUE 0xFFFFF
|
||||
#define FS_FACTOR 0.96
|
||||
if (ulValue == 0x1000)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
lfVol = REF_VOLTAGE * FS_FACTOR;
|
||||
|
||||
if (ulValue > ZERO_VALUE)
|
||||
{
|
||||
ulValue -= ZERO_VALUE;
|
||||
|
||||
lfVol = lfVol * ulValue / FULL_VALUE;
|
||||
|
||||
lfTmp = lfVol * _gtModuleInfo.fCapValue / _gtModuleInfo.ulConvPeriod; ///< uA
|
||||
|
||||
return (float)lfTmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
ulValue = ZERO_VALUE - ulValue;
|
||||
lfVol = lfVol * ulValue / FULL_VALUE;
|
||||
|
||||
lfTmp = lfVol * _gtModuleInfo.fCapValue / _gtModuleInfo.ulConvPeriod; ///< uA
|
||||
lfTmp = -lfTmp;
|
||||
return (float)lfTmp;
|
||||
}
|
||||
}
|
||||
|
||||
void tim3PeriodInit(uint32_t ulPeriod)
|
||||
{
|
||||
htim3.Init.Period = ulPeriod - 1;
|
||||
|
||||
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
}
|
||||
|
||||
void pwmConvInit(uint32_t ulPeriod)
|
||||
{
|
||||
TIM_MasterConfigTypeDef sMasterConfig = {0};
|
||||
TIM_OC_InitTypeDef sConfigOC = {0};
|
||||
|
||||
tim3PeriodInit(ulPeriod * 2 - 1);
|
||||
|
||||
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
|
||||
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
|
||||
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
sConfigOC.OCMode = TIM_OCMODE_PWM1;
|
||||
sConfigOC.Pulse = ulPeriod - 1;
|
||||
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
|
||||
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
|
||||
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
/* USER CODE BEGIN TIM3_Init 2 */
|
||||
|
||||
/* USER CODE END TIM3_Init 2 */
|
||||
HAL_TIM_MspPostInit(&htim3);
|
||||
}
|
||||
|
||||
void ddc112SetTestMode(uint8_t ucMode)
|
||||
{
|
||||
if (ucMode)
|
||||
{
|
||||
GPIO_HAL_HIGH(&_gatIoArray[IO_ID_TEST].tPort);
|
||||
debug("enable ddc112 test mode");
|
||||
}
|
||||
else
|
||||
{
|
||||
GPIO_HAL_LOW(&_gatIoArray[IO_ID_TEST].tPort);
|
||||
debug("disable ddc112 test mode");
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* DDC112数据采集就绪
|
||||
*/
|
||||
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
|
||||
{
|
||||
if (GPIO_Pin == MCU_ADC_DVAILD_Pin)
|
||||
{
|
||||
gulAdcSampleIndex++;
|
||||
_readChannel();
|
||||
}
|
||||
}
|
||||
|
||||
static void resetAdcDataQueue(void)
|
||||
{
|
||||
gtAdcDataQueue.ulReadPos = 0;
|
||||
gtAdcDataQueue.ulWritePos = 0;
|
||||
}
|
||||
|
||||
static uint16_t getBufferedDataLength(void)
|
||||
{
|
||||
uint16_t ulLength = 0;
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos == gtAdcDataQueue.ulReadPos) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (gtAdcDataQueue.ulWritePos > gtAdcDataQueue.ulReadPos)
|
||||
{
|
||||
ulLength = gtAdcDataQueue.ulWritePos - gtAdcDataQueue.ulReadPos;
|
||||
}
|
||||
else
|
||||
{
|
||||
ulLength = ADC_QUEUE_LEN - gtAdcDataQueue.ulReadPos + gtAdcDataQueue.ulWritePos;
|
||||
}
|
||||
|
||||
return ulLength;
|
||||
}
|
||||
|
||||
static void base64_encode(const unsigned char *input, size_t input_len, char *output)
|
||||
{
|
||||
static const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
int i = 0, j = 0;
|
||||
unsigned char char_array_3[3], char_array_4[4];
|
||||
|
||||
while (input_len--)
|
||||
{
|
||||
char_array_3[i++] = *(input++);
|
||||
if (i == 3)
|
||||
{
|
||||
char_array_4[0] = (char_array_3[0] >> 2) & 0x3F;
|
||||
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) | (char_array_3[1] >> 4);
|
||||
char_array_4[2] = ((char_array_3[1] & 0x0F) << 2) | (char_array_3[2] >> 6);
|
||||
char_array_4[3] = char_array_3[2] & 0x3F;
|
||||
|
||||
for (i = 0; i < 4; i++)
|
||||
{
|
||||
output[j++] = base64_table[char_array_4[i]];
|
||||
}
|
||||
i = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (i)
|
||||
{
|
||||
for (int k = i; k < 3; k++)
|
||||
{
|
||||
char_array_3[k] = '\0';
|
||||
}
|
||||
|
||||
char_array_4[0] = (char_array_3[0] >> 2) & 0x3F;
|
||||
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) | (char_array_3[1] >> 4);
|
||||
char_array_4[2] = ((char_array_3[1] & 0x0F) << 2) | (char_array_3[2] >> 6);
|
||||
char_array_4[3] = char_array_3[2] & 0x3F;
|
||||
|
||||
for (int k = 0; k < i + 1; k++)
|
||||
{
|
||||
output[j++] = base64_table[char_array_4[k]];
|
||||
}
|
||||
|
||||
while (i++ < 3)
|
||||
{
|
||||
output[j++] = '=';
|
||||
}
|
||||
}
|
||||
output[j] = '\0'; // Null-terminate the output string
|
||||
}
|
||||
|
||||
static int sendDataPacket(uint8_t *pucData, uint16_t usLen)
|
||||
{
|
||||
static char aucBase64Buf[45 * 1024];
|
||||
static char aucUdpBuf[64 * 1024];
|
||||
|
||||
if (usLen <= 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (usLen > 41 * 1024)
|
||||
{
|
||||
printf("data too long\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
base64_encode(pucData, usLen, aucBase64Buf);
|
||||
sprintf(aucUdpBuf, "{\"type\":\"data_points\",\"name\":\"daq\",\"data\":\"%s\"}", aucBase64Buf);
|
||||
|
||||
#if 0
|
||||
if (udpSendBroadcast(aucUdpBuf, strlen(aucUdpBuf)) < 0)
|
||||
{
|
||||
printf("udp send failed \r\n");
|
||||
return -1;
|
||||
}
|
||||
#else
|
||||
// udpSendTo(aucUdpBuf, strlen(aucUdpBuf),
|
||||
// "192.168.8.12",
|
||||
// 50009);
|
||||
udpSendTo(aucUdpBuf, strlen(aucUdpBuf),
|
||||
"192.168.100.100",
|
||||
50009);
|
||||
osDelay(100);
|
||||
udpSendTo(aucUdpBuf, strlen(aucUdpBuf),
|
||||
"192.168.100.10",
|
||||
50009);
|
||||
#endif
|
||||
|
||||
printf("send ok \r\n");
|
||||
|
||||
return usLen;
|
||||
}
|
||||
|
||||
static int makeDataPacket(void)
|
||||
{
|
||||
uint16_t ulPos = 0;
|
||||
uint16_t i = 0;
|
||||
uint16_t ulLen = getBufferedDataLength();
|
||||
uint16_t send_size = 0;
|
||||
|
||||
if (ulLen < 5)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
ulLen -= 5;
|
||||
|
||||
for (i = 0; i < ulLen; ++i)
|
||||
{
|
||||
ulPos = gtAdcDataQueue.ulReadPos + i;
|
||||
if (ulPos >= ADC_QUEUE_LEN)
|
||||
{
|
||||
ulPos -= ADC_QUEUE_LEN;
|
||||
}
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[ulPos];
|
||||
memcpy(&_gtTmpPkt.atData[i], (uint8_t *)ptData, sizeof(adcDataUnitDef));
|
||||
}
|
||||
|
||||
_gtTmpPkt.usHeaderA = 0xAA55;
|
||||
_gtTmpPkt.usHeaderB = 0x55CC;
|
||||
_gtTmpPkt.usLen = ulLen;
|
||||
printf("_gtTmpPkt.usLen : %d , _gtTmpPkt.usQueueRemainDataLen : %d \r\n", _gtTmpPkt.usLen, _gtTmpPkt.usQueueRemainDataLen);
|
||||
|
||||
send_size = 8 + sizeof(adcDataUnitDef) * ulLen;
|
||||
|
||||
return send_size;
|
||||
}
|
||||
|
||||
void encoderModeInit()
|
||||
{
|
||||
GPIO_InitTypeDef GPIO_InitStruct = {0};
|
||||
|
||||
/**TIM3 GPIO Configuration
|
||||
PB5 ------> TIM3_CH2
|
||||
*/
|
||||
GPIO_InitStruct.Pin = GPIO_PIN_5;
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
GPIO_InitStruct.Pull = GPIO_NOPULL;
|
||||
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
|
||||
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
|
||||
}
|
||||
|
||||
void encoderModeDeinit()
|
||||
{
|
||||
GPIO_InitTypeDef GPIO_InitStruct = {0};
|
||||
|
||||
/**TIM3 GPIO Configuration
|
||||
PB5 ------> TIM3_CH2
|
||||
*/
|
||||
GPIO_InitStruct.Pin = GPIO_PIN_5;
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
|
||||
GPIO_InitStruct.Pull = GPIO_NOPULL;
|
||||
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
|
||||
GPIO_InitStruct.Alternate = GPIO_AF2_TIM3;
|
||||
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
|
||||
}
|
||||
|
||||
void _sampleStart(void)
|
||||
{
|
||||
if (gptSysParam->usDdc112Period > 300) {
|
||||
encoderModeDeinit();
|
||||
_readChannel();
|
||||
|
||||
resetAdcDataQueue();
|
||||
|
||||
gulAdcSampleIndex = 0;
|
||||
ulSampleStartTime = osKernelGetTickCount();
|
||||
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
|
||||
} else {
|
||||
_readChannel();
|
||||
__disable_irq();
|
||||
encoderModeInit();
|
||||
resetAdcDataQueue();
|
||||
|
||||
gulAdcSampleIndex = 0;
|
||||
ulSampleStartTime = osKernelGetTickCount();
|
||||
__enable_irq();
|
||||
}
|
||||
}
|
||||
|
||||
void _sampleStop(void)
|
||||
{
|
||||
HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_2);
|
||||
_giEncoderTrigFlag = 0;
|
||||
HAL_GPIO_WritePin(RELAY_GPIO_Port, RELAY_Pin, GPIO_PIN_RESET);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief ddc112Start
|
||||
* @return 1:成功,0:失败
|
||||
*/
|
||||
int ddc112Start(uint16_t delay, uint32_t ulDuration)
|
||||
{
|
||||
if (_iWorkMode == WORK_MODE_IDLE) {
|
||||
osDelay(delay);
|
||||
_sampleStart();
|
||||
_iWorkMode = WORK_MODE_CMD_SAMPLE;
|
||||
// printf("ddc112Start\r\n");
|
||||
ulSampleDuration = ulDuration;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief ddc112Stop
|
||||
* @return 1:成功,0:失败
|
||||
*/
|
||||
int ddc112Stop(void)
|
||||
{
|
||||
if (_iWorkMode == 1)
|
||||
{
|
||||
_iWorkMode = 0;
|
||||
_sampleStop();
|
||||
printf("ddc112Stop\r\n");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void test_correct()
|
||||
{
|
||||
ddc112SetTestMode(1);
|
||||
osDelay(100);
|
||||
|
||||
_sampleStart();
|
||||
osDelay(100);
|
||||
uint16_t ulPos = 0;
|
||||
uint16_t i = 0;
|
||||
uint16_t ulLen = getBufferedDataLength();
|
||||
uint16_t send_size = 0;
|
||||
|
||||
if (ulLen == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = 0; i < ulLen; ++i)
|
||||
{
|
||||
ulPos = gtAdcDataQueue.ulReadPos + i;
|
||||
if (ulPos >= ADC_QUEUE_LEN)
|
||||
{
|
||||
ulPos -= ADC_QUEUE_LEN;
|
||||
}
|
||||
volatile adcDataUnitDef *ptData = >AdcDataQueue.atQueue[ulPos];
|
||||
memcpy(&_gtTmpPkt.atData[i], (uint8_t *)ptData, sizeof(adcDataUnitDef));
|
||||
}
|
||||
}
|
||||
|
||||
static void ddc112_task(void *arg)
|
||||
{
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
while (1)
|
||||
{
|
||||
switch (_iWorkMode)
|
||||
{
|
||||
case WORK_MODE_IDLE: // 空闲状态
|
||||
if (gptSysParam->usPinSampleTime > 0) {
|
||||
if (HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_8) == GPIO_PIN_RESET)
|
||||
{
|
||||
if (gptSysParam->usPinSampleDelay > 0) {
|
||||
osDelay(gptSysParam->usPinSampleDelay);
|
||||
}
|
||||
ulSampleDuration = gptSysParam->usPinSampleTime;
|
||||
if (ulSampleDuration > 16000) {
|
||||
ulSampleDuration = 16000;
|
||||
}
|
||||
_sampleStart();
|
||||
_iWorkMode = WORK_MODE_PIN_SAMPLE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case WORK_MODE_CMD_SAMPLE: // 命令采样状态
|
||||
case WORK_MODE_PIN_SAMPLE: // 引脚采样状态
|
||||
if (osKernelGetTickCount() > ulSampleStartTime + ulSampleDuration)
|
||||
{
|
||||
_sampleStop();
|
||||
_iWorkMode = WORK_MODE_SEND_DATA;
|
||||
printf("sample timeout \r\n");
|
||||
printf("sample data length: %d\r\n", getBufferedDataLength());
|
||||
}
|
||||
else if (getBufferedDataLength() > PACKET_DATA_UNIT_NUM)
|
||||
{
|
||||
_sampleStop();
|
||||
_iWorkMode = WORK_MODE_SEND_DATA;
|
||||
printf("sample data length: %d\r\n", getBufferedDataLength());
|
||||
}
|
||||
break;
|
||||
case WORK_MODE_SEND_DATA: // 发送数据状态
|
||||
{
|
||||
int ret = makeDataPacket();
|
||||
if (ret > 0)
|
||||
{
|
||||
sendDataPacket((uint8_t *)&_gtTmpPkt, ret);
|
||||
}
|
||||
resetAdcDataQueue();
|
||||
_iWorkMode = WORK_MODE_WAIT;
|
||||
}
|
||||
break;
|
||||
case WORK_MODE_WAIT: // 发送数据状态
|
||||
{
|
||||
if (gptSysParam->usPinSampleTime == 0) {
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
} else if (HAL_GPIO_ReadPin(GPIOD, GPIO_PIN_8) == GPIO_PIN_SET) {
|
||||
_iWorkMode = WORK_MODE_IDLE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
osDelay(1);
|
||||
}
|
||||
}
|
||||
|
||||
void aimSpeedSet(uint16_t usPeriod)
|
||||
{
|
||||
TIM_OC_InitTypeDef sConfigOC = {0};
|
||||
sConfigOC.OCMode = TIM_OCMODE_TIMING;
|
||||
sConfigOC.Pulse = 10000 - usPeriod;
|
||||
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
|
||||
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
sConfigOC.Pulse = 10000 + usPeriod;
|
||||
if (HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
|
||||
{
|
||||
Error_Handler();
|
||||
}
|
||||
TIM2->CNT = 10000;
|
||||
}
|
||||
|
||||
void ddc112UpdateParam(void)
|
||||
{
|
||||
ddc112SetRange(gptSysParam->ucDdc112Range);
|
||||
if (gptSysParam->usDdc112Period < 300) {
|
||||
aimSpeedSet(gptSysParam->usDdc112Period);
|
||||
} else {
|
||||
pwmConvInit(gptSysParam->usDdc112Period);
|
||||
}
|
||||
if (gptSysParam->ucTestMode)
|
||||
{
|
||||
ddc112SetTestMode(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ddc112SetTestMode(0);
|
||||
}
|
||||
}
|
||||
|
||||
void ddc112Init(void)
|
||||
{
|
||||
static const float afRangeCaps[] = {
|
||||
EXTERN_CAP_VALUE,
|
||||
12.5, 25, 37.5, 50, 62.5, 75, 87.5};
|
||||
_gtModuleInfo.eRange = (DDC_RANG_DEF)(gptSysParam->ucDdc112Range);
|
||||
_gtModuleInfo.ulConvPeriod = gptSysParam->usDdc112Period;
|
||||
_gtModuleInfo.ulAdcClk = 15000000;
|
||||
_gtModuleInfo.fCapValue = afRangeCaps[_gtModuleInfo.eRange];
|
||||
|
||||
_ioInit();
|
||||
|
||||
ddc112UpdateParam();
|
||||
printf("ddc112 pwm conv period: %d\r\n", _gtModuleInfo.ulConvPeriod);
|
||||
|
||||
_dvalidInterruptInit();
|
||||
|
||||
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1); ///< 启动定时器4通道1
|
||||
HAL_TIM_Encoder_Start(&htim2, TIM_CHANNEL_ALL);
|
||||
HAL_TIM_OC_Start_IT(&htim2, TIM_CHANNEL_3);
|
||||
HAL_TIM_OC_Start_IT(&htim2, TIM_CHANNEL_4);
|
||||
TIM2->CNT = 10000;
|
||||
|
||||
// 创建任务
|
||||
const osThreadAttr_t ddc112_task_attributes = {
|
||||
.name = "ddc112_task",
|
||||
.stack_size = 4096 * 4,
|
||||
.priority = (osPriority_t)osPriorityNormal,
|
||||
};
|
||||
if (osThreadNew(ddc112_task, NULL, &ddc112_task_attributes) == NULL)
|
||||
{
|
||||
printf("failed to create ddc112_task\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("create ddc112_task success\n");
|
||||
}
|
||||
}
|
||||
|
||||
void TIM3_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
uint32_t getDeltaTime(tickTimeDef *last, tickTimeDef *now)
|
||||
{
|
||||
if (last->ulTick == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (now->ulTick < last->ulTick) {
|
||||
return 0;
|
||||
} else if (now->ulTick == last->ulTick) {
|
||||
if (now->ulCnt < last->ulCnt) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return (now->ulTick - last->ulTick) * 1000 + (now->ulCnt - last->ulCnt);
|
||||
}
|
||||
|
||||
void channelHandler(uint32_t ulVal)
|
||||
{
|
||||
tickTimeDef tim;
|
||||
|
||||
if (_giEncoderTrigFlag > 10) {
|
||||
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_5);
|
||||
}
|
||||
|
||||
tim.ulCnt = TIM13->CNT;
|
||||
tim.ulTick = uwTick;
|
||||
|
||||
uint32_t ulTim = getDeltaTime(&_gtLastTrigTime, &tim);
|
||||
|
||||
if (ulTim > 0) {
|
||||
gulEncoderSpeed = gptSysParam->usDdc112Period * 10000 / ulTim;
|
||||
}
|
||||
|
||||
if (gulEncoderSpeed >= gptSysParam->usDdc112Period * 10 * 8 / 10) {
|
||||
if (_giEncoderTrigFlag < 100) {
|
||||
_giEncoderTrigFlag++;
|
||||
}
|
||||
}
|
||||
|
||||
// printf("pulse 40, %u, flag %d\n", gulEncoderSpeed, _giEncoderTrigFlag);
|
||||
|
||||
_gtLastTrigTime = tim;
|
||||
}
|
||||
|
||||
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
if (htim->Instance == TIM2) {
|
||||
uint32_t ulVal = TIM2->CNT;
|
||||
TIM2->CNT = 10000;
|
||||
channelHandler(ulVal);
|
||||
} else if (htim == &htim3) {
|
||||
// gulAdcSampleIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
void TIM2_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
|
||||
{
|
||||
tickTimeDef tim;
|
||||
|
||||
if (_giEncoderTrigFlag > 10) {
|
||||
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_5);
|
||||
}
|
||||
|
||||
tim.ulCnt = TIM13->CNT;
|
||||
tim.ulTick = uwTick;
|
||||
|
||||
uint32_t ulVal = getDeltaTime(&_gtLastTrigTime, &tim);
|
||||
|
||||
gulEncoderSpeed = gptSysParam->usDdc112Period * 10000 / ulVal;
|
||||
|
||||
if (gulEncoderSpeed >= gptSysParam->usDdc112Period * 10 * 8 / 10) {
|
||||
if (_giEncoderTrigFlag < 100) {
|
||||
_giEncoderTrigFlag++;
|
||||
}
|
||||
} else {
|
||||
_giEncoderTrigFlag = 0;
|
||||
}
|
||||
|
||||
// printf("pulse 40, %u, flag %d\n", gulEncoderSpeed, _giEncoderTrigFlag);
|
||||
|
||||
_gtLastTrigTime = tim;
|
||||
}
|
||||
|
||||
// void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
|
||||
//{
|
||||
// if(htim->Instance == TIM2)
|
||||
// {
|
||||
// if((ulEnc_sta & 0x80) == 0)
|
||||
// {
|
||||
// if(ulEnc_sta & 0x40)
|
||||
// {
|
||||
// ulEnc_sta |= 0x80;
|
||||
// ulEnc =HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_1);
|
||||
// TIM_RESET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1);
|
||||
// }
|
||||
// else {
|
||||
// ulEnc_sta = 0;
|
||||
// ulEnc = 0;
|
||||
// ulEnc_sta = 0x40;
|
||||
// __HAL_TIM_DISABLE(&htim2);
|
||||
// __HAL_TIM_SET_COUNTER(&htim2,0);
|
||||
// TIM_RESET_CAPTUREPOLARITY(&htim2,TIM_CHANNEL_1);
|
||||
// __HAL_TIM_ENABLE(&htim2);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,55 @@
|
||||
#ifndef DDC112_H
|
||||
#define DDC112_H
|
||||
|
||||
#include "main.h"
|
||||
|
||||
typedef enum {
|
||||
DDC_RANG_EXTERN = 0,
|
||||
DDC_RANG_12_5_PF,
|
||||
DDC_RANG_25_0_PF,
|
||||
DDC_RANG_37_5_PF,
|
||||
DDC_RANG_50_0_PF,
|
||||
DDC_RANG_62_5_PF,
|
||||
DDC_RANG_75_0_PF,
|
||||
DDC_RANG_87_5_PF,
|
||||
DDC_RANG_MAX,
|
||||
} DDC_RANG_DEF;
|
||||
|
||||
#define ADC_CHANNEL_NUM 2
|
||||
#define ADC_QUEUE_LEN 16250
|
||||
#define PACKET_DATA_UNIT_NUM 16000
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __adcDataUnitDef {
|
||||
|
||||
uint16_t aulData[ADC_CHANNEL_NUM];
|
||||
|
||||
} adcDataUnitDef;
|
||||
|
||||
typedef struct __adcDataQueueDef {
|
||||
uint32_t ulReadPos;
|
||||
uint32_t ulWritePos;
|
||||
adcDataUnitDef atQueue[ADC_QUEUE_LEN];
|
||||
} adcDataQueueDef;
|
||||
#pragma pack()
|
||||
|
||||
|
||||
int ddc112Start(uint16_t delay, uint32_t ulDuration);
|
||||
int ddc112Stop(void);
|
||||
|
||||
void ddc112SetTestMode(uint8_t ucMode);
|
||||
|
||||
void ddc112Init(void);
|
||||
void ddc112SetRange(DDC_RANG_DEF eRange);
|
||||
|
||||
extern void DDC112_IRQHandler(void);
|
||||
/**
|
||||
* @brief ddc112ValueToCurrent
|
||||
* @param ulValue
|
||||
* @return 电流,单位uA
|
||||
*/
|
||||
float ddc112ValueToCurrent(uint32_t ulValue);
|
||||
|
||||
void ddc112UpdateParam(void);
|
||||
|
||||
#endif // DDC112_H
|
||||
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* 单片机源码网 www.mcusrc.com
|
||||
* 奥西物联嵌入式工作室
|
||||
* designed by OCEIOT 代码已测试 2017-6-25
|
||||
*/
|
||||
#include "gpioHal.h"
|
||||
|
||||
#if 0
|
||||
/**
|
||||
* @brief 设置IO口的模式
|
||||
* @param ptGpio 相应IO的结构体指针
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalSetMode(const gpioHalDef *ptGpio, gpioHalModeDef mMode)
|
||||
{
|
||||
GPIO_InitTypeDef GPIO_InitStructure;
|
||||
|
||||
GPIO_StructInit(&GPIO_InitStructure);
|
||||
|
||||
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
|
||||
if (mMode == GPIO_Mode_IPU) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
||||
} else if (mMode == GPIO_Mode_IPD) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
|
||||
} else if (mMode == GPIO_Mode_Out_PP) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
||||
} else if (mMode == GPIO_Mode_Out_OD) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
|
||||
} else if (mMode == GPIO_Mode_Out_OD_PU) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
||||
} else if (mMode == GPIO_Mode_AF_PP) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
|
||||
} else if (mMode == GPIO_Mode_AF_OD) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
|
||||
} else if (mMode == GPIO_Mode_AF_OD_PU) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
||||
} else if (mMode == GPIO_Mode_AF_IN) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
||||
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
||||
} else if (mMode == GPIO_Mode_AIN) {
|
||||
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
|
||||
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
|
||||
}
|
||||
GPIO_InitStructure.GPIO_Pin = ptGpio->usPin;
|
||||
GPIO_Init(ptGpio->pPort, &GPIO_InitStructure);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 初始化IO,开启端口时钟,设置IO模式
|
||||
* @param ptGpio 相应IO的结构体指针
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalInit(const gpioHalDef *ptGpio, gpioHalModeDef mMode)
|
||||
{
|
||||
uint32_t ulOffset, ulRegAddr;
|
||||
ulOffset = ((uint32_t)(ptGpio->pPort) - (uint32_t)GPIOA) / ((uint32_t)GPIOB - (uint32_t)GPIOA);
|
||||
|
||||
ulRegAddr = RCC_AHB1Periph_GPIOA;
|
||||
while (ulOffset) {
|
||||
ulRegAddr <<= 1;
|
||||
--ulOffset;
|
||||
}
|
||||
|
||||
/*
|
||||
* 开启端口时钟
|
||||
*/
|
||||
RCC_AHB1PeriphClockCmd(ulRegAddr, ENABLE);
|
||||
|
||||
/*
|
||||
* 设置IO模式
|
||||
*/
|
||||
gpioHalSetMode(ptGpio, mMode);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief 初始化IO,开启端口时钟,设置IO模式
|
||||
* @param pPort 端口
|
||||
* @param usPin 时钟
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalInitExt(GPIO_TypeDef *pPort, uint16_t usPin, gpioHalModeDef mMode)
|
||||
{
|
||||
gpioHalDef tGpio;
|
||||
uint32_t ulOffset, ulRegAddr;
|
||||
ulOffset = ((uint32_t)(pPort) - (uint32_t)GPIOA) / ((uint32_t)GPIOB - (uint32_t)GPIOA);
|
||||
|
||||
ulRegAddr = RCC_AHB1Periph_GPIOA;
|
||||
while (ulOffset) {
|
||||
ulRegAddr <<= 1;
|
||||
--ulOffset;
|
||||
}
|
||||
|
||||
/*
|
||||
* 开启端口时钟
|
||||
*/
|
||||
RCC_AHB1PeriphClockCmd(ulRegAddr, ENABLE);
|
||||
|
||||
/*
|
||||
* 设置IO模式
|
||||
*/
|
||||
tGpio.pPort = pPort;
|
||||
tGpio.usPin = usPin;
|
||||
gpioHalSetMode(&tGpio, mMode);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* 单片机源码网 www.mcusrc.com
|
||||
* 奥西物联嵌入式工作室
|
||||
* designed by OCEIOT 代码已测试 2017-6-25
|
||||
*/
|
||||
|
||||
/*
|
||||
* 此文件仅适用于stm32f10x单片机并需要标准固件库支持
|
||||
* 本驱动对标准固件库的GPIO部分进一步封装
|
||||
* 以简化IO操作,实现单行代码初始化IO,单行代码操作IO
|
||||
*/
|
||||
#ifndef GPIO_HAL_H
|
||||
#define GPIO_HAL_H
|
||||
|
||||
#include "main.h"
|
||||
|
||||
typedef struct __gpioHalDef {
|
||||
GPIO_TypeDef *pPort;
|
||||
uint16_t usPin;
|
||||
} gpioHalDef;
|
||||
|
||||
typedef enum {
|
||||
GPIO_Mode_AIN, //模拟输入
|
||||
GPIO_Mode_IN_FLOATING, //浮空输入(高阻输入)
|
||||
GPIO_Mode_IPD, //下拉输入
|
||||
GPIO_Mode_IPU, //上拉输入
|
||||
GPIO_Mode_Out_OD, //开漏输出
|
||||
GPIO_Mode_Out_OD_PU, //开漏输出上拉
|
||||
GPIO_Mode_Out_PP, //推挽输出
|
||||
GPIO_Mode_AF_OD, //复用开漏输出
|
||||
GPIO_Mode_AF_OD_PU, //复用开漏输出上拉
|
||||
GPIO_Mode_AF_PP, //复用推挽输出
|
||||
GPIO_Mode_AF_IN, //复用输入
|
||||
} gpioHalModeDef;
|
||||
|
||||
/*
|
||||
* 常用的IO操作,直接操作寄存器,效率更高
|
||||
*/
|
||||
#define GPIO_RAW_HIGH(port, pin) (port)->BSRR = (pin)
|
||||
#define GPIO_RAW_LOW(port, pin) (port)->BSRR = ((pin) << 16)
|
||||
#define GPIO_RAW_TOG(port, pin) (port)->ODR ^= (pin)
|
||||
#define GPIO_RAW_READ(port, pin) (((port)->IDR & (pin)) ? 1 : 0)
|
||||
|
||||
#define GPIO_HAL_HIGH(GPIO) (GPIO)->pPort->BSRR = ((GPIO)->usPin)
|
||||
#define GPIO_HAL_LOW(GPIO) (GPIO)->pPort->BSRR = (((GPIO)->usPin) << 16)
|
||||
#define GPIO_HAL_TOG(GPIO) (GPIO)->pPort->ODR ^= (GPIO)->usPin
|
||||
#define GPIO_HAL_READ(GPIO) (((GPIO)->pPort->IDR & (GPIO)->usPin) ? 1 : 0)
|
||||
|
||||
#if 0
|
||||
|
||||
/**
|
||||
* @brief 设置IO口的模式
|
||||
* @param ptGpio 相应IO的结构体指针
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalSetMode(const gpioHalDef *ptGpio, gpioHalModeDef mMode);
|
||||
|
||||
/**
|
||||
* @brief 初始化IO,包括开启相应端口时钟,设置IO模式
|
||||
* @param ptGpio 相应IO的结构体指针
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalInit(const gpioHalDef *ptGpio, gpioHalModeDef mMode);
|
||||
|
||||
/**
|
||||
* @brief 初始化IO,开启端口时钟,设置IO模式
|
||||
* @param pPort 端口
|
||||
* @param usPin 时钟
|
||||
* @param mMode IO模式,有如下值
|
||||
* GPIO_Mode_AIN 模拟输入
|
||||
* GPIO_Mode_IN_FLOATING 浮空输入(高阻输入)
|
||||
* GPIO_Mode_IPD 下拉输入
|
||||
* GPIO_Mode_IPU 上拉输入
|
||||
* GPIO_Mode_Out_OD 开漏输出
|
||||
* GPIO_Mode_Out_OD_PU 开漏输出上拉
|
||||
* GPIO_Mode_Out_PP 推挽输出
|
||||
* GPIO_Mode_AF_OD 复用开漏输出
|
||||
* GPIO_Mode_AF_OD_PU 复用开漏输出上拉
|
||||
* GPIO_Mode_AF_PP 复用推挽输出
|
||||
*/
|
||||
void gpioHalInitExt(GPIO_TypeDef *pPort, uint16_t usPin, gpioHalModeDef mMode);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,304 @@
|
||||
#include "main.h"
|
||||
#include "cmsis_os.h"
|
||||
|
||||
|
||||
/* Private includes ----------------------------------------------------------*/
|
||||
/* USER CODE BEGIN Includes */
|
||||
#include "string.h"
|
||||
#include "stm32h7xx_hal.h"
|
||||
#include "stm32h7xx_it.h"
|
||||
|
||||
|
||||
#include "W25QXX/w25qxx.h"
|
||||
#include "Param/param.h"
|
||||
|
||||
#include "IAP/iap.h"
|
||||
#include "CPY_PROT/cpy_prot.h"
|
||||
|
||||
typedef enum {
|
||||
IAP_CMD_ERASE = 0x01,
|
||||
IAP_CMD_WRITE,
|
||||
IAP_CMD_CHECK,
|
||||
} IAP_CMD_DEF;
|
||||
|
||||
#define MAX_PACKET_PARAM_NUM 4
|
||||
|
||||
#pragma pack(1)
|
||||
|
||||
typedef struct __iapPacketDef {
|
||||
uint8_t ucCmd;
|
||||
uint32_t aulParams[MAX_PACKET_PARAM_NUM];
|
||||
uint8_t data[];
|
||||
} iapPacketDef;
|
||||
|
||||
#pragma pack()
|
||||
|
||||
static int init_ok = 0;
|
||||
|
||||
|
||||
uint16_t getBoardTemp(void);
|
||||
|
||||
void systemReboot(void)
|
||||
{
|
||||
__disable_irq();
|
||||
HAL_NVIC_SystemReset();
|
||||
while (1) {
|
||||
__asm("nop");
|
||||
}
|
||||
}
|
||||
|
||||
#define APPLICATION_ADDRESS 0x30000000
|
||||
|
||||
void copyFirmware(void)
|
||||
{
|
||||
uint32_t ulDstAddr = APPLICATION_ADDRESS;
|
||||
uint32_t ulSrcAddr = IAP_START_SECTOR * 4096;
|
||||
uint32_t ullen = 128 * 1024;
|
||||
|
||||
while (ullen >= 1024) {
|
||||
W25QXX_Read((uint8_t *)ulDstAddr, ulSrcAddr, 1024);
|
||||
ulDstAddr += 1024;
|
||||
ulSrcAddr += 1024;
|
||||
ullen -= 1024;
|
||||
}
|
||||
|
||||
if (ullen > 0) {
|
||||
W25QXX_Read((uint8_t *)ulDstAddr, ulSrcAddr, ullen);
|
||||
}
|
||||
ulDstAddr = APPLICATION_ADDRESS;
|
||||
printf("0x%08X \n", ((uint32_t *)ulDstAddr)[0]);
|
||||
}
|
||||
|
||||
void bootJump(void)
|
||||
{
|
||||
static uint32_t JumpAddress;
|
||||
typedef void (*pFunction)(void);
|
||||
static pFunction JumpToApplication;
|
||||
printf("disable irq\n");
|
||||
__disable_irq();
|
||||
SysTick->CTRL = 0x00;
|
||||
|
||||
/* execute the new program */
|
||||
JumpAddress = *(__IO uint32_t*) (0x08000000 + 4);
|
||||
/* Jump to user application */
|
||||
JumpToApplication = (pFunction) JumpAddress;
|
||||
/* Initialize user application's Stack Pointer */
|
||||
printf("set msp\n");
|
||||
__set_MSP(*(__IO uint32_t*) 0x08000000);
|
||||
__set_PSP(*(__IO uint32_t*) 0x08000000);
|
||||
printf("jump\n");
|
||||
JumpToApplication();
|
||||
}
|
||||
|
||||
void appJump(void)
|
||||
{
|
||||
|
||||
printf("jumpto addr : %0X \r\n",*(__IO uint32_t*) (APPLICATION_ADDRESS + 4));
|
||||
|
||||
__disable_irq();
|
||||
|
||||
HAL_DeInit();
|
||||
|
||||
SysTick->CTRL = 0x00;
|
||||
|
||||
/* execute the new program */
|
||||
static uint32_t JumpAddress = 0;
|
||||
JumpAddress = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
|
||||
/* Jump to user application */
|
||||
typedef void (*pFunction)(void);
|
||||
static pFunction JumpToApplication;
|
||||
JumpToApplication = (pFunction) JumpAddress;
|
||||
/* Initialize user application's Stack Pointer */
|
||||
__set_PSP(*(volatile unsigned int*) APPLICATION_ADDRESS);
|
||||
__set_CONTROL(0);
|
||||
__set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
|
||||
JumpToApplication();
|
||||
}
|
||||
|
||||
int checkApp(void)
|
||||
{
|
||||
uint32_t addr;
|
||||
|
||||
copyFirmware();
|
||||
|
||||
addr = *(__IO uint32_t*) (APPLICATION_ADDRESS);
|
||||
if ((addr > 0x24000000) && (addr < (0x24000000 + 0x80000))) {
|
||||
printf("MSP addr : %0X \r\n",addr);
|
||||
|
||||
} else {
|
||||
printf("MSP addr : %0X \r\n",addr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
addr = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
|
||||
if ((addr > 0x30000000) && (addr < (0x30000000 + 0x20000))) {
|
||||
printf("Reset addr : %0X \r\n",addr);
|
||||
} else {
|
||||
printf("Reset addr : %0X \r\n",addr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
int FLASH_If_Erase(uint32_t size)
|
||||
{
|
||||
int start_sector = IAP_START_SECTOR;
|
||||
int num = size / 4096;
|
||||
if (size % 4096) {
|
||||
num++;
|
||||
}
|
||||
for (int i = 0; i < num; ++i) {
|
||||
W25QXX_Erase_Sector((start_sector + i) * 4096);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FLASH_If_verify(uint32_t addr, uint8_t *pucSrc, uint32_t ulLen)
|
||||
{
|
||||
static uint8_t aucbuf[1024];
|
||||
int start_sector = IAP_START_SECTOR;
|
||||
|
||||
addr = addr + start_sector * 4096;
|
||||
|
||||
while (ulLen >= 256) {
|
||||
W25QXX_Read(aucbuf, addr, 256);
|
||||
if (memcmp(aucbuf, pucSrc, 256) != 0) {
|
||||
printf("verify failed at 0x%08X\n", addr);
|
||||
return -1;
|
||||
}
|
||||
pucSrc += 256;
|
||||
addr += 256;
|
||||
ulLen -= 256;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Read(aucbuf, addr, ulLen);
|
||||
if (memcmp(aucbuf, pucSrc, ulLen) != 0) {
|
||||
printf("verify failed at 0x%08X\n", addr);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FLASH_If_Write(uint32_t addr, uint8_t *pucSrc, uint32_t ulLen)
|
||||
{
|
||||
int start_sector = IAP_START_SECTOR;
|
||||
|
||||
addr = addr + start_sector * 4096;
|
||||
|
||||
while (ulLen >= 256) {
|
||||
W25QXX_Page_Program(pucSrc, addr, 256);
|
||||
pucSrc += 256;
|
||||
addr += 256;
|
||||
ulLen -= 256;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Page_Program(pucSrc, addr, ulLen);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int iapPacketHandler(const uint8_t *packet)
|
||||
{
|
||||
iapPacketDef *pkt = (iapPacketDef *)packet;
|
||||
switch (pkt->ucCmd) {
|
||||
case IAP_CMD_ERASE:
|
||||
{
|
||||
uint32_t len = pkt->aulParams[0];
|
||||
if (len > 0) {
|
||||
FLASH_If_Erase(len);
|
||||
char *str = "erase success";
|
||||
daq_send_packet( CPY_PROT_CMD_IAP | CPY_PROT_CMD_ACK, (uint8_t *)str, strlen(str));
|
||||
} else {
|
||||
char *str = "erase failed";
|
||||
daq_send_packet( CPY_PROT_CMD_IAP | CPY_PROT_CMD_ERROR, (uint8_t *)str, strlen(str));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case IAP_CMD_WRITE:
|
||||
{
|
||||
uint32_t addr = pkt->aulParams[0];
|
||||
uint32_t len = pkt->aulParams[1];
|
||||
int ret = FLASH_If_Write(addr, pkt->data, len);
|
||||
ret = FLASH_If_verify(addr, pkt->data, len);
|
||||
if (ret == 0) {
|
||||
printf("write success at %d\n", addr);
|
||||
char *str = "write success";
|
||||
daq_send_packet( CPY_PROT_CMD_IAP | CPY_PROT_CMD_ACK, (uint8_t *)str, strlen(str));
|
||||
} else {
|
||||
printf("write failed at %d\n", addr);
|
||||
char *str = "write failed";
|
||||
daq_send_packet( CPY_PROT_CMD_IAP | CPY_PROT_CMD_ERROR, (uint8_t *)str, strlen(str));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case IAP_CMD_CHECK:
|
||||
{
|
||||
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef BOOTLOADER
|
||||
static int bootBlockingFlag = 0;
|
||||
void blockInBootloader(int block)
|
||||
{
|
||||
if (block) {
|
||||
bootBlockingFlag = 1;
|
||||
} else {
|
||||
bootBlockingFlag = 0;
|
||||
}
|
||||
|
||||
static uint32_t val;
|
||||
W25QXX_Read((uint8_t *)&val, IAP_START_SECTOR * 4096, 4);
|
||||
printf("0x%08X \n", val);
|
||||
}
|
||||
#endif
|
||||
|
||||
int giIapThreadStatus = 0;
|
||||
|
||||
static void iapThread(void *arg)
|
||||
{
|
||||
|
||||
printf("iapThread running ... \r\n");
|
||||
|
||||
osDelay(3000);
|
||||
|
||||
#ifdef BOOTLOADER
|
||||
while(1) {
|
||||
if (bootBlockingFlag == 0) {
|
||||
if (checkApp()) {
|
||||
appJump();
|
||||
}
|
||||
}
|
||||
osDelay(1000);
|
||||
}
|
||||
#else
|
||||
while(1) {
|
||||
osDelay(1000);
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
void iapThreadInit(void)
|
||||
{
|
||||
const osThreadAttr_t Task_attributes = {
|
||||
.name = "iap_thread",
|
||||
.stack_size = 4096 * 4,
|
||||
.priority = (osPriority_t) osPriorityNormal,
|
||||
};
|
||||
if (osThreadNew(iapThread, NULL, &Task_attributes) == NULL)
|
||||
{
|
||||
printf("failed to create iap_thread\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef IAP_H
|
||||
#define IAP_H
|
||||
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "main.h"
|
||||
/* Exported types ------------------------------------------------------------*/
|
||||
|
||||
#define IAP_START_SECTOR 16
|
||||
|
||||
void systemReboot(void);
|
||||
int iapPacketHandler(const uint8_t *packet);
|
||||
void blockInBootloader(int block);
|
||||
void iapThreadInit(void);
|
||||
|
||||
|
||||
#endif // IAP_H
|
||||
@@ -0,0 +1,87 @@
|
||||
#include "param.h"
|
||||
|
||||
#include "W25QXX/w25qxx.h"
|
||||
|
||||
sysParamDef _gtSystemParam;
|
||||
sysOtpInfoDef _gtOtpInfo;
|
||||
|
||||
sysParamDef *gptSysParam = &_gtSystemParam;
|
||||
sysOtpInfoDef *gptOtpInfo = &_gtOtpInfo;
|
||||
|
||||
int loadSysParam(void)
|
||||
{
|
||||
debug("load param");
|
||||
W25QXX_Read((uint8_t *)gptSysParam, FLASH_PART_PARAM_START, sizeof(sysParamDef));
|
||||
|
||||
dump((uint8_t *)(gptSysParam), sizeof(sysParamDef));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void saveSysParam(void)
|
||||
{
|
||||
|
||||
debug("save param");
|
||||
dump((uint8_t *)(gptSysParam), sizeof(sysParamDef));
|
||||
|
||||
W25QXX_Erase_Sector(FLASH_PART_PARAM_START);
|
||||
|
||||
W25QXX_Page_Program((uint8_t *)(gptSysParam), FLASH_PART_PARAM_START, sizeof(sysParamDef));
|
||||
}
|
||||
|
||||
const sysOtpInfoDef *loadOtpInfo(void)
|
||||
{
|
||||
debug("load otp info");
|
||||
W25QXX_Read((uint8_t *)gptOtpInfo, FLASH_PART_OTP_START, sizeof(sysOtpInfoDef));
|
||||
|
||||
dump((uint8_t *)(gptOtpInfo), sizeof(sysOtpInfoDef));
|
||||
|
||||
return gptOtpInfo;
|
||||
}
|
||||
|
||||
int saveOtpInfo(const sysOtpInfoDef *otpInfo)
|
||||
{
|
||||
debug("save otp info");
|
||||
dump((uint8_t *)(otpInfo), sizeof(sysOtpInfoDef));
|
||||
if (otpInfo == NULL)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
loadOtpInfo();
|
||||
|
||||
for (int i = 0; i < sizeof(sysOtpInfoDef); i++)
|
||||
{
|
||||
if (((uint8_t *)gptOtpInfo)[i] != 0xFF)
|
||||
{
|
||||
debug("write failed, otp info is not empty");
|
||||
return -2;
|
||||
}
|
||||
}
|
||||
|
||||
W25QXX_Page_Program((uint8_t *)(otpInfo), FLASH_PART_OTP_START, sizeof(sysOtpInfoDef));
|
||||
|
||||
loadOtpInfo();
|
||||
|
||||
if (memcmp((uint8_t *)gptOtpInfo, (uint8_t *)otpInfo, sizeof(sysOtpInfoDef)) != 0)
|
||||
{
|
||||
debug("write failed, otp info is not equal");
|
||||
return -3;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void systemResetFactory(void)
|
||||
{
|
||||
debug("reset factory");
|
||||
for (uint32_t i = FLASH_PART_PARAM_START; i < FLASH_PART_PARAM_END; i += W25QXX_SECTOR_SIZE)
|
||||
{
|
||||
W25QXX_Erase_Sector(i);
|
||||
}
|
||||
for (uint32_t i = FLASH_PART_OTP_START; i < FLASH_PART_OTP_END; i += W25QXX_SECTOR_SIZE)
|
||||
{
|
||||
W25QXX_Erase_Sector(i);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef PARAM_H
|
||||
#define PARAM_H
|
||||
#include "main.h"
|
||||
|
||||
#pragma pack(1)
|
||||
typedef struct __sysParamDef
|
||||
{
|
||||
uint16_t usAdcPeriod; ///< 定时采样周期 微秒
|
||||
uint16_t usAdcinterval; ///< 定距采样间隔 微米
|
||||
uint8_t ucUseEncoder; ///< 启用编码器
|
||||
uint8_t ucAverageCount; ///< 平均次数
|
||||
} sysParamDef;
|
||||
|
||||
typedef struct __sysOtpInfoDef
|
||||
{
|
||||
char aucModel[32];
|
||||
char aucDate[32];
|
||||
char aucSn[32];
|
||||
} sysOtpInfoDef;
|
||||
|
||||
#pragma pack()
|
||||
|
||||
extern sysParamDef *gptSysParam;
|
||||
|
||||
int loadSysParam(void);
|
||||
void saveSysParam(void);
|
||||
|
||||
const sysOtpInfoDef *loadOtpInfo(void);
|
||||
int saveOtpInfo(const sysOtpInfoDef *otpInfo);
|
||||
|
||||
void systemResetFactory(void);
|
||||
|
||||
|
||||
#endif // PARAM_H
|
||||
@@ -0,0 +1,67 @@
|
||||
# UDP大数据包发送模块
|
||||
|
||||
## 功能描述
|
||||
|
||||
`udpSendBigPacket` 函数用于将大数据包(最大60KB)拆分成多个小包发送。每个小包的有效载荷最大为1024字节,包含包头信息。
|
||||
|
||||
## 包头结构
|
||||
|
||||
每个发送的包都包含以下包头信息:
|
||||
|
||||
```c
|
||||
typedef struct {
|
||||
uint16_t magic; // 魔数 (0xAA55)
|
||||
uint16_t total_size; // 总数据大小
|
||||
uint32_t big_packet_id; // 大包ID,32位随机整数,用于区分不同的大包
|
||||
uint16_t packet_id; // 包序号 (0, 1, 2, ...)
|
||||
uint16_t total_packets; // 总包数
|
||||
uint16_t payload_len; // 当前包的有效载荷长度
|
||||
uint8_t reserved[2]; // 保留字段
|
||||
} udp_packet_header_t;
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
```c
|
||||
#include "udp.h"
|
||||
|
||||
// 准备要发送的数据
|
||||
uint8_t data[5000]; // 5KB数据
|
||||
// ... 填充数据 ...
|
||||
|
||||
// 发送大数据包
|
||||
int result = udpSendBigPacket(data, 5000, "192.168.1.100", 8080);
|
||||
if (result >= 0) {
|
||||
printf("发送成功\n");
|
||||
} else {
|
||||
printf("发送失败,错误码: %d\n", result);
|
||||
}
|
||||
```
|
||||
|
||||
## 错误码说明
|
||||
|
||||
- `0`: 发送成功
|
||||
- `-1`: 参数错误(空指针、长度超出范围等)
|
||||
- `-2`: 内存分配失败
|
||||
- 其他负值: `udpSendTo` 函数返回的错误码
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 函数会自动将数据拆分成多个包发送,无需手动处理
|
||||
2. 每个包都会包含完整的包头信息
|
||||
3. 第一包会指定总数据大小,便于接收端重组
|
||||
4. 函数不等待回复,采用异步发送方式
|
||||
5. 最大支持60KB的数据包
|
||||
6. 每个包的有效载荷最大1024字节
|
||||
7. 每个大包都有唯一的32位随机ID,用于区分并发传输的不同大包
|
||||
8. 大包ID使用 `rand()` 函数生成,确保唯一性
|
||||
|
||||
## 接收端处理
|
||||
|
||||
接收端需要:
|
||||
1. 检查魔数 (0xAA55)
|
||||
2. 根据 `big_packet_id` 区分不同的大包
|
||||
3. 根据 `total_size` 和 `total_packets` 分配缓冲区
|
||||
4. 按 `packet_id` 顺序重组数据
|
||||
5. 验证所有包是否接收完整
|
||||
6. 使用 `big_packet_id` 可以同时处理多个并发的大包传输
|
||||
@@ -0,0 +1,164 @@
|
||||
# UDP大数据包接收端 (Python实现)
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **多发送方支持**: 可以同时处理多个发送方的并发传输
|
||||
- **超时机制**: 1秒超时,超时的包自动丢弃
|
||||
- **包重组**: 自动将分散的小包重组成完整数据
|
||||
- **线程安全**: 使用锁机制确保多线程环境下的数据安全
|
||||
- **实时日志**: 详细的日志输出,便于调试和监控
|
||||
|
||||
## 安装和运行
|
||||
|
||||
### 基本运行
|
||||
|
||||
```bash
|
||||
# 启动接收端(默认监听8080端口)
|
||||
python udp_receiver.py
|
||||
|
||||
# 指定端口
|
||||
python udp_receiver.py --port 9000
|
||||
|
||||
# 指定监听地址
|
||||
python udp_receiver.py --host 192.168.1.100 --port 8080
|
||||
|
||||
# 启用调试日志
|
||||
python udp_receiver.py --debug
|
||||
```
|
||||
|
||||
### 参数说明
|
||||
|
||||
- `--host`: 监听地址 (默认: 0.0.0.0)
|
||||
- `--port`: 监听端口 (默认: 8080)
|
||||
- `--timeout`: 包超时时间,秒 (默认: 1.0)
|
||||
- `--debug`: 启用调试日志
|
||||
|
||||
## 测试
|
||||
|
||||
### 使用测试发送端
|
||||
|
||||
```bash
|
||||
# 测试单个发送端
|
||||
python test_sender.py --test single
|
||||
|
||||
# 测试多个发送端同时发送
|
||||
python test_sender.py --test multiple
|
||||
|
||||
# 测试超时场景
|
||||
python test_sender.py --test timeout
|
||||
```
|
||||
|
||||
### 手动测试
|
||||
|
||||
```bash
|
||||
# 终端1: 启动接收端
|
||||
python udp_receiver.py --debug
|
||||
|
||||
# 终端2: 启动发送端
|
||||
python test_sender.py --test single
|
||||
```
|
||||
|
||||
## 核心类说明
|
||||
|
||||
### UDPPacketHeader
|
||||
包头解析类,与C端保持一致的包头结构:
|
||||
```python
|
||||
class UDPPacketHeader:
|
||||
MAGIC = 0xAA55
|
||||
HEADER_SIZE = 16
|
||||
|
||||
# 字段: magic, total_size, big_packet_id, packet_id, total_packets, payload_len
|
||||
```
|
||||
|
||||
### PacketReassembler
|
||||
包重组器,负责单个大包的重组:
|
||||
- 管理包的重组状态
|
||||
- 检查超时
|
||||
- 按序号重组数据
|
||||
|
||||
### UDPReceiver
|
||||
主接收端类:
|
||||
- 监听UDP端口
|
||||
- 管理多个重组器
|
||||
- 处理并发传输
|
||||
- 自动清理超时包
|
||||
|
||||
## 工作流程
|
||||
|
||||
1. **接收包**: 监听UDP端口,接收数据包
|
||||
2. **解析包头**: 验证魔数,解析包头信息
|
||||
3. **创建/获取重组器**: 根据发送方地址和大包ID创建或获取重组器
|
||||
4. **添加包**: 将包添加到对应的重组器
|
||||
5. **检查完成**: 检查是否所有包都已接收
|
||||
6. **重组数据**: 按序号重组完整数据
|
||||
7. **处理数据**: 保存或处理重组后的数据
|
||||
8. **清理**: 自动清理超时的包
|
||||
|
||||
## 超时机制
|
||||
|
||||
- **超时时间**: 1秒(可配置)
|
||||
- **检查频率**: 每0.5秒检查一次
|
||||
- **清理策略**: 超时的包自动丢弃,释放内存
|
||||
- **日志记录**: 超时事件会记录到日志
|
||||
|
||||
## 并发处理
|
||||
|
||||
- **多发送方**: 支持多个发送方同时发送
|
||||
- **大包ID**: 使用32位随机ID区分不同的大包
|
||||
- **线程安全**: 使用锁机制保护共享数据
|
||||
- **独立重组**: 每个大包有独立的重组器
|
||||
|
||||
## 日志输出
|
||||
|
||||
### 信息级别
|
||||
- `INFO`: 重要事件(启动、完成、创建重组器)
|
||||
- `WARNING`: 警告事件(超时、错误)
|
||||
- `ERROR`: 错误事件(解析失败、网络错误)
|
||||
- `DEBUG`: 调试信息(包接收详情)
|
||||
|
||||
### 日志示例
|
||||
```
|
||||
2024-01-01 12:00:00,000 - INFO - UDP接收端启动,监听 0.0.0.0:8080
|
||||
2024-01-01 12:00:01,123 - INFO - 创建新的大包重组器: ID=12345, 大小=5000, 包数=5, 来源=('192.168.1.100', 12345)
|
||||
2024-01-01 12:00:01,234 - DEBUG - 接收包 1/5 来自 ('192.168.1.100', 12345), 大包ID: 12345
|
||||
2024-01-01 12:00:01,345 - INFO - 大包 12345 重组完成,大小: 5000 字节
|
||||
2024-01-01 12:00:01,456 - INFO - 收到完整数据包: 大小=5000 字节, 来源=('192.168.1.100', 12345), ID=12345
|
||||
2024-01-01 12:00:02,000 - WARNING - 清理超时的大包: ID=67890, 来源=('192.168.1.101', 54321), 已接收=2/5
|
||||
```
|
||||
|
||||
## 数据保存
|
||||
|
||||
默认情况下,接收到的完整数据会保存为二进制文件:
|
||||
- 文件名格式: `received_data_{big_packet_id}_{timestamp}.bin`
|
||||
- 可以修改 `_handle_completed_packet` 方法来自定义数据处理逻辑
|
||||
|
||||
## 性能考虑
|
||||
|
||||
- **内存使用**: 每个重组器占用少量内存,超时后自动释放
|
||||
- **CPU使用**: 轻量级处理,适合高并发场景
|
||||
- **网络效率**: 支持大包传输,减少网络开销
|
||||
- **扩展性**: 模块化设计,易于扩展功能
|
||||
|
||||
## 错误处理
|
||||
|
||||
- **网络错误**: 自动重试,记录错误日志
|
||||
- **数据错误**: 验证包头,丢弃无效数据
|
||||
- **超时处理**: 自动清理,防止内存泄漏
|
||||
- **异常恢复**: 优雅处理异常,保持服务稳定
|
||||
|
||||
## 与C端兼容性
|
||||
|
||||
Python接收端完全兼容C端发送的包格式:
|
||||
- 相同的包头结构
|
||||
- 相同的魔数 (0xAA55)
|
||||
- 相同的字节序 (小端序)
|
||||
- 相同的字段定义
|
||||
|
||||
## 扩展建议
|
||||
|
||||
1. **数据验证**: 添加CRC校验
|
||||
2. **压缩支持**: 支持数据压缩
|
||||
3. **加密传输**: 添加数据加密
|
||||
4. **统计监控**: 添加传输统计
|
||||
5. **配置管理**: 支持配置文件
|
||||
6. **API接口**: 提供REST API接口
|
||||
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
UDP大数据包发送端测试程序
|
||||
用于测试接收端的功能
|
||||
"""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import random
|
||||
import time
|
||||
import threading
|
||||
from typing import List
|
||||
|
||||
# 包头结构定义 (与C端保持一致)
|
||||
class UDPPacketHeader:
|
||||
"""UDP包头结构"""
|
||||
MAGIC = 0xAA55
|
||||
HEADER_SIZE = 16
|
||||
|
||||
def __init__(self, magic: int, total_size: int, big_packet_id: int,
|
||||
packet_id: int, total_packets: int, payload_len: int):
|
||||
self.magic = magic
|
||||
self.total_size = total_size
|
||||
self.big_packet_id = big_packet_id
|
||||
self.packet_id = packet_id
|
||||
self.total_packets = total_packets
|
||||
self.payload_len = payload_len
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
"""转换为字节数据"""
|
||||
return struct.pack('<HHIHHH',
|
||||
self.magic, self.total_size, self.big_packet_id,
|
||||
self.packet_id, self.total_packets, self.payload_len)
|
||||
|
||||
class UDPSender:
|
||||
"""UDP发送端"""
|
||||
|
||||
def __init__(self, target_host: str, target_port: int):
|
||||
self.target_host = target_host
|
||||
self.target_port = target_port
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
|
||||
def send_big_packet(self, data: bytes, delay: float = 0.0) -> int:
|
||||
"""
|
||||
发送大数据包
|
||||
"""
|
||||
if len(data) > 60 * 1024: # 60KB限制
|
||||
raise ValueError("数据太大,超过60KB限制")
|
||||
|
||||
# 生成随机大包ID
|
||||
big_packet_id = random.randint(1, 0xFFFFFFFF)
|
||||
|
||||
# 计算包数量
|
||||
max_payload_size = 1024
|
||||
total_packets = (len(data) + max_payload_size - 1) // max_payload_size
|
||||
|
||||
print(f"发送大包: ID={big_packet_id}, 大小={len(data)} 字节, 包数={total_packets}")
|
||||
|
||||
# 发送所有包
|
||||
for packet_id in range(total_packets):
|
||||
# 计算当前包的载荷
|
||||
start_offset = packet_id * max_payload_size
|
||||
end_offset = min(start_offset + max_payload_size, len(data))
|
||||
payload = data[start_offset:end_offset]
|
||||
payload_len = len(payload)
|
||||
|
||||
# 创建包头
|
||||
header = UDPPacketHeader(
|
||||
magic=UDPPacketHeader.MAGIC,
|
||||
total_size=len(data),
|
||||
big_packet_id=big_packet_id,
|
||||
packet_id=packet_id,
|
||||
total_packets=total_packets,
|
||||
payload_len=payload_len
|
||||
)
|
||||
|
||||
# 组装完整包
|
||||
packet = header.to_bytes() + payload
|
||||
|
||||
# 发送包
|
||||
self.socket.sendto(packet, (self.target_host, self.target_port))
|
||||
|
||||
print(f" 发送包 {packet_id + 1}/{total_packets}, 载荷大小: {payload_len}")
|
||||
|
||||
# 延迟(模拟网络延迟)
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
|
||||
return big_packet_id
|
||||
|
||||
def close(self):
|
||||
"""关闭socket"""
|
||||
self.socket.close()
|
||||
|
||||
def generate_test_data(size: int) -> bytes:
|
||||
"""生成测试数据"""
|
||||
return bytes([random.randint(0, 255) for _ in range(size)])
|
||||
|
||||
def test_single_sender():
|
||||
"""测试单个发送端"""
|
||||
sender = UDPSender('127.0.0.1', 8080)
|
||||
|
||||
try:
|
||||
# 发送不同大小的数据包
|
||||
test_sizes = [100, 1000, 5000, 10000, 30000]
|
||||
|
||||
for size in test_sizes:
|
||||
print(f"\n=== 测试发送 {size} 字节数据 ===")
|
||||
data = generate_test_data(size)
|
||||
big_packet_id = sender.send_big_packet(data, delay=0.01)
|
||||
print(f"大包 {big_packet_id} 发送完成")
|
||||
time.sleep(0.5) # 等待接收端处理
|
||||
|
||||
finally:
|
||||
sender.close()
|
||||
|
||||
def test_multiple_senders():
|
||||
"""测试多个发送端同时发送"""
|
||||
def sender_thread(sender_id: int, data_size: int):
|
||||
sender = UDPSender('127.0.0.1', 8080)
|
||||
try:
|
||||
data = generate_test_data(data_size)
|
||||
big_packet_id = sender.send_big_packet(data, delay=0.02)
|
||||
print(f"发送端 {sender_id}: 大包 {big_packet_id} 发送完成")
|
||||
finally:
|
||||
sender.close()
|
||||
|
||||
# 创建多个发送线程
|
||||
threads = []
|
||||
for i in range(3):
|
||||
data_size = random.randint(1000, 10000)
|
||||
thread = threading.Thread(target=sender_thread, args=(i, data_size))
|
||||
threads.append(thread)
|
||||
thread.start()
|
||||
|
||||
# 等待所有线程完成
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
print("所有发送端完成")
|
||||
|
||||
def test_timeout_scenario():
|
||||
"""测试超时场景(故意延迟发送)"""
|
||||
sender = UDPSender('127.0.0.1', 8080)
|
||||
|
||||
try:
|
||||
print("=== 测试超时场景 ===")
|
||||
data = generate_test_data(5000)
|
||||
|
||||
# 只发送前几个包,然后等待超时
|
||||
big_packet_id = random.randint(1, 0xFFFFFFFF)
|
||||
total_packets = (len(data) + 1024 - 1) // 1024
|
||||
|
||||
for packet_id in range(min(3, total_packets)): # 只发送前3个包
|
||||
start_offset = packet_id * 1024
|
||||
end_offset = min(start_offset + 1024, len(data))
|
||||
payload = data[start_offset:end_offset]
|
||||
|
||||
header = UDPPacketHeader(
|
||||
magic=UDPPacketHeader.MAGIC,
|
||||
total_size=len(data),
|
||||
big_packet_id=big_packet_id,
|
||||
packet_id=packet_id,
|
||||
total_packets=total_packets,
|
||||
payload_len=len(payload)
|
||||
)
|
||||
|
||||
packet = header.to_bytes() + payload
|
||||
sender.socket.sendto(packet, (sender.target_host, sender.target_port))
|
||||
print(f"发送包 {packet_id + 1}/{total_packets} (故意不发送完整)")
|
||||
|
||||
print("等待超时...")
|
||||
time.sleep(2) # 等待超时
|
||||
|
||||
finally:
|
||||
sender.close()
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='UDP大数据包发送端测试程序')
|
||||
parser.add_argument('--host', default='127.0.0.1', help='目标主机 (默认: 127.0.0.1)')
|
||||
parser.add_argument('--port', type=int, default=8080, help='目标端口 (默认: 8080)')
|
||||
parser.add_argument('--test', choices=['single', 'multiple', 'timeout'],
|
||||
default='single', help='测试类型 (默认: single)')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"UDP发送端测试程序")
|
||||
print(f"目标: {args.host}:{args.port}")
|
||||
print(f"测试类型: {args.test}")
|
||||
|
||||
if args.test == 'single':
|
||||
test_single_sender()
|
||||
elif args.test == 'multiple':
|
||||
test_multiple_senders()
|
||||
elif args.test == 'timeout':
|
||||
test_timeout_scenario()
|
||||
|
||||
print("测试完成")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
UDP大数据包接收端
|
||||
支持多个发送方同时发送,包含1秒超时机制
|
||||
"""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
import logging
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 包头结构定义 (与C端保持一致)
|
||||
class UDPPacketHeader:
|
||||
"""UDP包头结构"""
|
||||
MAGIC = 0xAA55
|
||||
HEADER_SIZE = 16 # 包头大小
|
||||
|
||||
def __init__(self, data: bytes):
|
||||
"""
|
||||
从字节数据解析包头
|
||||
"""
|
||||
if len(data) < self.HEADER_SIZE:
|
||||
raise ValueError("数据长度不足,无法解析包头")
|
||||
|
||||
# 解析包头字段 (小端序)
|
||||
(self.magic, self.total_size, self.big_packet_id,
|
||||
self.packet_id, self.total_packets, self.payload_len) = struct.unpack('<HHIHHH', data[:16])
|
||||
|
||||
# 验证魔数
|
||||
if self.magic != self.MAGIC:
|
||||
raise ValueError(f"无效的魔数: {self.magic:04X}, 期望: {self.MAGIC:04X}")
|
||||
|
||||
class PacketReassembler:
|
||||
"""包重组器,处理单个大包的重组"""
|
||||
|
||||
def __init__(self, big_packet_id: int, total_size: int, total_packets: int,
|
||||
sender_addr: Tuple[str, int], timeout: float = 1.0):
|
||||
self.big_packet_id = big_packet_id
|
||||
self.total_size = total_size
|
||||
self.total_packets = total_packets
|
||||
self.sender_addr = sender_addr
|
||||
self.timeout = timeout
|
||||
self.start_time = time.time()
|
||||
|
||||
# 存储接收到的包
|
||||
self.packets: Dict[int, bytes] = {}
|
||||
self.received_count = 0
|
||||
self.completed = False
|
||||
self.data = None
|
||||
|
||||
def add_packet(self, packet_id: int, payload: bytes) -> bool:
|
||||
"""
|
||||
添加一个包到重组器
|
||||
返回True如果包是新接收的,False如果包已存在
|
||||
"""
|
||||
if packet_id in self.packets:
|
||||
return False # 包已存在
|
||||
|
||||
self.packets[packet_id] = payload
|
||||
self.received_count += 1
|
||||
|
||||
# 检查是否所有包都已接收
|
||||
if self.received_count == self.total_packets:
|
||||
self._reassemble()
|
||||
return True
|
||||
|
||||
return True
|
||||
|
||||
def _reassemble(self):
|
||||
"""重组完整数据"""
|
||||
try:
|
||||
# 按包序号排序
|
||||
sorted_packets = sorted(self.packets.items())
|
||||
|
||||
# 重组数据
|
||||
reassembled_data = b''
|
||||
for packet_id, payload in sorted_packets:
|
||||
reassembled_data += payload
|
||||
|
||||
# 截取到指定长度
|
||||
self.data = reassembled_data[:self.total_size]
|
||||
self.completed = True
|
||||
|
||||
logger.info(f"大包 {self.big_packet_id} 重组完成,大小: {len(self.data)} 字节")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"重组大包 {self.big_packet_id} 时出错: {e}")
|
||||
|
||||
def is_timeout(self) -> bool:
|
||||
"""检查是否超时"""
|
||||
return time.time() - self.start_time > self.timeout
|
||||
|
||||
def is_completed(self) -> bool:
|
||||
"""检查是否完成重组"""
|
||||
return self.completed
|
||||
|
||||
def get_data(self) -> Optional[bytes]:
|
||||
"""获取重组后的数据"""
|
||||
return self.data if self.completed else None
|
||||
|
||||
class UDPReceiver:
|
||||
"""UDP接收端主类"""
|
||||
|
||||
def __init__(self, host: str = '0.0.0.0', port: int = 8080, timeout: float = 1.0):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.timeout = timeout
|
||||
self.socket = None
|
||||
self.running = False
|
||||
|
||||
# 存储所有正在重组的大包
|
||||
# key: (sender_addr, big_packet_id), value: PacketReassembler
|
||||
self.reassemblers: Dict[Tuple[Tuple[str, int], int], PacketReassembler] = {}
|
||||
self.reassembler_lock = threading.Lock()
|
||||
|
||||
# 清理线程
|
||||
self.cleanup_thread = None
|
||||
|
||||
def start(self):
|
||||
"""启动接收端"""
|
||||
try:
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.socket.bind((self.host, self.port))
|
||||
self.socket.settimeout(0.1) # 设置socket超时,用于检查停止信号
|
||||
|
||||
self.running = True
|
||||
logger.info(f"UDP接收端启动,监听 {self.host}:{self.port}")
|
||||
|
||||
# 启动清理线程
|
||||
self.cleanup_thread = threading.Thread(target=self._cleanup_timeout_packets, daemon=True)
|
||||
self.cleanup_thread.start()
|
||||
|
||||
# 主接收循环
|
||||
self._receive_loop()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"启动接收端失败: {e}")
|
||||
self.stop()
|
||||
|
||||
def stop(self):
|
||||
"""停止接收端"""
|
||||
self.running = False
|
||||
if self.socket:
|
||||
self.socket.close()
|
||||
logger.info("UDP接收端已停止")
|
||||
|
||||
def _receive_loop(self):
|
||||
"""主接收循环"""
|
||||
while self.running:
|
||||
try:
|
||||
data, addr = self.socket.recvfrom(2048) # 最大接收2048字节
|
||||
self._process_packet(data, addr)
|
||||
|
||||
except socket.timeout:
|
||||
continue # 超时继续循环
|
||||
except Exception as e:
|
||||
if self.running: # 只有在运行状态下才记录错误
|
||||
logger.error(f"接收数据时出错: {e}")
|
||||
|
||||
def _process_packet(self, data: bytes, addr: Tuple[str, int]):
|
||||
"""处理接收到的数据包"""
|
||||
try:
|
||||
# 解析包头
|
||||
header = UDPPacketHeader(data)
|
||||
|
||||
# 提取载荷数据
|
||||
payload = data[UDPPacketHeader.HEADER_SIZE:UDPPacketHeader.HEADER_SIZE + header.payload_len]
|
||||
|
||||
# 获取或创建重组器
|
||||
reassembler = self._get_or_create_reassembler(header, addr)
|
||||
|
||||
if reassembler is None:
|
||||
return # 超时或无效的包
|
||||
|
||||
# 添加包到重组器
|
||||
if reassembler.add_packet(header.packet_id, payload):
|
||||
logger.debug(f"接收包 {header.packet_id}/{header.total_packets} "
|
||||
f"来自 {addr}, 大包ID: {header.big_packet_id}")
|
||||
|
||||
# 检查是否完成重组
|
||||
if reassembler.is_completed():
|
||||
self._handle_completed_packet(reassembler)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理来自 {addr} 的数据包时出错: {e}")
|
||||
|
||||
def _get_or_create_reassembler(self, header: UDPPacketHeader, addr: Tuple[str, int]) -> Optional[PacketReassembler]:
|
||||
"""获取或创建包重组器"""
|
||||
key = (addr, header.big_packet_id)
|
||||
|
||||
with self.reassembler_lock:
|
||||
# 检查是否已存在
|
||||
if key in self.reassemblers:
|
||||
reassembler = self.reassemblers[key]
|
||||
|
||||
# 检查是否超时
|
||||
if reassembler.is_timeout():
|
||||
logger.warning(f"大包 {header.big_packet_id} 超时,丢弃")
|
||||
del self.reassemblers[key]
|
||||
return None
|
||||
|
||||
return reassembler
|
||||
|
||||
# 创建新的重组器
|
||||
reassembler = PacketReassembler(
|
||||
header.big_packet_id,
|
||||
header.total_size,
|
||||
header.total_packets,
|
||||
addr,
|
||||
self.timeout
|
||||
)
|
||||
|
||||
self.reassemblers[key] = reassembler
|
||||
logger.info(f"创建新的大包重组器: ID={header.big_packet_id}, "
|
||||
f"大小={header.total_size}, 包数={header.total_packets}, 来源={addr}")
|
||||
|
||||
return reassembler
|
||||
|
||||
def _handle_completed_packet(self, reassembler: PacketReassembler):
|
||||
"""处理完成重组的数据包"""
|
||||
data = reassembler.get_data()
|
||||
if data:
|
||||
# 这里可以添加自定义的数据处理逻辑
|
||||
logger.info(f"收到完整数据包: 大小={len(data)} 字节, "
|
||||
f"来源={reassembler.sender_addr}, ID={reassembler.big_packet_id}")
|
||||
|
||||
# 示例:保存到文件
|
||||
filename = f"received_data_{reassembler.big_packet_id}_{int(time.time())}.bin"
|
||||
with open(filename, 'wb') as f:
|
||||
f.write(data)
|
||||
logger.info(f"数据已保存到文件: {filename}")
|
||||
|
||||
# 从重组器列表中移除
|
||||
with self.reassembler_lock:
|
||||
key = (reassembler.sender_addr, reassembler.big_packet_id)
|
||||
if key in self.reassemblers:
|
||||
del self.reassemblers[key]
|
||||
|
||||
def _cleanup_timeout_packets(self):
|
||||
"""清理超时的包(在后台线程中运行)"""
|
||||
while self.running:
|
||||
time.sleep(0.5) # 每0.5秒检查一次
|
||||
|
||||
with self.reassembler_lock:
|
||||
timeout_keys = []
|
||||
for key, reassembler in self.reassemblers.items():
|
||||
if reassembler.is_timeout():
|
||||
timeout_keys.append(key)
|
||||
|
||||
# 移除超时的包
|
||||
for key in timeout_keys:
|
||||
reassembler = self.reassemblers[key]
|
||||
logger.warning(f"清理超时的大包: ID={reassembler.big_packet_id}, "
|
||||
f"来源={reassembler.sender_addr}, "
|
||||
f"已接收={reassembler.received_count}/{reassembler.total_packets}")
|
||||
del self.reassemblers[key]
|
||||
|
||||
def get_stats(self) -> Dict:
|
||||
"""获取统计信息"""
|
||||
with self.reassembler_lock:
|
||||
return {
|
||||
'active_reassemblers': len(self.reassemblers),
|
||||
'reassemblers': [
|
||||
{
|
||||
'big_packet_id': r.big_packet_id,
|
||||
'sender': r.sender_addr,
|
||||
'received': r.received_count,
|
||||
'total': r.total_packets,
|
||||
'progress': f"{r.received_count}/{r.total_packets}",
|
||||
'time_elapsed': time.time() - r.start_time
|
||||
}
|
||||
for r in self.reassemblers.values()
|
||||
]
|
||||
}
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='UDP大数据包接收端')
|
||||
parser.add_argument('--host', default='0.0.0.0', help='监听地址 (默认: 0.0.0.0)')
|
||||
parser.add_argument('--port', type=int, default=8080, help='监听端口 (默认: 8080)')
|
||||
parser.add_argument('--timeout', type=float, default=1.0, help='包超时时间,秒 (默认: 1.0)')
|
||||
parser.add_argument('--debug', action='store_true', help='启用调试日志')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.debug:
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
|
||||
# 创建并启动接收端
|
||||
receiver = UDPReceiver(args.host, args.port, args.timeout)
|
||||
|
||||
try:
|
||||
# 启动接收端
|
||||
receiver.start()
|
||||
except KeyboardInterrupt:
|
||||
logger.info("收到中断信号,正在停止...")
|
||||
receiver.stop()
|
||||
except Exception as e:
|
||||
logger.error(f"运行时出错: {e}")
|
||||
receiver.stop()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,253 @@
|
||||
import socket
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import psutil
|
||||
import struct
|
||||
import csv
|
||||
from config import *
|
||||
from x_ray_data_processor import processor
|
||||
from PySide6.QtCore import QObject, Signal, Slot, QThread,QTimer
|
||||
# 定义adcDataUnitDef结构体
|
||||
class adcDataUnitDef:
|
||||
def __init__(self):
|
||||
self.ucCmd = 0
|
||||
self.ucAddr = 0
|
||||
self.usData = 0
|
||||
|
||||
class UdpServer(QThread):
|
||||
start_cal = Signal(int, bytearray, str, int) # 信号:接收到消息,包含数据、发送者地址和端口
|
||||
send_collect_data = Signal(dict) #
|
||||
update_acquisition_info = Signal(int, dict)
|
||||
def __init__(self, ip="0.0.0.0", port=50009, parent=None):
|
||||
super(UdpServer, self).__init__(parent)
|
||||
self.kill_udp_port(port)
|
||||
self.ip = ip
|
||||
self.port = port
|
||||
self.server_socket = None
|
||||
self.running = True
|
||||
self.motor1_direction = ""
|
||||
self.motor2_direction = ""
|
||||
self.collect_object1 = {
|
||||
"method" : "scanner1",
|
||||
"channelA_data" :"base64",
|
||||
"channelB_data" :"base64",
|
||||
"intensityA" : 98,
|
||||
"intensityB" : 98
|
||||
}
|
||||
self.collect_object2 = {
|
||||
"method" : "scanner2",
|
||||
"channelA_data" :"base64",
|
||||
"channelB_data" :"base64",
|
||||
"intensityA" : 98,
|
||||
"intensityB" : 98
|
||||
}
|
||||
self.debug_timer = QTimer(self)
|
||||
self.debug_timer.timeout.connect(self.update_debug_timer)
|
||||
if YSMODE:
|
||||
self.debug_timer.start(1000)
|
||||
|
||||
def update_debug_timer(self):
|
||||
import random
|
||||
channelA = [random.randint(1, 1000) for _ in range(3000)]
|
||||
channelB = [random.randint(1, 1000) for _ in range(3000)]
|
||||
self.collect_object1['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
|
||||
self.collect_object1['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
|
||||
self.collect_object2['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
|
||||
self.collect_object2['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
|
||||
self.send_collect_data.emit(self.collect_object1)
|
||||
self.send_collect_data.emit(self.collect_object2)
|
||||
|
||||
def kill_udp_port(self, port):
|
||||
for proc in psutil.process_iter():
|
||||
try:
|
||||
for conn in proc.connections(kind='udp'):
|
||||
if conn.laddr.port == port:
|
||||
print(f" PID={proc.pid}, procname={proc.name()}")
|
||||
proc.kill()
|
||||
except psutil.AccessDenied:
|
||||
continue
|
||||
def packet_crc(self, data):
|
||||
usSum = 0
|
||||
for byte in data:
|
||||
usSum += byte
|
||||
return usSum & 0xFFFF # 确保返回值为16位
|
||||
|
||||
def handle_sample_data(self, data):
|
||||
# 确保数据长度是4的倍数
|
||||
if len(data) % 4 != 0:
|
||||
raise ValueError("Data length must be a multiple of 4")
|
||||
|
||||
# 使用列表推导式来简化代码
|
||||
unpacked_data = [struct.unpack_from('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]
|
||||
|
||||
# 将数据分为两组
|
||||
data_list1 = unpacked_data[::2] # 取偶数索引的元素
|
||||
data_list2 = unpacked_data[1::2] # 取奇数索引的元素
|
||||
|
||||
# 打印数据长度,用于调试
|
||||
print(f"Data contains {len(unpacked_data) // 2} pairs of values")
|
||||
# print(data_list1)
|
||||
# print("=======================================")
|
||||
# print(data_list2)
|
||||
file_content = bytearray()
|
||||
datalen = len(data_list2)
|
||||
for i in range (datalen):
|
||||
file_content.extend(struct.pack('<ff', data_list1[i], data_list2[i]))
|
||||
return data_list1,data_list2,file_content,datalen
|
||||
|
||||
# @Slot(int, str)
|
||||
# def update_direction(self, motor_index, direction):
|
||||
# if motor_index == 1:
|
||||
# self.motor1_direction = direction
|
||||
# elif motor_index == 2:
|
||||
# self.motor2_direction = direction
|
||||
|
||||
def parse_packet(self, base64_data):
|
||||
binary_data = base64.b64decode(base64_data)
|
||||
channel_A = []
|
||||
channel_B = []
|
||||
header_a = struct.unpack('<H', binary_data[0:2])[0]
|
||||
header_b = struct.unpack('<H', binary_data[2:4])[0]
|
||||
queue_remain = struct.unpack('<H', binary_data[4:6])[0]
|
||||
data_len = struct.unpack('<H', binary_data[6:8])[0]
|
||||
|
||||
if header_a != 0xAA55 or header_b != 0x55CC:
|
||||
print("unknown packet header",hex(header_a), hex(header_b))
|
||||
return None
|
||||
data_points = []
|
||||
offset = 8
|
||||
for _ in range(data_len):
|
||||
if offset + 4 > len(binary_data):
|
||||
print("offset:", offset, "data_len:", len(data_points))
|
||||
break
|
||||
channel_A.append(struct.unpack('<H', binary_data[offset:offset+2])[0])
|
||||
channel_B.append(struct.unpack('<H', binary_data[offset+2:offset+4])[0])
|
||||
offset += 12
|
||||
file_content = bytearray()
|
||||
|
||||
for i in range (data_len):
|
||||
file_content.extend(struct.pack('<ff', channel_A[i], channel_B[i]))
|
||||
# 解析数据单元
|
||||
return channel_A, channel_B,file_content, data_len
|
||||
|
||||
def run(self):
|
||||
"""启动 UDP 服务器"""
|
||||
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.server_socket.bind((self.ip, self.port))
|
||||
|
||||
# 增加接收缓冲区大小
|
||||
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536) # 设置为 64KB
|
||||
|
||||
print(f"UDP server is running on {self.ip}:{self.port}")
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
while True: # 循环接收数据
|
||||
try:
|
||||
data, addr = self.server_socket.recvfrom(65536) # 接收最多 64KB 数据
|
||||
msg = json.loads(data.decode())
|
||||
msg_type = msg.get('type')
|
||||
if msg_type == "dev_discovery":
|
||||
self.handle_dev_discovery(msg, addr[0])
|
||||
if msg_type == "data_points":
|
||||
self.handle_data_point(msg, addr[0])
|
||||
except json.JSONDecodeError:
|
||||
print(f"Error decoding JSON data: {data.decode()}")
|
||||
except OSError as e:
|
||||
print(f"Error receiving data: {e}") # 记录错误信息
|
||||
# finally:
|
||||
# self.stop()
|
||||
|
||||
def correct_data(self, filename):
|
||||
# 加载数据
|
||||
|
||||
processor.load_data(filename)
|
||||
filename = filename[0:-4] +"_corrected.csv"
|
||||
# 自动选择圆弧区间
|
||||
if processor.auto_select_arcs():
|
||||
# 拟合数据
|
||||
if processor.fit_data():
|
||||
# 校正数据
|
||||
corrected = processor.correct_data()
|
||||
|
||||
# 保存校正后的数据,去掉头尾各200个点
|
||||
channel_A,channel_B,corrected = processor.save_corrected_data(
|
||||
corrected,
|
||||
filename,
|
||||
trim_edges=True,
|
||||
trim_amount=0
|
||||
)
|
||||
return channel_A,channel_B,corrected
|
||||
return None,None,None
|
||||
|
||||
def handle_dev_discovery(self, msg, ip_address):
|
||||
if msg.get("name") == "daq":
|
||||
status = msg.get("status")
|
||||
if status:
|
||||
# temp = status.get("temp", 0) / 10
|
||||
# speed = status.get("speed", 0)
|
||||
if ip_address == "192.168.100.236":
|
||||
self.update_acquisition_info.emit(1, status)
|
||||
elif ip_address == "192.168.100.237":
|
||||
self.update_acquisition_info.emit(2, status)
|
||||
|
||||
|
||||
def handle_data_point(self, msg, ip_address):
|
||||
try:
|
||||
print("handle data from", ip_address)
|
||||
direction = ""
|
||||
if msg.get("direction") == "up":
|
||||
direction = "UP"
|
||||
elif msg.get("direction") == "down":
|
||||
direction = "DOWN"
|
||||
if msg.get("name") == "daq":
|
||||
channelA, channelB,file_content, row_count =self.parse_packet(msg.get("data","") )
|
||||
index_col = [i for i in range(row_count)]
|
||||
#save data to csv file
|
||||
filename = f'/home/admin/PythonPro/TGX_PYSERVER/datas/data{time.strftime("%Y%m%d%H%M%S")}.csv'
|
||||
with open(filename, 'w', newline='') as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerow(['INDEX', 'CH1', 'CH2'])
|
||||
writer.writerows(zip(index_col, channelA, channelB))
|
||||
if COREECTMODE:
|
||||
channelA,channelB,corrected = self.correct_data(filename)
|
||||
if corrected:
|
||||
file_content = corrected
|
||||
channelA_json = json.dumps(channelA)
|
||||
channelB_json = json.dumps(channelB)
|
||||
channelA_bytes = channelA_json.encode('utf-8')
|
||||
channelB_bytes = channelB_json.encode('utf-8')
|
||||
|
||||
if ip_address == "192.168.100.236":
|
||||
self.collect_object1["method"] = "scanner1"
|
||||
self.start_cal.emit(1, file_content, direction, row_count)
|
||||
print("====emit direction[1]:", direction)
|
||||
self.collect_object1['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
|
||||
self.collect_object1['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
|
||||
self.send_collect_data.emit(self.collect_object1)
|
||||
elif ip_address == "192.168.100.237":
|
||||
self.collect_object2["method"] = "scanner2"
|
||||
self.start_cal.emit(2, file_content, direction, row_count)
|
||||
print("====emit direction[2]:", direction)
|
||||
self.collect_object2['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
|
||||
self.collect_object2['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
|
||||
self.send_collect_data.emit(self.collect_object2)
|
||||
|
||||
except OSError as e:
|
||||
print(f"Error handle_data_point: {e}") # 记录错误信息
|
||||
|
||||
def stop(self):
|
||||
"""停止 UDP 服务器"""
|
||||
self.running = False
|
||||
if self.server_socket:
|
||||
self.server_socket.close()
|
||||
self.wait() # 等待线程结束
|
||||
|
||||
def send_message(self, message, ip, port):
|
||||
"""发送消息到指定的 IP 和端口"""
|
||||
if self.server_socket:
|
||||
self.server_socket.sendto(message.encode(), (ip, port))
|
||||
|
||||
def __del__(self):
|
||||
self.stop() # 确保在对象销毁时停止服务器
|
||||
@@ -0,0 +1,485 @@
|
||||
import socket
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import psutil
|
||||
import struct
|
||||
import csv
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
import logging
|
||||
from config import *
|
||||
from x_ray_data_processor import processor
|
||||
from PySide6.QtCore import QObject, Signal, Slot, QThread, QTimer
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 定义adcDataUnitDef结构体
|
||||
class adcDataUnitDef:
|
||||
def __init__(self):
|
||||
self.ucCmd = 0
|
||||
self.ucAddr = 0
|
||||
self.usData = 0
|
||||
|
||||
# 新增:UDP包头结构定义 (与C端保持一致)
|
||||
class UDPPacketHeader:
|
||||
"""UDP包头结构"""
|
||||
MAGIC = 0xAA55
|
||||
HEADER_SIZE = 16 # 包头大小
|
||||
|
||||
def __init__(self, data: bytes):
|
||||
"""
|
||||
从字节数据解析包头
|
||||
"""
|
||||
if len(data) < self.HEADER_SIZE:
|
||||
raise ValueError("数据长度不足,无法解析包头")
|
||||
|
||||
# 解析包头字段 (小端序)
|
||||
(self.magic, self.total_size, self.big_packet_id,
|
||||
self.packet_id, self.total_packets, self.payload_len) = struct.unpack('<HHIHHH', data[:16])
|
||||
|
||||
# 验证魔数
|
||||
if self.magic != self.MAGIC:
|
||||
raise ValueError(f"无效的魔数: {self.magic:04X}, 期望: {self.MAGIC:04X}")
|
||||
|
||||
# 新增:包重组器,处理单个大包的重组
|
||||
class PacketReassembler:
|
||||
"""包重组器,处理单个大包的重组"""
|
||||
|
||||
def __init__(self, big_packet_id: int, total_size: int, total_packets: int,
|
||||
sender_addr: Tuple[str, int], timeout: float = 1.0):
|
||||
self.big_packet_id = big_packet_id
|
||||
self.total_size = total_size
|
||||
self.total_packets = total_packets
|
||||
self.sender_addr = sender_addr
|
||||
self.timeout = timeout
|
||||
self.start_time = time.time()
|
||||
|
||||
# 存储接收到的包
|
||||
self.packets: Dict[int, bytes] = {}
|
||||
self.received_count = 0
|
||||
self.completed = False
|
||||
self.data = None
|
||||
|
||||
def add_packet(self, packet_id: int, payload: bytes) -> bool:
|
||||
"""
|
||||
添加一个包到重组器
|
||||
返回True如果包是新接收的,False如果包已存在
|
||||
"""
|
||||
if packet_id in self.packets:
|
||||
return False # 包已存在
|
||||
|
||||
self.packets[packet_id] = payload
|
||||
self.received_count += 1
|
||||
|
||||
# 检查是否所有包都已接收
|
||||
if self.received_count == self.total_packets:
|
||||
self._reassemble()
|
||||
return True
|
||||
|
||||
return True
|
||||
|
||||
def _reassemble(self):
|
||||
"""重组完整数据"""
|
||||
try:
|
||||
# 按包序号排序
|
||||
sorted_packets = sorted(self.packets.items())
|
||||
|
||||
# 重组数据
|
||||
reassembled_data = b''
|
||||
for packet_id, payload in sorted_packets:
|
||||
reassembled_data += payload
|
||||
|
||||
# 截取到指定长度
|
||||
self.data = reassembled_data[:self.total_size]
|
||||
self.completed = True
|
||||
|
||||
logger.info(f"大包 {self.big_packet_id} 重组完成,大小: {len(self.data)} 字节")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"重组大包 {self.big_packet_id} 时出错: {e}")
|
||||
|
||||
def is_timeout(self) -> bool:
|
||||
"""检查是否超时"""
|
||||
return time.time() - self.start_time > self.timeout
|
||||
|
||||
def is_completed(self) -> bool:
|
||||
"""检查是否完成重组"""
|
||||
return self.completed
|
||||
|
||||
def get_data(self) -> Optional[bytes]:
|
||||
"""获取重组后的数据"""
|
||||
return self.data if self.completed else None
|
||||
|
||||
class UdpServerEnhanced(QThread):
|
||||
start_cal = Signal(int, bytearray, str, int) # 信号:接收到消息,包含数据、发送者地址和端口
|
||||
send_collect_data = Signal(dict) #
|
||||
update_acquisition_info = Signal(int, dict)
|
||||
|
||||
def __init__(self, ip="0.0.0.0", port=50009, parent=None):
|
||||
super(UdpServerEnhanced, self).__init__(parent)
|
||||
self.kill_udp_port(port)
|
||||
self.ip = ip
|
||||
self.port = port
|
||||
self.server_socket = None
|
||||
self.running = True
|
||||
self.motor1_direction = ""
|
||||
self.motor2_direction = ""
|
||||
|
||||
# 新增:分包重组相关属性
|
||||
self.reassemblers: Dict[Tuple[Tuple[str, int], int], PacketReassembler] = {}
|
||||
self.reassembler_lock = threading.Lock()
|
||||
self.cleanup_thread = None
|
||||
self.timeout = 1.0 # 1秒超时
|
||||
|
||||
self.collect_object1 = {
|
||||
"method" : "scanner1",
|
||||
"channelA_data" :"base64",
|
||||
"channelB_data" :"base64",
|
||||
"intensityA" : 98,
|
||||
"intensityB" : 98
|
||||
}
|
||||
self.collect_object2 = {
|
||||
"method" : "scanner2",
|
||||
"channelA_data" :"base64",
|
||||
"channelB_data" :"base64",
|
||||
"intensityA" : 98,
|
||||
"intensityB" : 98
|
||||
}
|
||||
self.debug_timer = QTimer(self)
|
||||
self.debug_timer.timeout.connect(self.update_debug_timer)
|
||||
if YSMODE:
|
||||
self.debug_timer.start(1000)
|
||||
|
||||
def update_debug_timer(self):
|
||||
import random
|
||||
channelA = [random.randint(1, 1000) for _ in range(3000)]
|
||||
channelB = [random.randint(1, 1000) for _ in range(3000)]
|
||||
self.collect_object1['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
|
||||
self.collect_object1['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
|
||||
self.collect_object2['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode()
|
||||
self.collect_object2['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode()
|
||||
self.send_collect_data.emit(self.collect_object1)
|
||||
self.send_collect_data.emit(self.collect_object2)
|
||||
|
||||
def kill_udp_port(self, port):
|
||||
for proc in psutil.process_iter():
|
||||
try:
|
||||
for conn in proc.connections(kind='udp'):
|
||||
if conn.laddr.port == port:
|
||||
print(f" PID={proc.pid}, procname={proc.name()}")
|
||||
proc.kill()
|
||||
except psutil.AccessDenied:
|
||||
continue
|
||||
|
||||
def packet_crc(self, data):
|
||||
usSum = 0
|
||||
for byte in data:
|
||||
usSum += byte
|
||||
return usSum & 0xFFFF # 确保返回值为16位
|
||||
|
||||
def handle_sample_data(self, data):
|
||||
# 确保数据长度是4的倍数
|
||||
if len(data) % 4 != 0:
|
||||
raise ValueError("Data length must be a multiple of 4")
|
||||
|
||||
# 使用列表推导式来简化代码
|
||||
unpacked_data = [struct.unpack_from('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]
|
||||
|
||||
# 将数据分为两组
|
||||
data_list1 = unpacked_data[::2] # 取偶数索引的元素
|
||||
data_list2 = unpacked_data[1::2] # 取奇数索引的元素
|
||||
|
||||
# 打印数据长度,用于调试
|
||||
print(f"Data contains {len(unpacked_data) // 2} pairs of values")
|
||||
# print(data_list1)
|
||||
# print("=======================================")
|
||||
# print(data_list2)
|
||||
file_content = bytearray()
|
||||
datalen = len(data_list2)
|
||||
for i in range (datalen):
|
||||
file_content.extend(struct.pack('<ff', data_list1[i], data_list2[i]))
|
||||
return data_list1,data_list2,file_content,datalen
|
||||
|
||||
def parse_packet(self, base64_data):
|
||||
binary_data = base64.b64decode(base64_data)
|
||||
channel_A = []
|
||||
channel_B = []
|
||||
header_a = struct.unpack('<H', binary_data[0:2])[0]
|
||||
header_b = struct.unpack('<H', binary_data[2:4])[0]
|
||||
queue_remain = struct.unpack('<H', binary_data[4:6])[0]
|
||||
data_len = struct.unpack('<H', binary_data[6:8])[0]
|
||||
|
||||
if header_a != 0xAA55 or header_b != 0x55CC:
|
||||
print("unknown packet header",hex(header_a), hex(header_b))
|
||||
return None
|
||||
data_points = []
|
||||
offset = 8
|
||||
for _ in range(data_len):
|
||||
if offset + 4 > len(binary_data):
|
||||
print("offset:", offset, "data_len:", len(data_points))
|
||||
break
|
||||
channel_A.append(struct.unpack('<H', binary_data[offset:offset+2])[0])
|
||||
channel_B.append(struct.unpack('<H', binary_data[offset+2:offset+4])[0])
|
||||
offset += 12
|
||||
file_content = bytearray()
|
||||
|
||||
for i in range (data_len):
|
||||
file_content.extend(struct.pack('<ff', channel_A[i], channel_B[i]))
|
||||
# 解析数据单元
|
||||
return channel_A, channel_B,file_content, data_len
|
||||
|
||||
# 新增:检查是否为分包数据
|
||||
def is_fragmented_packet(self, data: bytes) -> bool:
|
||||
"""检查数据包是否以UDP_PACKET_MAGIC开头"""
|
||||
if len(data) < 2:
|
||||
return False
|
||||
magic = struct.unpack('<H', data[:2])[0]
|
||||
return magic == UDPPacketHeader.MAGIC
|
||||
|
||||
# 新增:处理分包数据
|
||||
def handle_fragmented_packet(self, data: bytes, addr: Tuple[str, int]):
|
||||
"""处理分包数据"""
|
||||
try:
|
||||
# 解析包头
|
||||
header = UDPPacketHeader(data)
|
||||
|
||||
# 提取载荷数据
|
||||
payload = data[UDPPacketHeader.HEADER_SIZE:UDPPacketHeader.HEADER_SIZE + header.payload_len]
|
||||
|
||||
# 获取或创建重组器
|
||||
reassembler = self._get_or_create_reassembler(header, addr)
|
||||
|
||||
if reassembler is None:
|
||||
return # 超时或无效的包
|
||||
|
||||
# 添加包到重组器
|
||||
if reassembler.add_packet(header.packet_id, payload):
|
||||
logger.debug(f"接收包 {header.packet_id}/{header.total_packets} "
|
||||
f"来自 {addr}, 大包ID: {header.big_packet_id}")
|
||||
|
||||
# 检查是否完成重组
|
||||
if reassembler.is_completed():
|
||||
self._handle_completed_packet(reassembler)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理来自 {addr} 的分包数据时出错: {e}")
|
||||
|
||||
# 新增:获取或创建包重组器
|
||||
def _get_or_create_reassembler(self, header: UDPPacketHeader, addr: Tuple[str, int]) -> Optional[PacketReassembler]:
|
||||
"""获取或创建包重组器"""
|
||||
key = (addr, header.big_packet_id)
|
||||
|
||||
with self.reassembler_lock:
|
||||
# 检查是否已存在
|
||||
if key in self.reassemblers:
|
||||
reassembler = self.reassemblers[key]
|
||||
|
||||
# 检查是否超时
|
||||
if reassembler.is_timeout():
|
||||
logger.warning(f"大包 {header.big_packet_id} 超时,丢弃")
|
||||
del self.reassemblers[key]
|
||||
return None
|
||||
|
||||
return reassembler
|
||||
|
||||
# 创建新的重组器
|
||||
reassembler = PacketReassembler(
|
||||
header.big_packet_id,
|
||||
header.total_size,
|
||||
header.total_packets,
|
||||
addr,
|
||||
self.timeout
|
||||
)
|
||||
|
||||
self.reassemblers[key] = reassembler
|
||||
logger.info(f"创建新的大包重组器: ID={header.big_packet_id}, "
|
||||
f"大小={header.total_size}, 包数={header.total_packets}, 来源={addr}")
|
||||
|
||||
return reassembler
|
||||
|
||||
# 新增:处理完成重组的数据包
|
||||
def _handle_completed_packet(self, reassembler: PacketReassembler):
|
||||
"""处理完成重组的数据包"""
|
||||
data = reassembler.get_data()
|
||||
if data:
|
||||
logger.info(f"收到完整数据包: 大小={len(data)} 字节, "
|
||||
f"来源={reassembler.sender_addr}, ID={reassembler.big_packet_id}")
|
||||
|
||||
# 调用现有的数据处理方法
|
||||
try:
|
||||
# 尝试解析为JSON格式
|
||||
msg = json.loads(data.decode().strip('\0'))
|
||||
msg_type = msg.get('type')
|
||||
if msg_type == "dev_discovery":
|
||||
self.handle_dev_discovery(msg, reassembler.sender_addr[0])
|
||||
elif msg_type == "data_points":
|
||||
self.handle_data_point(msg, reassembler.sender_addr[0])
|
||||
else:
|
||||
logger.warning(f"未知的消息类型: {msg_type}")
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(f"重组后的数据不是有效的JSON格式")
|
||||
except Exception as e:
|
||||
logger.error(f"处理重组数据时出错: {e}")
|
||||
|
||||
# 从重组器列表中移除
|
||||
with self.reassembler_lock:
|
||||
key = (reassembler.sender_addr, reassembler.big_packet_id)
|
||||
if key in self.reassemblers:
|
||||
del self.reassemblers[key]
|
||||
|
||||
# 新增:清理超时的包
|
||||
def _cleanup_timeout_packets(self):
|
||||
"""清理超时的包(在后台线程中运行)"""
|
||||
while self.running:
|
||||
time.sleep(0.5) # 每0.5秒检查一次
|
||||
|
||||
with self.reassembler_lock:
|
||||
timeout_keys = []
|
||||
for key, reassembler in self.reassemblers.items():
|
||||
if reassembler.is_timeout():
|
||||
timeout_keys.append(key)
|
||||
|
||||
# 移除超时的包
|
||||
for key in timeout_keys:
|
||||
reassembler = self.reassemblers[key]
|
||||
logger.warning(f"清理超时的大包: ID={reassembler.big_packet_id}, "
|
||||
f"来源={reassembler.sender_addr}, "
|
||||
f"已接收={reassembler.received_count}/{reassembler.total_packets}")
|
||||
del self.reassemblers[key]
|
||||
|
||||
def run(self):
|
||||
"""启动 UDP 服务器"""
|
||||
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.server_socket.bind((self.ip, self.port))
|
||||
|
||||
# 增加接收缓冲区大小
|
||||
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536) # 设置为 64KB
|
||||
|
||||
print(f"UDP server is running on {self.ip}:{self.port}")
|
||||
|
||||
# 启动清理线程
|
||||
self.cleanup_thread = threading.Thread(target=self._cleanup_timeout_packets, daemon=True)
|
||||
self.cleanup_thread.start()
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
while True: # 循环接收数据
|
||||
try:
|
||||
data, addr = self.server_socket.recvfrom(65536) # 接收最多 64KB 数据
|
||||
|
||||
# 检查是否为分包数据
|
||||
if self.is_fragmented_packet(data):
|
||||
# 处理分包数据
|
||||
self.handle_fragmented_packet(data, addr)
|
||||
else:
|
||||
# 使用现有的处理方法
|
||||
try:
|
||||
msg = json.loads(data.decode().strip('\0'))
|
||||
msg_type = msg.get('type')
|
||||
if msg_type == "dev_discovery":
|
||||
self.handle_dev_discovery(msg, addr[0])
|
||||
if msg_type == "data_points":
|
||||
self.handle_data_point(msg, addr[0])
|
||||
except json.JSONDecodeError:
|
||||
print(f"Error decoding JSON data: {data.decode()}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error processing data: {e}")
|
||||
|
||||
except OSError as e:
|
||||
print(f"Error receiving data: {e}") # 记录错误信息
|
||||
|
||||
def correct_data(self, filename):
|
||||
# 加载数据
|
||||
processor.load_data(filename)
|
||||
filename = filename[0:-4] +"_corrected.csv"
|
||||
# 自动选择圆弧区间
|
||||
if processor.auto_select_arcs():
|
||||
# 拟合数据
|
||||
if processor.fit_data():
|
||||
# 校正数据
|
||||
corrected = processor.correct_data()
|
||||
|
||||
# 保存校正后的数据,去掉头尾各200个点
|
||||
channel_A,channel_B,corrected = processor.save_corrected_data(
|
||||
corrected,
|
||||
filename,
|
||||
trim_edges=True,
|
||||
trim_amount=0
|
||||
)
|
||||
return channel_A,channel_B,corrected
|
||||
return None,None,None
|
||||
|
||||
def handle_dev_discovery(self, msg, ip_address):
|
||||
if msg.get("name") == "daq":
|
||||
status = msg.get("status")
|
||||
if status:
|
||||
# temp = status.get("temp", 0) / 10
|
||||
# speed = status.get("speed", 0)
|
||||
if ip_address == "192.168.100.236":
|
||||
self.update_acquisition_info.emit(1, status)
|
||||
elif ip_address == "192.168.100.237":
|
||||
self.update_acquisition_info.emit(2, status)
|
||||
|
||||
def handle_data_point(self, msg, ip_address):
|
||||
try:
|
||||
print("handle data from", ip_address)
|
||||
direction = ""
|
||||
if msg.get("direction") == "up":
|
||||
direction = "UP"
|
||||
elif msg.get("direction") == "down":
|
||||
direction = "DOWN"
|
||||
if msg.get("name") == "daq":
|
||||
channelA, channelB,file_content, row_count =self.parse_packet(msg.get("data","") )
|
||||
index_col = [i for i in range(row_count)]
|
||||
#save data to csv file
|
||||
filename = f'/home/admin/PythonPro/TGX_PYSERVER/datas/data{time.strftime("%Y%m%d%H%M%S")}.csv'
|
||||
with open(filename, 'w', newline='') as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerow(['INDEX', 'CH1', 'CH2'])
|
||||
writer.writerows(zip(index_col, channelA, channelB))
|
||||
if COREECTMODE:
|
||||
channelA,channelB,corrected = self.correct_data(filename)
|
||||
if corrected:
|
||||
file_content = corrected
|
||||
channelA_json = json.dumps(channelA)
|
||||
channelB_json = json.dumps(channelB)
|
||||
channelA_bytes = channelA_json.encode('utf-8')
|
||||
channelB_bytes = channelB_json.encode('utf-8')
|
||||
|
||||
if ip_address == "192.168.100.236":
|
||||
self.collect_object1["method"] = "scanner1"
|
||||
self.start_cal.emit(1, file_content, direction, row_count)
|
||||
print("====emit direction[1]:", direction)
|
||||
self.collect_object1['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
|
||||
self.collect_object1['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
|
||||
self.send_collect_data.emit(self.collect_object1)
|
||||
elif ip_address == "192.168.100.237":
|
||||
self.collect_object2["method"] = "scanner2"
|
||||
self.start_cal.emit(2, file_content, direction, row_count)
|
||||
print("====emit direction[2]:", direction)
|
||||
self.collect_object2['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8')
|
||||
self.collect_object2['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8')
|
||||
self.send_collect_data.emit(self.collect_object2)
|
||||
|
||||
except OSError as e:
|
||||
print(f"Error handle_data_point: {e}") # 记录错误信息
|
||||
|
||||
def stop(self):
|
||||
"""停止 UDP 服务器"""
|
||||
self.running = False
|
||||
if self.server_socket:
|
||||
self.server_socket.close()
|
||||
self.wait() # 等待线程结束
|
||||
|
||||
def send_message(self, message, ip, port):
|
||||
"""发送消息到指定的 IP 和端口"""
|
||||
if self.server_socket:
|
||||
self.server_socket.sendto(message.encode(), (ip, port))
|
||||
|
||||
def __del__(self):
|
||||
self.stop() # 确保在对象销毁时停止服务器
|
||||
@@ -0,0 +1,78 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef UDP_H
|
||||
#define UDP_H
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
/* Exported types ------------------------------------------------------------*/
|
||||
|
||||
// 包头结构定义
|
||||
typedef struct {
|
||||
uint16_t magic; // 魔数,用于标识包的有效性 (0xAA55)
|
||||
uint16_t total_size; // 总数据大小 (字节)
|
||||
uint32_t big_packet_id; // 大包ID,32位随机整数,用于区分不同的大包
|
||||
uint16_t packet_id; // 包序号 (0, 1, 2, ...)
|
||||
uint16_t total_packets; // 总包数
|
||||
uint16_t payload_len; // 当前包的有效载荷长度
|
||||
uint8_t reserved[2]; // 保留字段,用于未来扩展
|
||||
} __attribute__((packed)) udp_packet_header_t;
|
||||
|
||||
// 函数声明
|
||||
int udpSendTo(uint8_t *buf, int len, char *addr, uint16_t port);
|
||||
int udpSendBigPacket(uint8_t *buf, int len, char *addr, uint16_t port);
|
||||
|
||||
// 常量定义
|
||||
#define UDP_PACKET_MAGIC 0xAA55
|
||||
#define UDP_MAX_PAYLOAD_SIZE 512
|
||||
#define UDP_HEADER_SIZE sizeof(udp_packet_header_t)
|
||||
#define UDP_MAX_PACKET_SIZE (UDP_HEADER_SIZE + UDP_MAX_PAYLOAD_SIZE)
|
||||
#define UDP_MAX_TOTAL_SIZE 60*1024 // 60KB
|
||||
|
||||
#endif // UDP_H
|
||||
@@ -0,0 +1,250 @@
|
||||
#include "w25qxx.h"
|
||||
|
||||
extern SPI_HandleTypeDef hspi1;
|
||||
|
||||
/**
|
||||
* @brief SPI发送指定长度的数据
|
||||
* @param buf —— 发送数据缓冲区首地址
|
||||
* @param size —— 要发送数据的字节数
|
||||
* @retval 成功返回HAL_OK
|
||||
*/
|
||||
static HAL_StatusTypeDef SPI_Transmit(uint8_t* send_buf, uint16_t size)
|
||||
{
|
||||
return HAL_SPI_Transmit(&hspi1, send_buf, size, 100);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief SPI接收指定长度的数据
|
||||
* @param buf —— 接收数据缓冲区首地址
|
||||
* @param size —— 要接收数据的字节数
|
||||
* @retval 成功返回HAL_OK
|
||||
*/
|
||||
static HAL_StatusTypeDef SPI_Receive(uint8_t* recv_buf, uint16_t size)
|
||||
{
|
||||
return HAL_SPI_Receive(&hspi1, recv_buf, size, 100);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief 读取Flash内部的ID
|
||||
* @param none
|
||||
* @retval 成功返回device_id
|
||||
*/
|
||||
uint16_t W25QXX_ReadID(void)
|
||||
{
|
||||
uint8_t recv_buf[2] = {0}; //recv_buf[0]存放Manufacture ID, recv_buf[1]存放Device ID
|
||||
uint16_t device_id = 0;
|
||||
uint8_t send_data[4] = {ManufactDeviceID_CMD,0x00,0x00,0x00}; //待发送数据,命令+地址
|
||||
|
||||
/* 使能片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
/* 发送并读取数据 */
|
||||
if (HAL_OK == SPI_Transmit(send_data, 4))
|
||||
{
|
||||
if (HAL_OK == SPI_Receive(recv_buf, 2))
|
||||
{
|
||||
device_id = (recv_buf[0] << 8) | recv_buf[1];
|
||||
}
|
||||
}
|
||||
|
||||
/* 取消片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
return device_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 读取W25QXX的状态寄存器,W25Q64一共有2个状态寄存器
|
||||
* @param reg —— 状态寄存器编号(1~2)
|
||||
* @retval 状态寄存器的值
|
||||
*/
|
||||
static uint8_t W25QXX_ReadSR(uint8_t reg)
|
||||
{
|
||||
uint8_t result = 0;
|
||||
uint8_t send_buf[4] = {0x00,0x00,0x00,0x00};
|
||||
switch(reg)
|
||||
{
|
||||
case 1:
|
||||
send_buf[0] = READ_STATU_REGISTER_1;
|
||||
case 2:
|
||||
send_buf[0] = READ_STATU_REGISTER_2;
|
||||
case 0:
|
||||
default:
|
||||
send_buf[0] = READ_STATU_REGISTER_1;
|
||||
}
|
||||
|
||||
/* 使能片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
if (HAL_OK == SPI_Transmit(send_buf, 4))
|
||||
{
|
||||
if (HAL_OK == SPI_Receive(&result, 1))
|
||||
{
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/* 取消片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief 阻塞等待Flash处于空闲状态
|
||||
* @param none
|
||||
* @retval none
|
||||
*/
|
||||
static void W25QXX_Wait_Busy(void)
|
||||
{
|
||||
while((W25QXX_ReadSR(1) & 0x01) == 0x01); // 等待BUSY位清空
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 读取SPI FLASH数据
|
||||
* @param buffer —— 数据存储区
|
||||
* @param start_addr —— 开始读取的地址(最大32bit)
|
||||
* @param nbytes —— 要读取的字节数(最大65535)
|
||||
* @retval 成功返回0,失败返回-1
|
||||
*/
|
||||
int W25QXX_Read(uint8_t* buffer, uint32_t addr, uint16_t nbytes)
|
||||
{
|
||||
uint8_t cmd = READ_DATA_CMD;
|
||||
uint8_t aucBuf[4];
|
||||
int ret = 0;
|
||||
int iCnt = 0;
|
||||
AGAIN:
|
||||
W25QXX_Wait_Busy();
|
||||
|
||||
/* 使能片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
aucBuf[0] = cmd;
|
||||
aucBuf[1] = (uint8_t)(addr >> 16);
|
||||
aucBuf[2] = (uint8_t)(addr >> 8);
|
||||
aucBuf[3] = (uint8_t)(addr >> 0);
|
||||
|
||||
if ((ret = SPI_Transmit(aucBuf, 4)) == HAL_OK)
|
||||
{
|
||||
if ((ret = SPI_Receive(buffer, nbytes)) == HAL_OK)
|
||||
{
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
debug("spi read failed:%d", ret);
|
||||
if (iCnt < 3) {
|
||||
iCnt++;
|
||||
goto AGAIN;
|
||||
}
|
||||
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief W25QXX写使能,将S1寄存器的WEL置位
|
||||
* @param none
|
||||
* @retval
|
||||
*/
|
||||
void W25QXX_Write_Enable(void)
|
||||
{
|
||||
uint8_t cmd= WRITE_ENABLE_CMD;
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
SPI_Transmit(&cmd, 1);
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
W25QXX_Wait_Busy();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief W25QXX写禁止,将WEL清零
|
||||
* @param none
|
||||
* @retval none
|
||||
*/
|
||||
void W25QXX_Write_Disable(void)
|
||||
{
|
||||
uint8_t cmd = WRITE_DISABLE_CMD;
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
SPI_Transmit(&cmd, 1);
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
W25QXX_Wait_Busy();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief W25QXX擦除一个扇区
|
||||
* @param sector_addr —— 扇区地址 根据实际容量设置
|
||||
* @retval none
|
||||
* @note 阻塞操作
|
||||
*/
|
||||
void W25QXX_Erase_Sector(uint32_t addr)
|
||||
{
|
||||
uint8_t cmd = SECTOR_ERASE_CMD;
|
||||
uint8_t aucBuf[4];
|
||||
|
||||
W25QXX_Write_Enable(); //擦除操作即写入0xFF,需要开启写使能
|
||||
W25QXX_Wait_Busy(); //等待写使能完成
|
||||
|
||||
/* 使能片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
aucBuf[0] = cmd;
|
||||
aucBuf[1] = (uint8_t)(addr >> 16);
|
||||
aucBuf[2] = (uint8_t)(addr >> 8);
|
||||
aucBuf[3] = (uint8_t)(addr >> 0);
|
||||
|
||||
SPI_Transmit(aucBuf, 4);
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
W25QXX_Wait_Busy(); //等待扇区擦除完成
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief 页写入操作
|
||||
* @param dat —— 要写入的数据缓冲区首地址
|
||||
* @param WriteAddr —— 要写入的地址
|
||||
* @param byte_to_write —— 要写入的字节数(0-256)
|
||||
* @retval none
|
||||
*/
|
||||
void W25QXX_Page_Program(uint8_t* dat, uint32_t addr, uint16_t nbytes)
|
||||
{
|
||||
uint8_t cmd = PAGE_PROGRAM_CMD;
|
||||
uint8_t aucBuf[4];
|
||||
|
||||
W25QXX_Write_Enable();
|
||||
|
||||
/* 使能片选 */
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_RESET);
|
||||
|
||||
aucBuf[0] = cmd;
|
||||
aucBuf[1] = (uint8_t)(addr >> 16);
|
||||
aucBuf[2] = (uint8_t)(addr >> 8);
|
||||
aucBuf[3] = (uint8_t)(addr >> 0);
|
||||
|
||||
SPI_Transmit(aucBuf, 4);
|
||||
|
||||
SPI_Transmit(dat, nbytes);
|
||||
|
||||
HAL_GPIO_WritePin(FLASH_CS_GPIO_Port, FLASH_CS_Pin, GPIO_PIN_SET);
|
||||
|
||||
W25QXX_Wait_Busy();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef W25QXX_H
|
||||
#define W25QXX_H
|
||||
|
||||
|
||||
#include "main.h"
|
||||
|
||||
#define W25QXX_SECTOR_SIZE (4 * 1024)
|
||||
#define W25QXX_SIZE_MAX (1 * 1024 * 1024)
|
||||
|
||||
#define FLASH_PART_PARAM_START 0x0
|
||||
#define FLASH_PART_PARAM_SIZE (8 * W25QXX_SECTOR_SIZE)
|
||||
#define FLASH_PART_PARAM_END (FLASH_PART_PARAM_START + FLASH_PART_PARAM_SIZE)
|
||||
|
||||
#define FLASH_PART_OTP_START FLASH_PART_PARAM_END
|
||||
#define FLASH_PART_OTP_SIZE (8 * W25QXX_SECTOR_SIZE)
|
||||
#define FLASH_PART_OTP_END (FLASH_PART_OTP_START + FLASH_PART_OTP_SIZE)
|
||||
|
||||
|
||||
#define FLASH_PART_OTA_START FLASH_PART_OTP_END
|
||||
#define FLASH_PART_OTA_SIZE (64 * W25QXX_SECTOR_SIZE)
|
||||
#define FLASH_PART_OTA_END (FLASH_PART_OTA_START + FLASH_PART_OTA_SIZE)
|
||||
|
||||
|
||||
#define ManufactDeviceID_CMD 0x90
|
||||
#define READ_STATU_REGISTER_1 0x05
|
||||
#define READ_STATU_REGISTER_2 0x35
|
||||
#define READ_DATA_CMD 0x03
|
||||
#define WRITE_ENABLE_CMD 0x06
|
||||
#define WRITE_DISABLE_CMD 0x04
|
||||
#define SECTOR_ERASE_CMD 0x20
|
||||
#define CHIP_ERASE_CMD 0xc7
|
||||
#define PAGE_PROGRAM_CMD 0x02
|
||||
|
||||
|
||||
static HAL_StatusTypeDef SPI_Transmit(uint8_t* send_buf, uint16_t size);//向 SPI Flash 发送数据的函数
|
||||
static HAL_StatusTypeDef SPI_Receive(uint8_t* recv_buf, uint16_t size);//从 SPI Flash 接收数据的函数
|
||||
static HAL_StatusTypeDef SPI_TransmitReceive(uint8_t* send_buf, uint8_t* recv_buf, uint16_t size);//发送数据的同时读取数据的函数
|
||||
|
||||
|
||||
uint16_t W25QXX_ReadID(void);//读取Flash内部的ID
|
||||
static uint8_t W25QXX_ReadSR(uint8_t reg);//读取W25QXX的状态寄存器,W25Q64一共有2个状态寄存器
|
||||
int W25QXX_Read(uint8_t* buffer, uint32_t start_addr, uint16_t nbytes);//
|
||||
void W25QXX_Write_Enable(void);
|
||||
void W25QXX_Write_Disable(void);
|
||||
void W25QXX_Erase_Sector(uint32_t sector_addr);
|
||||
void W25QXX_Page_Program(uint8_t* dat, uint32_t WriteAddr, uint16_t nbytes);
|
||||
|
||||
|
||||
#endif // W25QXX_H
|
||||
@@ -0,0 +1,648 @@
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
|
||||
#include "ymodem.h"
|
||||
#include "string.h"
|
||||
#include "main.h"
|
||||
#include "stdlib.h"
|
||||
#include "W25QXX/w25qxx.h"
|
||||
|
||||
/* Private typedef -----------------------------------------------------------*/
|
||||
/* Private define ------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/* Exported constants --------------------------------------------------------*/
|
||||
/* Packet structure defines */
|
||||
#define PACKET_HEADER_SIZE ((uint32_t)3)
|
||||
#define PACKET_DATA_INDEX ((uint32_t)4)
|
||||
#define PACKET_START_INDEX ((uint32_t)1)
|
||||
#define PACKET_NUMBER_INDEX ((uint32_t)2)
|
||||
#define PACKET_CNUMBER_INDEX ((uint32_t)3)
|
||||
#define PACKET_TRAILER_SIZE ((uint32_t)2)
|
||||
#define PACKET_OVERHEAD_SIZE (PACKET_HEADER_SIZE + PACKET_TRAILER_SIZE - 1)
|
||||
#define PACKET_SIZE ((uint32_t)128)
|
||||
#define PACKET_1K_SIZE ((uint32_t)1024)
|
||||
|
||||
/* /-------- Packet in IAP memory ------------------------------------------\
|
||||
* | 0 | 1 | 2 | 3 | 4 | ... | n+4 | n+5 | n+6 |
|
||||
* |------------------------------------------------------------------------|
|
||||
* | unused | start | number | !num | data[0] | ... | data[n] | crc0 | crc1 |
|
||||
* \------------------------------------------------------------------------/
|
||||
* the first byte is left unused for memory alignment reasons */
|
||||
|
||||
#define FILE_NAME_LENGTH ((uint32_t)64)
|
||||
#define FILE_SIZE_LENGTH ((uint32_t)16)
|
||||
|
||||
#define SOH ((uint8_t)0x01) /* start of 128-byte data packet */
|
||||
#define STX ((uint8_t)0x02) /* start of 1024-byte data packet */
|
||||
#define EOT ((uint8_t)0x04) /* end of transmission */
|
||||
#define ACK ((uint8_t)0x06) /* acknowledge */
|
||||
#define NAK ((uint8_t)0x15) /* negative acknowledge */
|
||||
#define CA ((uint32_t)0x18) /* two of these in succession aborts transfer */
|
||||
#define CRC16 ((uint8_t)0x43) /* 'C' == 0x43, request 16-bit CRC */
|
||||
#define NEGATIVE_BYTE ((uint8_t)0xFF)
|
||||
|
||||
#define ABORT1 ((uint8_t)0x41) /* 'A' == 0x41, abort by user */
|
||||
#define ABORT2 ((uint8_t)0x61) /* 'a' == 0x61, abort by user */
|
||||
|
||||
#define NAK_TIMEOUT ((uint32_t)0x100000)
|
||||
#define DOWNLOAD_TIMEOUT ((uint32_t)1000) /* One second retry delay */
|
||||
#define MAX_ERRORS ((uint32_t)5)
|
||||
|
||||
|
||||
|
||||
|
||||
/* Private macro -------------------------------------------------------------*/
|
||||
#define APPLICATION_ADDRESS 0x30000000
|
||||
#define USER_FLASH_SIZE 0x40000 ///< 256KB
|
||||
/* Private variables ---------------------------------------------------------*/
|
||||
/* @note ATTENTION - please keep this variable 32bit alligned */
|
||||
static uint8_t aPacketData[PACKET_1K_SIZE + PACKET_DATA_INDEX + PACKET_TRAILER_SIZE];
|
||||
|
||||
#define UDP_RECV_BUF_LEN 10240
|
||||
static uint8_t aucRecvBuf[10240];
|
||||
static int udpRxLen = 0;
|
||||
static int udpRxPos = 0;
|
||||
|
||||
|
||||
/* Private function prototypes -----------------------------------------------*/
|
||||
static HAL_StatusTypeDef ReceivePacket(uint8_t *p_data, uint32_t *p_length, uint32_t timeout);
|
||||
static uint16_t UpdateCRC16(uint16_t crc_in, uint8_t byte);
|
||||
static uint16_t Cal_CRC16(const uint8_t* p_data, uint32_t size);
|
||||
|
||||
/* Private functions ---------------------------------------------------------*/
|
||||
|
||||
extern int udpRecv(uint8_t *buf, int len);
|
||||
extern int udpSend(uint8_t *buf, int len);
|
||||
|
||||
HAL_StatusTypeDef ymodemTx(uint8_t ucByte)
|
||||
{
|
||||
static uint8_t ucBuf = 0;
|
||||
ucBuf = ucByte;
|
||||
udpSend(&ucBuf, 1);
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
HAL_StatusTypeDef ymodemTx2(uint8_t ucByte1, uint8_t ucByte2)
|
||||
{
|
||||
static uint8_t aucBuf[2];
|
||||
aucBuf[0] = ucByte1;
|
||||
aucBuf[1] = ucByte2;
|
||||
|
||||
udpSend(aucBuf, 2);
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
HAL_StatusTypeDef ymodemRx(uint8_t *pucBytes, uint32_t ulLen, int iTimeout)
|
||||
{
|
||||
int iRet;
|
||||
if (iTimeout < 100) {
|
||||
iTimeout = 100;
|
||||
}
|
||||
debug("ymodem to recv %d bytes", ulLen);
|
||||
|
||||
if (udpRxLen - udpRxPos >= ulLen) {
|
||||
memcpy(pucBytes, &aucRecvBuf[udpRxPos], ulLen);
|
||||
udpRxPos += ulLen;
|
||||
|
||||
debug("modem rx %d byte", ulLen);
|
||||
// dump(pucBytes, ulLen);
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
while (1) {
|
||||
if (iTimeout <= 0) {
|
||||
break;
|
||||
}
|
||||
iRet = udpRecv(aucRecvBuf, UDP_RECV_BUF_LEN);
|
||||
iTimeout -= 100;
|
||||
if (iRet > 0) {
|
||||
udpRxPos = 0;
|
||||
udpRxLen = iRet;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (udpRxLen - udpRxPos >= ulLen) {
|
||||
memcpy(pucBytes, &aucRecvBuf[udpRxPos], ulLen);
|
||||
udpRxPos += ulLen;
|
||||
debug("modem rx %d byte", ulLen);
|
||||
// dump(pucBytes, ulLen);
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
return HAL_TIMEOUT;
|
||||
}
|
||||
|
||||
int FLASH_If_dump(uint32_t addr, uint32_t ulLen)
|
||||
{
|
||||
uint8_t aucbuf[1024];
|
||||
int start_sector = 16;
|
||||
|
||||
addr = addr + start_sector * 4096;
|
||||
|
||||
while (ulLen >= 16) {
|
||||
W25QXX_Read(aucbuf, addr, 16);
|
||||
dump(aucbuf, 16);
|
||||
addr += 16;
|
||||
ulLen -= 16;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Read(aucbuf, addr, ulLen);
|
||||
dump(aucbuf, ulLen);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ram_dump(uint8_t *ram, uint32_t ulLen)
|
||||
{
|
||||
while (ulLen >= 16) {
|
||||
dump(ram, 16);
|
||||
ram += 16;
|
||||
ulLen -= 16;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
dump(ram, ulLen);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FLASH_CehckEmpty(uint32_t addr, uint32_t ulLen)
|
||||
{
|
||||
uint8_t aucbuf[1024];
|
||||
|
||||
while (ulLen >= 256) {
|
||||
W25QXX_Read(aucbuf, addr, 256);
|
||||
for (int i= 0; i < 256; i++) {
|
||||
if (aucbuf[i] != 0xFF) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
addr += 256;
|
||||
ulLen -= 256;
|
||||
}
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Read(aucbuf, addr, ulLen);
|
||||
for (int i= 0; i < ulLen; i++) {
|
||||
if (aucbuf[i] != 0xFF) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int FLASH_If_Erase(uint32_t size)
|
||||
{
|
||||
int ret;
|
||||
int start_sector = 16;
|
||||
int num = size / 4096;
|
||||
if (size % 4096) {
|
||||
num++;
|
||||
}
|
||||
for (int i = 0; i < num; ++i) {
|
||||
W25QXX_Erase_Sector((start_sector + i) * 4096);
|
||||
|
||||
debug("erase sector %d", start_sector + i);
|
||||
|
||||
ret = FLASH_CehckEmpty((start_sector + i) * 4096, 4096);
|
||||
if (ret >= 0) {
|
||||
debug("erase failed at sector %d", i);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FLASH_If_verify(uint32_t addr, uint8_t *pucSrc, uint32_t ulLen)
|
||||
{
|
||||
static uint8_t aucbuf[1024];
|
||||
int start_sector = 16;
|
||||
|
||||
addr = addr + start_sector * 4096;
|
||||
|
||||
while (ulLen >= 256) {
|
||||
int iCnt = 0;
|
||||
AGAIN:
|
||||
if (W25QXX_Read(aucbuf, addr, 256) != 0) {
|
||||
debug("read flash failed at %d", addr);
|
||||
}
|
||||
if (memcmp(aucbuf, pucSrc, 256) != 0) {
|
||||
debug("verify fialed at %d", addr);
|
||||
debug("flash:");
|
||||
ram_dump(aucbuf, 256);
|
||||
debug("ram:");
|
||||
ram_dump(pucSrc, 256);
|
||||
if (iCnt < 3) {
|
||||
iCnt++;
|
||||
goto AGAIN;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
if (iCnt != 0) {
|
||||
debug("OK");
|
||||
ram_dump(pucSrc, 256);
|
||||
}
|
||||
pucSrc += 256;
|
||||
addr += 256;
|
||||
ulLen -= 256;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Read(aucbuf, addr, ulLen);
|
||||
if (memcmp(aucbuf, pucSrc, ulLen) != 0) {
|
||||
debug("verify fialed at %d", addr);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FLASH_If_Write(uint32_t addr, uint8_t *pucSrc, uint32_t ulLen)
|
||||
{
|
||||
int start_sector = 16;
|
||||
|
||||
addr = addr + start_sector * 4096;
|
||||
|
||||
while (ulLen >= 256) {
|
||||
W25QXX_Page_Program(pucSrc, addr, 256);
|
||||
pucSrc += 256;
|
||||
addr += 256;
|
||||
ulLen -= 256;
|
||||
}
|
||||
|
||||
if (ulLen > 0) {
|
||||
W25QXX_Page_Program(pucSrc, addr, ulLen);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Receive a packet from sender
|
||||
* @param data
|
||||
* @param length
|
||||
* 0: end of transmission
|
||||
* 2: abort by sender
|
||||
* >0: packet length
|
||||
* @param timeout
|
||||
* @retval HAL_OK: normally return
|
||||
* HAL_BUSY: abort by user
|
||||
*/
|
||||
static HAL_StatusTypeDef ReceivePacket(uint8_t *p_data, uint32_t *p_length, uint32_t timeout)
|
||||
{
|
||||
uint32_t crc;
|
||||
uint32_t packet_size = 0;
|
||||
HAL_StatusTypeDef status;
|
||||
uint8_t char1;
|
||||
|
||||
*p_length = 0;
|
||||
status = ymodemRx(&char1, 1, timeout);
|
||||
|
||||
if (status == HAL_OK)
|
||||
{
|
||||
switch (char1)
|
||||
{
|
||||
case SOH:
|
||||
packet_size = PACKET_SIZE;
|
||||
debug("SOH");
|
||||
break;
|
||||
case STX:
|
||||
packet_size = PACKET_1K_SIZE;
|
||||
break;
|
||||
case EOT:
|
||||
break;
|
||||
case CA:
|
||||
if ((ymodemRx(&char1, 1, timeout) == HAL_OK) && (char1 == CA))
|
||||
{
|
||||
packet_size = 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
status = HAL_ERROR;
|
||||
}
|
||||
break;
|
||||
case ABORT1:
|
||||
case ABORT2:
|
||||
status = HAL_BUSY;
|
||||
break;
|
||||
default:
|
||||
status = HAL_ERROR;
|
||||
break;
|
||||
}
|
||||
*p_data = char1;
|
||||
|
||||
if (packet_size >= PACKET_SIZE )
|
||||
{
|
||||
status = ymodemRx(&p_data[PACKET_NUMBER_INDEX], packet_size + PACKET_OVERHEAD_SIZE, timeout);
|
||||
|
||||
/* Simple packet sanity check */
|
||||
if (status == HAL_OK )
|
||||
{
|
||||
if (p_data[PACKET_NUMBER_INDEX] != ((p_data[PACKET_CNUMBER_INDEX]) ^ NEGATIVE_BYTE))
|
||||
{
|
||||
packet_size = 0;
|
||||
status = HAL_ERROR;
|
||||
debug("PACKET_NUMBER != PACKET_CNUMBER");
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Check packet CRC */
|
||||
crc = p_data[ packet_size + PACKET_DATA_INDEX ] << 8;
|
||||
crc += p_data[ packet_size + PACKET_DATA_INDEX + 1 ];
|
||||
if (Cal_CRC16(&p_data[PACKET_DATA_INDEX], packet_size) != crc )
|
||||
{
|
||||
packet_size = 0;
|
||||
status = HAL_ERROR;
|
||||
debug("crc error");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
packet_size = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
*p_length = packet_size;
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update CRC16 for input byte
|
||||
* @param crc_in input value
|
||||
* @param input byte
|
||||
* @retval None
|
||||
*/
|
||||
uint16_t UpdateCRC16(uint16_t crc_in, uint8_t byte)
|
||||
{
|
||||
uint32_t crc = crc_in;
|
||||
uint32_t in = byte | 0x100;
|
||||
|
||||
do
|
||||
{
|
||||
crc <<= 1;
|
||||
in <<= 1;
|
||||
if(in & 0x100)
|
||||
++crc;
|
||||
if(crc & 0x10000)
|
||||
crc ^= 0x1021;
|
||||
}
|
||||
|
||||
while(!(in & 0x10000));
|
||||
|
||||
return crc & 0xffffu;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Cal CRC16 for YModem Packet
|
||||
* @param data
|
||||
* @param length
|
||||
* @retval None
|
||||
*/
|
||||
uint16_t Cal_CRC16(const uint8_t* p_data, uint32_t size)
|
||||
{
|
||||
uint32_t crc = 0;
|
||||
const uint8_t* dataEnd = p_data+size;
|
||||
|
||||
while(p_data < dataEnd)
|
||||
crc = UpdateCRC16(crc, *p_data++);
|
||||
|
||||
crc = UpdateCRC16(crc, 0);
|
||||
crc = UpdateCRC16(crc, 0);
|
||||
|
||||
return crc&0xffffu;
|
||||
}
|
||||
|
||||
/* Public functions ---------------------------------------------------------*/
|
||||
/**
|
||||
* @brief Receive a file using the ymodem protocol with CRC16.
|
||||
* @param p_size The size of the file.
|
||||
* @retval COM_StatusTypeDef result of reception/programming
|
||||
*/
|
||||
COM_StatusTypeDef Ymodem_Receive ( uint32_t *p_size, char *aFileName )
|
||||
{
|
||||
uint32_t i, packet_length, session_done = 0, file_done, errors = 0, session_begin = 0;
|
||||
uint32_t flashdestination, ramsource, filesize;
|
||||
uint8_t *file_ptr;
|
||||
uint8_t file_size[FILE_SIZE_LENGTH], tmp, packets_received;
|
||||
COM_StatusTypeDef result = COM_OK;
|
||||
|
||||
/* Initialize flashdestination variable */
|
||||
flashdestination = 0;
|
||||
|
||||
while ((session_done == 0) && (result == COM_OK))
|
||||
{
|
||||
packets_received = 0;
|
||||
file_done = 0;
|
||||
while ((file_done == 0) && (result == COM_OK))
|
||||
{
|
||||
switch (ReceivePacket(aPacketData, &packet_length, DOWNLOAD_TIMEOUT))
|
||||
{
|
||||
case HAL_OK:
|
||||
errors = 0;
|
||||
switch (packet_length)
|
||||
{
|
||||
case 2:
|
||||
/* Abort by sender */
|
||||
ymodemTx(ACK);
|
||||
result = COM_ABORT;
|
||||
break;
|
||||
case 0:
|
||||
/* End of transmission */
|
||||
ymodemTx(ACK);
|
||||
file_done = 1;
|
||||
break;
|
||||
default:
|
||||
/* Normal packet */
|
||||
if (aPacketData[PACKET_NUMBER_INDEX] != packets_received)
|
||||
{
|
||||
ymodemTx(NAK);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (packets_received == 0)
|
||||
{
|
||||
/* File name packet */
|
||||
if (aPacketData[PACKET_DATA_INDEX] != 0)
|
||||
{
|
||||
/* File name extraction */
|
||||
i = 0;
|
||||
file_ptr = aPacketData + PACKET_DATA_INDEX;
|
||||
while ( (*file_ptr != 0) && (i < FILE_NAME_LENGTH))
|
||||
{
|
||||
aFileName[i++] = *file_ptr++;
|
||||
}
|
||||
|
||||
/* File size extraction */
|
||||
aFileName[i++] = '\0';
|
||||
i = 0;
|
||||
file_ptr ++;
|
||||
while ( (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH))
|
||||
{
|
||||
file_size[i++] = *file_ptr++;
|
||||
}
|
||||
file_size[i++] = '\0';
|
||||
filesize = atoi((char *)file_size);
|
||||
|
||||
/* Test the size of the image to be sent */
|
||||
/* Image size is greater than Flash size */
|
||||
|
||||
printf("[AAA]*p_size : %u , USER_FLASH_SIZE : %u \r\n",*p_size, (USER_FLASH_SIZE + 1));
|
||||
|
||||
if (*p_size > (USER_FLASH_SIZE + 1))
|
||||
{
|
||||
/* End session */
|
||||
ymodemTx2(CA, CA);
|
||||
result = COM_LIMIT;
|
||||
|
||||
printf("[AAA] 222 \r\n");
|
||||
}
|
||||
/* erase user application area */
|
||||
|
||||
printf("filesize : %u \r\n",filesize);
|
||||
|
||||
FLASH_If_Erase(filesize);
|
||||
*p_size = filesize;
|
||||
|
||||
ymodemTx2(ACK, CRC16);
|
||||
|
||||
printf("[AAA] 1111 \r\n");
|
||||
|
||||
|
||||
}
|
||||
/* File header packet is empty, end session */
|
||||
else
|
||||
{
|
||||
ymodemTx(ACK);
|
||||
file_done = 1;
|
||||
session_done = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else /* Data packet */
|
||||
{
|
||||
// ramsource = (uint32_t) & aPacketData[PACKET_DATA_INDEX];
|
||||
static uint8_t aucBuf[sizeof(aPacketData)];
|
||||
memcpy(aucBuf, aPacketData, sizeof(aPacketData));
|
||||
/* Write received data in Flash */
|
||||
if (FLASH_If_Write(flashdestination, &aucBuf[PACKET_DATA_INDEX], packet_length) == 0)
|
||||
{
|
||||
if (FLASH_If_verify(flashdestination, &aucBuf[PACKET_DATA_INDEX], packet_length) != 0) {
|
||||
debug("verify failed at %d", flashdestination);
|
||||
}
|
||||
flashdestination += packet_length;
|
||||
ymodemTx(ACK);
|
||||
}
|
||||
else /* An error occurred while writing to Flash memory */
|
||||
{
|
||||
/* End session */
|
||||
ymodemTx2(CA, CA);
|
||||
result = COM_DATA;
|
||||
}
|
||||
}
|
||||
packets_received ++;
|
||||
session_begin = 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case HAL_BUSY: /* Abort actually */
|
||||
ymodemTx2(CA, CA);
|
||||
result = COM_ABORT;
|
||||
break;
|
||||
default:
|
||||
if (session_begin > 0)
|
||||
{
|
||||
errors ++;
|
||||
}
|
||||
if (errors > MAX_ERRORS)
|
||||
{
|
||||
/* Abort communication */
|
||||
ymodemTx2(CA, CA);
|
||||
}
|
||||
else
|
||||
{
|
||||
ymodemTx(CRC16); /* Ask for a packet */
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/* Private typedef -----------------------------------------------------------*/
|
||||
/* Private define ------------------------------------------------------------*/
|
||||
/* Private macro -------------------------------------------------------------*/
|
||||
/* Private variables ---------------------------------------------------------*/
|
||||
typedef void (*pFunction)(void);
|
||||
|
||||
static pFunction JumpToApplication;
|
||||
static uint32_t JumpAddress;
|
||||
|
||||
void copyFirmware(void)
|
||||
{
|
||||
uint32_t ulDstAddr = 0x30000000;
|
||||
uint32_t ulSrcAddr = 16 * 4096;
|
||||
uint32_t ullen = 256 * 1024;
|
||||
while (ullen >= 1024) {
|
||||
W25QXX_Read((uint8_t *)ulDstAddr, ulSrcAddr, 1024);
|
||||
ulDstAddr += 1024;
|
||||
ulSrcAddr += 1024;
|
||||
ullen -= 1024;
|
||||
}
|
||||
|
||||
while (ullen > 0) {
|
||||
W25QXX_Read((uint8_t *)ulDstAddr, ulSrcAddr, ullen);
|
||||
}
|
||||
}
|
||||
|
||||
void appJump(void)
|
||||
{
|
||||
__disable_irq();
|
||||
|
||||
W25QXX_Read((uint8_t *)(0x20000000 + 127 * 1024), 0, 1024);
|
||||
|
||||
/* execute the new program */
|
||||
JumpAddress = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
|
||||
/* Jump to user application */
|
||||
JumpToApplication = (pFunction) JumpAddress;
|
||||
/* Initialize user application's Stack Pointer */
|
||||
__set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
|
||||
JumpToApplication();
|
||||
}
|
||||
|
||||
int checkApp(void)
|
||||
{
|
||||
uint32_t addr;
|
||||
|
||||
copyFirmware();
|
||||
|
||||
dump(APPLICATION_ADDRESS, 16);
|
||||
|
||||
addr = *(__IO uint32_t*) (APPLICATION_ADDRESS);
|
||||
if ((addr > 0x24000000) && (addr < (0x24000000 + 0x80000))) {
|
||||
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
|
||||
addr = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
|
||||
if ((addr > 0x20000000) && (addr < (0x20000000 + 0x20000))) {
|
||||
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef YMODEM_H
|
||||
#define YMODEM_H
|
||||
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "main.h"
|
||||
/* Exported types ------------------------------------------------------------*/
|
||||
|
||||
|
||||
/**
|
||||
* @brief Comm status structures definition
|
||||
*/
|
||||
typedef enum
|
||||
{
|
||||
COM_OK = 0x00,
|
||||
COM_ERROR = 0x01,
|
||||
COM_ABORT = 0x02,
|
||||
COM_TIMEOUT = 0x03,
|
||||
COM_DATA = 0x04,
|
||||
COM_LIMIT = 0x05
|
||||
} COM_StatusTypeDef;
|
||||
|
||||
|
||||
/* Exported functions ------------------------------------------------------- */
|
||||
COM_StatusTypeDef Ymodem_Receive ( uint32_t *p_size, char *aFileName );
|
||||
|
||||
int checkApp(void);
|
||||
void appJump(void);
|
||||
|
||||
#endif // YMODEM_H
|
||||
Reference in New Issue
Block a user