77 lines
2.5 KiB
C++
77 lines
2.5 KiB
C++
#pragma once
|
|
|
|
#include "spdlog/spdlog.h"
|
|
#include <map>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <functional>
|
|
#include <chrono> // For std::chrono
|
|
#include <mutex> // For std::mutex
|
|
#include <nlohmann/json.hpp>
|
|
|
|
// 报警级别
|
|
enum class AlarmLevel {
|
|
INFO,
|
|
WARNING,
|
|
CRITICAL
|
|
};
|
|
|
|
// 报警规则结构体
|
|
struct AlarmRule {
|
|
std::string rule_id; // 规则唯一ID
|
|
std::string device_id; // 针对的设备ID
|
|
std::string data_point_name; // 监控的数据点名称
|
|
std::string compare_type; // 比较类型: "GT" (>), "LT" (<), "EQ" (=), "GE" (>=), "LE" (<=)
|
|
double threshold; // 报警阈值
|
|
AlarmLevel level; // 报警级别
|
|
std::string message_template; // 报警消息模板,例如 "设备 {device_id} 的 {data_point_name} ({value}) 超过阈值 {threshold}!"
|
|
std::chrono::seconds debounce_interval; // 报警去抖动/抑制间隔
|
|
};
|
|
|
|
// 报警事件结构体
|
|
struct AlarmEvent {
|
|
std::string event_id;
|
|
std::string rule_id;
|
|
std::string device_id;
|
|
std::string data_point_name;
|
|
double current_value;
|
|
double threshold;
|
|
AlarmLevel level;
|
|
std::string timestamp;
|
|
std::string message;
|
|
};
|
|
|
|
class AlarmManager {
|
|
public:
|
|
using AlarmCallback = std::function<void(const AlarmEvent&)>;
|
|
|
|
AlarmManager();
|
|
|
|
// 加载报警规则 (例如从配置文件)
|
|
bool load_rules(const std::string& config_path);
|
|
|
|
// 检查数据是否触发报警
|
|
void check_data_for_alarms(const std::string& device_id, const nlohmann::json& data_json);
|
|
|
|
// 注册报警回调函数,当报警触发时调用
|
|
void register_alarm_callback(AlarmCallback callback);
|
|
|
|
// 辅助函数:将报警级别枚举转为字符串 (用于MQTT payload或日志)
|
|
static std::string alarm_level_to_string(AlarmLevel level);
|
|
|
|
private:
|
|
std::vector<AlarmRule> m_alarm_rules;
|
|
std::vector<AlarmCallback> m_alarm_callbacks;
|
|
|
|
// 记录每个规则上一次触发报警的时间,用于去抖动
|
|
std::map<std::string, std::chrono::steady_clock::time_point> m_last_alarm_time;
|
|
// 记录每个规则的当前报警状态,防止重复发送
|
|
std::map<std::string, bool> m_active_alarms;
|
|
|
|
std::mutex m_mutex; // 用于保护 m_last_alarm_time 和 m_active_alarms
|
|
|
|
bool evaluate_rule(const std::string& compare_type, double value, double threshold);
|
|
std::string generate_alarm_message(const AlarmRule& rule, double current_value);
|
|
std::string get_current_timestamp();
|
|
};
|