1 解析mqtt 传过来的json
用cjson 解析。
2 类似mvc的结构,调用具体的动作函数
- 定义设备处理结构体:使用结构体数组映射设备名称与处理函数,实现可扩展的指令分发
- 分离设备逻辑:为每个设备(如 LED、Motor)编写独立的处理函数,保持模块解耦
- 统一 JSON 解析流程:在解析函数中通过遍历结构体数组匹配指令,调用对应处理函数
- 状态校验机制:对输入的状态值进行合法性校验,避免无效操作

完整修改后代码
#include "system.h"
#include "SysTick.h"
#include "led.h" // 添加LED函数声明头文件
#include "usart.h"
#include "wifi_config.h"
#include "wifi_function.h"
#include <string.h>
#include "cJSON.h"
// 声明外部变量
extern struct STRUCT_USARTx_Fram strEsp8266_Fram_Record;
// 函数声明
void ProcessWiFiData(uint8_t *data, uint16_t length);
void HandleMQTTMessage(const char *topic, const char *message, const char *message_le);
// 全局变量
char topic_id[20] = "topic911";
char sub_topic_id[20] = "topic108";
uint8_t wifi_rx_buffer[RX_BUF_MAX_LEN]; // 用于暂存接收数据的缓冲区
// ========== 设备处理结构体定义 ==========
typedef enum {
DEVICE_LED,
DEVICE_MOTOR,
DEVICE_UNKNOWN
} DeviceType;
typedef struct {
const char *device_name; // 设备名称(JSON键名)
DeviceType device_type; // 设备类型枚举
void (*handler)(const char *state); // 处理函数指针
} DeviceHandler;
// ========== 设备处理函数实现 ==========
// LED处理函数(假设LED_Init()已在led.h中声明)

最低0.47元/天 解锁文章
939

被折叠的 条评论
为什么被折叠?



