优化了web界面,下载功能等

This commit is contained in:
zjk
2025-03-02 14:35:21 +08:00
parent 0fbe95bc45
commit 16cffa296a
6 changed files with 773 additions and 176 deletions
+53 -4
View File
@@ -24,7 +24,6 @@ vector<crow::websocket::connection*> wsConnections;
shared_ptr<SQLiteDB> db;
shared_ptr<MOOS::MOOSAsyncCommClient> moosClient;
// WebSocket消息处理
void sendStateUpdate() {
crow::json::wvalue msg;
@@ -47,7 +46,8 @@ void sendStateUpdate() {
// 添加数据库状态信息
msg["db_status"] = {
{"connected", db->isDatabaseConnected("/home/zjk/project/H100/H100PowerManger/data", "power_data.db")},
{"database", db->getDBPatch()}
{"database", db->getDBPatch()},
{"size", db->getDatabaseSize()}
};
// 添加MOOS数据库状态信息
@@ -69,7 +69,7 @@ int main() {
crow::SimpleApp app;
db = make_shared<SQLiteDB>("/home/zjk/project/H100/H100PowerManger/data/power_data.db");
moosClient = make_shared<MOOS::MOOSAsyncCommClient>();
moosClient->Run("localhost", 9000, "appPowerMangerWebUI", 200); // 设置更高的通信频率
moosClient->Run("localhost", 9000, "appPowerMangerWebUI");
// WebSocket路由
CROW_WEBSOCKET_ROUTE(app, "/ws/state")
@@ -86,7 +86,6 @@ int main() {
cout << "WebSocket connection closed" << endl;
})
.onmessage([&](crow::websocket::connection& conn, const string& data, bool is_binary){
// 处理收到的WebSocket消息
cout << "Received WebSocket message: " << data << endl;
});
@@ -129,6 +128,56 @@ int main() {
}
});
// 下载数据库API
CROW_ROUTE(app, "/api/download-db")
([]() {
const std::string dbPath = "/home/zjk/project/H100/H100PowerManger/data/power_data.db";
const size_t chunkSize = 4096; // 4KB chunks
std::ifstream file(dbPath, std::ios::binary | std::ios::ate);
if (!file) {
return crow::response(404, "Database file not found");
}
// 获取文件大小
std::streamsize fileSize = file.tellg();
file.seekg(0, std::ios::beg);
if (fileSize == 0) {
return crow::response(500, "Database file is empty");
}
// 创建响应
crow::response res;
res.code = 200;
res.set_header("Content-Type", "application/octet-stream");
res.set_header("Content-Disposition", "attachment; filename=power_data.db");
res.set_header("Content-Length", std::to_string(fileSize));
try {
// 分块读取和写入文件
auto buffer = std::make_unique<char[]>(chunkSize);
size_t totalSent = 0;
while (totalSent < fileSize) {
size_t remaining = fileSize - totalSent;
size_t readSize = std::min(remaining, chunkSize);
file.read(buffer.get(), readSize);
if (file.gcount() <= 0) break;
res.write(std::string(buffer.get(), file.gcount()));
totalSent += file.gcount();
}
file.close();
return res;
} catch (const std::exception& e) {
file.close();
return crow::response(500, std::string("Download failed: ") + e.what());
}
});
// 启动服务器
app.port(18080)
.multithreaded()