100 lines
3.1 KiB
C++
100 lines
3.1 KiB
C++
// alarm/alarm_service.h
|
|
#pragma once
|
|
|
|
#include <boost/asio/io_context.hpp>
|
|
#include <condition_variable>
|
|
#include <map>
|
|
#include <mutex>
|
|
#include <nlohmann/json.hpp>
|
|
#include <queue>
|
|
#include <string>
|
|
#include <thread>
|
|
#include <vector>
|
|
|
|
#include "alarm_defs.h"
|
|
#include "alarm_event.h"
|
|
#include "mqtt/mqtt_client.h"
|
|
#include "spdlog/spdlog.h"
|
|
#include "tts/piper_tts_interface.h"
|
|
|
|
using json = nlohmann::json;
|
|
|
|
class AlarmService {
|
|
public:
|
|
AlarmService(boost::asio::io_context &io, PiperTTSInterface &tts_service,
|
|
MqttClient &mqtt_client);
|
|
|
|
~AlarmService();
|
|
|
|
void stop();
|
|
|
|
bool load_rules(const std::string &config_path);
|
|
bool reload_rules();
|
|
|
|
void process_device_data(const std::string &device_id,
|
|
const std::string &data_json);
|
|
|
|
void process_system_data(const std::string &system_data_json);
|
|
|
|
nlohmann::json getActiveAlarmsJson();
|
|
nlohmann::json getAlarmHistoryJson(int limit);
|
|
|
|
/**
|
|
* @brief [新增] 手动清除一个当前激活的告警
|
|
* @param rule_id 要清除的规则IDparse_rules_from_fil
|
|
* @param device_id 触发该规则的设备ID
|
|
* @return 成功则返回 true
|
|
*/
|
|
bool manually_clear_alarm(const std::string &rule_id,
|
|
const std::string &device_id);
|
|
|
|
std::string get_rules_as_json_string();
|
|
|
|
/**
|
|
* @brief [新增] 从 JSON 字符串内容中解析和校验规则
|
|
* 这是所有解析器的核心
|
|
*/
|
|
bool parse_rules_from_content(const std::string &json_content,
|
|
std::vector<AlarmRule> &out_rules,
|
|
std::map<std::string, AlarmState> &out_states);
|
|
|
|
/**
|
|
* @brief [新增] 验证并保存告警规则到文件
|
|
* @param json_content 包含新规则的完整JSON字符串
|
|
* @return 成功 (JSON有效且写入成功) 则返回 true
|
|
*/
|
|
bool save_rules_from_json_string(const std::string &json_content);
|
|
|
|
private:
|
|
void check_rule_against_value(AlarmRule &rule, double value,
|
|
const std::string &actual_device_id);
|
|
std::string format_message(const AlarmRule &rule,
|
|
const std::string &template_str, double value,
|
|
const std::string &actual_device_id);
|
|
void trigger_alarm_action(AlarmRule &rule, double value,
|
|
const std::string &actual_device_id);
|
|
void clear_alarm(AlarmRule &rule, double value,
|
|
const std::string &actual_device_id);
|
|
void tts_worker();
|
|
void schedule_tts(const std::string &text);
|
|
bool parse_rules_from_file(const std::string &config_path,
|
|
std::vector<AlarmRule> &out_rules,
|
|
std::map<std::string, AlarmState> &out_states);
|
|
|
|
boost::asio::io_context &m_io_context;
|
|
PiperTTSInterface &m_tts_service;
|
|
MqttClient &m_mqtt_client;
|
|
|
|
std::vector<AlarmRule> m_rules;
|
|
std::map<std::string, AlarmState> m_alarm_states;
|
|
|
|
std::string m_rules_config_path;
|
|
std::mutex m_rules_mutex;
|
|
|
|
// TTS 播报队列
|
|
std::mutex m_tts_queue_mutex;
|
|
std::condition_variable m_tts_cv;
|
|
std::queue<std::string> m_tts_queue;
|
|
std::thread m_tts_thread;
|
|
bool m_tts_running;
|
|
}; |