VSSCANF 错误,从 c 中的响应缓冲区中提取变量 [按行和按关键字]



如果我从响应缓冲区提取一个变量,两种方法(按行号或关键字(都可以正常工作。但如果我试图提取多种类型的多个变量,如字符串、int和float,那么在成功提取字符串后,它就不起作用了。(注释unnessury代码(连杆在这里

#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
uint8_t res_buf[2048];
uint8_t line_counts;
} MODULE_Typedef;  //module buffer
// validate and get response pointer by line number
uint8_t *MODULE_ATRespGetByLineNumber(MODULE_Typedef *module, uint8_t resp_line) {
uint8_t *resp_buf = module->res_buf;
uint8_t *resp_line_buf = 0;
uint8_t line_num = 1;
if (resp_line > module->line_counts || resp_line <= 0) {
return 0;
}
for (line_num = 1; line_num <= module->line_counts; line_num++) {
if (resp_line == line_num) {
resp_line_buf = resp_buf;
return resp_line_buf;
}
resp_buf += strlen(resp_buf) + 1;
}
return 0;
}
//parse response by line number
uint16_t MODULE_ATRespParseLine(MODULE_Typedef *module, uint8_t resp_line, const char *resp_expr, ...) {
va_list args;
int resp_args_num = 0;
const char *resp_line_buf = 0;
if ((resp_line_buf = MODULE_ATRespGetByLineNumber(module, resp_line)) == 0) {
return -1;
}
// printf("rnOK = %srn",resp_line_buf);
va_start(args, resp_expr);
resp_args_num = vsscanf(resp_line_buf, resp_expr, args);
va_end(args);
return resp_args_num;
}
//validate and get response pointer by keyword
uint8_t *MODULE_ATRespGetByKeyword(MODULE_Typedef *module, uint8_t *keyword) {
char *resp_buf = module->res_buf;
char *resp_line_buf = 0;
uint16_t line_num = 1;
for (line_num = 1; line_num <= module->line_counts; line_num++) {
if (strstr(resp_buf, keyword)) {
resp_line_buf = resp_buf;

return resp_line_buf;
}
resp_buf += strlen(resp_buf) + 1;
}
return 0;
}
//parse response using keyword
uint16_t MODULE_ATRespParse(MODULE_Typedef *module, uint8_t *keyword, uint8_t *resp_expr, ...) 
{
uint16_t resp_args_num = 0;
char *resp_line_buf = MODULE_ATRespGetByKeyword(module, keyword);
va_list args;
if (resp_line_buf) {
va_start(args, resp_expr);
resp_args_num = vsscanf(resp_line_buf, resp_expr, args);
va_end(args);
return resp_args_num;
}
}
int main() {
char opr[20] = {"ERROR"}; 
uint8_t gpsv1 = 0,gpsv2 = 0,gpsv3 = 0,gpsv4 = 0,gpsv5 = 0,gpsv6 = 0,gpsv7 = 0,gpsv8 = 0,gpsv9 = 0,gpsv10 = 0,gpsv11=0;
uint8_t mode = -1,format = -1,act = -1;    
MODULE_Typedef resp1 = {
.res_buf = {"+CREG: 0,2,AIRTEL,45"},
.line_counts = 1,
};
printf("rnrnrnbuffer res1 = %srn",resp1.res_buf);
MODULE_ATRespParse(&resp1,"+CREG:","+CREG: %d, %d, %[^,]s,%d",&mode,&format,opr,&act);
printf("rnmode = %dnformat = %dnoperator = %snnwk = %dn",mode,format,opr,act);
}

我的输入缓冲区:

缓冲区res1=+CREG:0,2,AIRTEL,45

从中提取变量:

模式=0格式=2operator=AIRTELnwk=255

您必须根据格式说明符传递正确的变量指针。如果您使用的是%d,则意味着您的参数类型应为int *

  1. 将变量类型uint8_t更改为int(对于%d(
  2. %d更改为%2SCNu8(用于uint8_t(

这些解决方案应该能解决您的问题。导螺杆

相关内容

最新更新