优化了实现,采用websocket
This commit is contained in:
@@ -9,139 +9,130 @@
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include "../pPowerManger/SQLiteDB.h"
|
||||
#include "../pPowerManger/pmSysvariable.h"
|
||||
#include <MOOS/libMOOS/Comms/MOOSAsyncCommClient.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
// 定义一个全局变量,用于存储状态信息
|
||||
// 定义全局变量
|
||||
ccuState ccustate;
|
||||
StateData stateData;
|
||||
mutex wsMutex;
|
||||
vector<crow::websocket::connection*> wsConnections;
|
||||
shared_ptr<SQLiteDB> db;
|
||||
shared_ptr<MOOS::MOOSAsyncCommClient> moosClient;
|
||||
|
||||
|
||||
// WebSocket消息处理
|
||||
void sendStateUpdate() {
|
||||
crow::json::wvalue msg;
|
||||
string time;
|
||||
{
|
||||
lock_guard<mutex> lock(wsMutex);
|
||||
db->getStateData(stateData, time);
|
||||
}
|
||||
|
||||
msg["state"] = {
|
||||
{"time", time},
|
||||
{"state_id", stateData.state_id},
|
||||
{"state_name", stateData.state_name},
|
||||
{"event", stateData.event},
|
||||
{"event_id", stateData.event_id},
|
||||
{"fault_code", stateData.fault_code},
|
||||
{"note", stateData.note}
|
||||
};
|
||||
|
||||
// 添加数据库状态信息
|
||||
msg["db_status"] = {
|
||||
{"connected", db->isDatabaseConnected("/home/zjk/project/H100/H100PowerManger/data", "power_data.db")},
|
||||
{"database", db->getDBPatch()}
|
||||
};
|
||||
|
||||
// 添加MOOS数据库状态信息
|
||||
msg["moos_db_status"] = {
|
||||
{"connected", moosClient->IsConnected()},
|
||||
{"host", "localhost"},
|
||||
{"port", 9000}
|
||||
};
|
||||
|
||||
{
|
||||
lock_guard<mutex> lock(wsMutex);
|
||||
for(auto conn : wsConnections) {
|
||||
conn->send_text(msg.dump());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
crow::SimpleApp app;
|
||||
SQLiteDB db("/home/zjk/project/H100/H100PowerManger/data/power_data.db");
|
||||
MOOS::MOOSAsyncCommClient moosClient;
|
||||
moosClient.Run("localhost", 9000, "appPowerMangerWebUI");
|
||||
db = make_shared<SQLiteDB>("/home/zjk/project/H100/H100PowerManger/data/power_data.db");
|
||||
moosClient = make_shared<MOOS::MOOSAsyncCommClient>();
|
||||
moosClient->Run("localhost", 9000, "appPowerMangerWebUI");
|
||||
|
||||
std::cout << " Current Path -> " << std::system("pwd") << std::endl;
|
||||
// WebSocket路由
|
||||
CROW_WEBSOCKET_ROUTE(app, "/ws/state")
|
||||
.onopen([&](crow::websocket::connection& conn){
|
||||
lock_guard<mutex> lock(wsMutex);
|
||||
wsConnections.push_back(&conn);
|
||||
cout << "New WebSocket connection" << endl;
|
||||
})
|
||||
.onclose([&](crow::websocket::connection& conn, const string& /*reason*/, uint16_t /*code*/){
|
||||
lock_guard<mutex> lock(wsMutex);
|
||||
wsConnections.erase(
|
||||
remove(wsConnections.begin(), wsConnections.end(), &conn),
|
||||
wsConnections.end());
|
||||
cout << "WebSocket connection closed" << endl;
|
||||
})
|
||||
.onmessage([&](crow::websocket::connection& conn, const string& data, bool is_binary){
|
||||
// 处理收到的WebSocket消息
|
||||
cout << "Received WebSocket message: " << data << endl;
|
||||
});
|
||||
|
||||
// 定义路由,处理根路径的请求
|
||||
// 状态更新定时器
|
||||
thread([](){
|
||||
while(true) {
|
||||
sendStateUpdate();
|
||||
this_thread::sleep_for(chrono::seconds(1));
|
||||
}
|
||||
}).detach();
|
||||
|
||||
// 绑定主页路由
|
||||
CROW_ROUTE(app, "/")([]() {
|
||||
auto page = crow::mustache::load_text("index.html");
|
||||
return page;
|
||||
});
|
||||
|
||||
// 定义路由,处理 /api/power-data 的请求
|
||||
CROW_ROUTE(app, "/api/db-status")
|
||||
([&db]() {
|
||||
crow::json::wvalue response;
|
||||
if (db.isDatabaseConnected("/home/zjk/project/H100/H100PowerManger/data", "power_data.db")) {
|
||||
response["connected"] = true;
|
||||
response["database"] = db.getDBPatch();
|
||||
} else {
|
||||
response["connected"] = false;
|
||||
}
|
||||
return response;
|
||||
});
|
||||
CROW_ROUTE(app, "/api/state")
|
||||
([&db]() {
|
||||
crow::json::wvalue response;
|
||||
string time;
|
||||
db.getStateData(stateData,time);//状态机的状态
|
||||
response["state_id"] = stateData.state_id;
|
||||
response["state_name"] = stateData.state_name;
|
||||
response["event"] = stateData.event;
|
||||
response["event_id"] = stateData.event_id;
|
||||
response["fault_code"] = stateData.fault_code;
|
||||
response["note"] = stateData.note;
|
||||
response["time"] = time;
|
||||
return response;
|
||||
});
|
||||
// 定义路由,处理 /api/power-data 的请求
|
||||
CROW_ROUTE(app, "/api/download-db")
|
||||
([&db]() {
|
||||
std::ifstream file("/home/zjk/project/H100/H100PowerManger/src/appPowerMangerWebUI/index.html", std::ios::binary);
|
||||
if (!file) {
|
||||
return crow::response(404, "Database file not found");
|
||||
}
|
||||
|
||||
// 获取文件大小
|
||||
file.seekg(0, std::ios::end);
|
||||
size_t fileSize = file.tellg();
|
||||
file.seekg(0, std::ios::beg);
|
||||
|
||||
// 创建响应对象
|
||||
crow::response response;
|
||||
response.code = 200;
|
||||
response.set_header("Content-Type", "application/octet-stream");
|
||||
response.set_header("Content-Disposition", "attachment; filename=power_data.db");
|
||||
response.set_header("Content-Length", std::to_string(fileSize));
|
||||
|
||||
// 直接返回文件流
|
||||
response.body = std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
return response;
|
||||
});
|
||||
// 定义路由,处理 /api/moos-db 的请求
|
||||
CROW_ROUTE(app, "/api/moos-db")
|
||||
([&moosClient]() -> crow::json::wvalue {
|
||||
crow::json::wvalue response;
|
||||
if (moosClient.IsConnected()) {
|
||||
response["connected"] = true;
|
||||
response["host"] = moosClient.GetDBHostname();
|
||||
response["port"] = std::to_string(moosClient.GetDBHostPort());
|
||||
}
|
||||
else {
|
||||
response["connected"] = false;
|
||||
}
|
||||
return response;
|
||||
});
|
||||
|
||||
// 定义路由,处理 /api/moos-notify 的请求(POST)
|
||||
CROW_ROUTE(app, "/api/moos-notify").methods("POST"_method)
|
||||
([&moosClient](const crow::request& req) {
|
||||
// MOOS通知API
|
||||
CROW_ROUTE(app, "/api/moos-notify")
|
||||
.methods("POST"_method)
|
||||
([](const crow::request& req) {
|
||||
auto json = crow::json::load(req.body);
|
||||
if (!json) {
|
||||
return crow::response(400, "Invalid JSON");
|
||||
}
|
||||
|
||||
std::string var = json["var"].s();
|
||||
std::string key = json["key"].s();
|
||||
|
||||
// 发送MOOS消息
|
||||
bool notifyResult = moosClient.Notify(var, key);
|
||||
std::cout << "MOOS Notify: var=" << var << ", key=" << key
|
||||
<< ", result=" << (notifyResult ? "success" : "failed") << std::endl;
|
||||
string var = json["var"].s();
|
||||
string key = json["key"].s();
|
||||
|
||||
crow::response res;
|
||||
if (notifyResult)
|
||||
{
|
||||
res.body = crow::json::wvalue({
|
||||
{"success", true},
|
||||
{"message", key + ":" + var}
|
||||
}).dump();
|
||||
if (var.empty() || key.empty()) {
|
||||
return crow::response(400, "Var and Key are required");
|
||||
}
|
||||
else
|
||||
{
|
||||
res.body = crow::json::wvalue({
|
||||
{"success", false},
|
||||
{"message", key + ":" + var},
|
||||
}).dump();
|
||||
|
||||
try {
|
||||
moosClient->Notify(var, key);
|
||||
return crow::response(200, "{\"success\":true}");
|
||||
} catch (const exception& e) {
|
||||
return crow::response(500,
|
||||
crow::json::wvalue{{"success", false}, {"message", e.what()}}.dump());
|
||||
}
|
||||
res.set_header("Content-Type", "application/json");
|
||||
return res;
|
||||
});
|
||||
|
||||
// 启动服务器,监听端口 18080 并启动多线程
|
||||
std::cout << "Server started on port 18080" << std::endl;
|
||||
// app.port(18080).multithreaded().run();
|
||||
|
||||
// 启动服务器
|
||||
app.port(18080)
|
||||
.multithreaded()
|
||||
.concurrency(16) // 增加并发线程数
|
||||
.concurrency(16)
|
||||
.run();
|
||||
|
||||
return 0;
|
||||
|
||||
Reference in New Issue
Block a user