-
Notifications
You must be signed in to change notification settings - Fork 273
Description
无意间发现只要MQTT服务器掉线或者关机,RT-THREAD5.1系统就会死机,无论是WIFI链接或者网口链接,终端提示
Warning: There is no enough buffer for saving data, please increase the RT_SERIAL_RB_BUFSZ option.
按提示从64修改为1024还是不行。
rtconfig.h
RT_SERIAL_RB_BUFSZ 1024
#include <rtdevice.h>
#include <board.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mqttclient.h"
#include "time.h"
#include <rtthread.h>
#include <rtdbg.h>
#include <arpa/inet.h>
#include <netdev.h>
#include <drivers/rtc.h>
#define LED1_PIN GET_PIN(G, 14)
#define LED2_PIN GET_PIN(I, 0)
#define LED3_PIN GET_PIN(I, 1)
// 定义MQTT客户端标识变量
#define CLIENT_IDENTIFIER "a2"
//AHT20的SDA引脚 - STM32的PH8
//AHT20的SCL引脚 - STM32的PH7
/* 默认网卡对象函数 */
struct netdev *netdev_get_by_name(const char *name);
// 声明DS3231温度获取函数
extern float ds3231_get_temperature(void);
// 简化版CPU使用率获取函数
static uint8_t get_cpu_usage(void)
{
static rt_tick_t last_idle_tick = 0;
static rt_tick_t last_total_tick = 0;
rt_tick_t idle_tick = rt_thread_idle_sethook(NULL);
rt_tick_t total_tick = rt_tick_get();
rt_tick_t idle_diff = idle_tick - last_idle_tick;
rt_tick_t total_diff = total_tick - last_total_tick;
last_idle_tick = idle_tick;
last_total_tick = total_tick;
if (total_diff == 0) {
return 0;
}
uint8_t usage = 100 - (idle_diff * 100) / total_diff;
return usage > 100 ? 100 : usage; // 确保不超过100%
}
//发布函数
static int mqtt_publish_handle1(mqtt_client_t client)
{
mqtt_message_t msg;
memset(&msg, 0, sizeof(msg));
msg.qos = 0;
uint8_t cpu_usage = get_cpu_usage();
float temperature = ds3231_get_temperature();
char payload[50];
snprintf(payload, sizeof(payload), "%s_CPU_°C >>> %d,%.1f", CLIENT_IDENTIFIER, cpu_usage, temperature);
msg.payload = payload;
return mqtt_publish(client, "cpu", &msg);
}
int main(void)
{
/ 设置默认网卡对象 */
netdev_set_default(netdev_get_by_name("esp0"));
//无线esp0,有线e0.
mqtt_client_t client = NULL;
mqtt_log_init();
client = mqtt_lease();
mqtt_set_host(client, "192.168.10.248");
mqtt_set_port(client, "1883");
mqtt_set_user_name(client, CLIENT_IDENTIFIER);
mqtt_set_password(client, "12345678Qq");
mqtt_set_client_id(client, CLIENT_IDENTIFIER);
mqtt_set_clean_session(client, 1);
mqtt_connect(client);
rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);
rt_pin_mode(LED2_PIN, PIN_MODE_OUTPUT);
rt_pin_mode(LED3_PIN, PIN_MODE_OUTPUT);
while(1) {
/ LED 每 2 秒闪烁一次 /
rt_pin_write(LED1_PIN, PIN_HIGH);
rt_pin_write(LED2_PIN, PIN_HIGH);
rt_pin_write(LED3_PIN, PIN_HIGH);
rt_thread_mdelay(2000);
rt_pin_write(LED1_PIN, PIN_LOW);
rt_pin_write(LED2_PIN, PIN_LOW);
rt_pin_write(LED3_PIN, PIN_LOW);
rt_thread_mdelay(2000);
/ 每 60 秒发送一次 MQTT 数据 */
static uint32_t last_publish_time = 0;
uint32_t current_time = rt_tick_get();
if (current_time - last_publish_time >= 60 * 1000)
{
mqtt_publish_handle1(client);
last_publish_time = current_time;
}
}
return RT_EOK;
}