Files
H100PowerManger/src/pELoad/web/WebServer.h
T

56 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#ifndef PELOAD_WEB_SERVER_H
#define PELOAD_WEB_SERVER_H
#define UNIX
#include "mongoose.h"
#include <string>
#include <functional>
#include <vector>
#include <mutex>
#include <atomic>
#include <thread>
namespace eload {
class WebServer {
public:
WebServer();
~WebServer();
bool start(int port);
void stop();
bool isRunning() const { return m_running; }
// 向所有 WebSocket 客户端广播文本
// 线程安全:mongoose 非线程安全,本接口只把文本放入待发队列,
// 由 Web 线程在 mg_mgr_poll 返回后统一发送(禁止跨线程直接 mg_ws_send)
void broadcast(const std::string& text);
// 新客户端连接时调用,返回初始快照
void setOnOpen(std::function<std::string()> handler);
// 处理 /api/* 请求:返回 (Content-Type, body)。
// 默认内容类型 application/json;文本/CSV 接口由处理器自行指定。
void setApiHandler(std::function<std::pair<std::string, std::string>(const std::string& uri, const std::string& query)> handler);
private:
static bool serverThreadCB(void* pParam);
bool serverThreadFunc();
void handleEvent(struct mg_connection* c, int ev, void* ev_data);
void flushPending();
struct mg_mgr m_mgr;
int m_port = 0;
std::atomic<bool> m_running{false};
std::thread m_thread;
std::mutex m_pendingMutex;
std::string m_pending; // latest snapshot to broadcast
std::vector<mg_connection*> m_wsConnections; // web thread only
std::function<std::string()> m_onOpen;
std::function<std::pair<std::string, std::string>(const std::string&, const std::string&)> m_apiHandler;
};
} // namespace eload
#endif // PELOAD_WEB_SERVER_H