upload
This commit is contained in:
779
libs/vslam_web/src/web_server.cc
Normal file
779
libs/vslam_web/src/web_server.cc
Normal file
@@ -0,0 +1,779 @@
|
||||
#include "vslam/web_server.h"
|
||||
|
||||
#include <boost/asio/dispatch.hpp>
|
||||
#include <boost/asio/io_context.hpp>
|
||||
#include <boost/asio/ip/tcp.hpp>
|
||||
#include <boost/asio/post.hpp>
|
||||
#include <boost/asio/strand.hpp>
|
||||
#include <boost/beast/core.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/json_parse.h"
|
||||
#include "json_writer.h"
|
||||
#include "vslam/binary_codec.h"
|
||||
#include "vslam/log.h"
|
||||
#include "web_assets.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace asio = boost::asio;
|
||||
using tcp = asio::ip::tcp;
|
||||
|
||||
const char* MimeType(const std::string& path) {
|
||||
const size_t dot = path.rfind('.');
|
||||
const std::string ext = dot == std::string::npos ? "" : path.substr(dot);
|
||||
if (ext == ".html") return "text/html; charset=utf-8";
|
||||
if (ext == ".js") return "application/javascript; charset=utf-8";
|
||||
if (ext == ".css") return "text/css; charset=utf-8";
|
||||
if (ext == ".json") return "application/json";
|
||||
if (ext == ".svg") return "image/svg+xml";
|
||||
if (ext == ".ico") return "image/x-icon";
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// Chan duong dan di len tren (..) va duong dan tuyet doi. Endpoint nay khong
|
||||
// xac thuc nen phai gia dinh duong dan la thu dich.
|
||||
bool SafeAssetPath(const std::string& target, std::string* out) {
|
||||
if (target.empty() || target[0] != '/') return false;
|
||||
std::string p = target.substr(1);
|
||||
const size_t q = p.find('?');
|
||||
if (q != std::string::npos) p = p.substr(0, q);
|
||||
if (p.empty()) p = "index.html";
|
||||
if (p.find("..") != std::string::npos) return false;
|
||||
if (p.find('\\') != std::string::npos) return false;
|
||||
*out = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Giao dien chung cho HttpSession va WsSession, de Stop() dong duoc moi phien
|
||||
// ma khong can biet loai.
|
||||
class SessionBase {
|
||||
public:
|
||||
virtual ~SessionBase() = default;
|
||||
virtual void Close() = 0;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class WebServerImpl {
|
||||
public:
|
||||
WebConfig cfg;
|
||||
WebServer::CommandHandler on_command;
|
||||
WebServer::TeleopHandler on_teleop;
|
||||
|
||||
asio::io_context ioc;
|
||||
std::unique_ptr<tcp::acceptor> acceptor;
|
||||
std::vector<std::thread> threads;
|
||||
std::atomic<bool> running{false};
|
||||
uint16_t bound_port = 0;
|
||||
|
||||
// MOI phien deu giu mot shared_ptr<WebServerImpl> (chung can cfg, stats,
|
||||
// handler). Neu o day giu nguoc lai bang shared_ptr thi thanh chu trinh va
|
||||
// khong gi duoc giai phong. Giu bang weak_ptr.
|
||||
//
|
||||
// Chu trinh thu hai, tinh vi hon, da tung lam ro toan bo server: io_context
|
||||
// la THANH VIEN cua WebServerImpl, con handler dang cho thi giu
|
||||
// shared_ptr<WebServerImpl>. ioc.stop() KHONG huy handler dang cho -- chung
|
||||
// nam lai trong hang doi cua io_context cho toi khi io_context bi huy, ma
|
||||
// io_context lai khong the bi huy vi chinh chung dang giu no. Vi vay Stop()
|
||||
// phai DONG MOI PHIEN TRUOC, de handler hoan tat voi loi va nha con tro ra.
|
||||
mutable std::mutex sessions_mu;
|
||||
std::map<const SessionBase*, std::weak_ptr<SessionBase>> all_sessions;
|
||||
std::map<const class WsSession*, std::weak_ptr<class WsSession>> ws_sessions;
|
||||
|
||||
void Register(const SessionBase* key, std::weak_ptr<SessionBase> w) {
|
||||
std::lock_guard<std::mutex> lk(sessions_mu);
|
||||
all_sessions.emplace(key, std::move(w));
|
||||
}
|
||||
void Unregister(const SessionBase* key) {
|
||||
std::lock_guard<std::mutex> lk(sessions_mu);
|
||||
all_sessions.erase(key);
|
||||
}
|
||||
|
||||
mutable std::mutex stats_mu;
|
||||
WebServer::Stats stats;
|
||||
|
||||
// Hinh hoc 3D cua the gioi. Dat mot lan luc khoi dong, doc tu luong web --
|
||||
// mutex RIENG, khong dung chung voi stats_mu: mot yeu cau world.bin sao 6.7
|
||||
// MB duoi lock, giu stats_mu ngan ay lau se lam nghen moi khung gui di.
|
||||
mutable std::mutex world_mu;
|
||||
std::string world_blob;
|
||||
|
||||
WebServerImpl(WebConfig c, WebServer::CommandHandler cmd,
|
||||
WebServer::TeleopHandler tel)
|
||||
: cfg(std::move(c)), on_command(std::move(cmd)), on_teleop(std::move(tel)) {}
|
||||
|
||||
void BumpSent(size_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.frames_sent++;
|
||||
stats.bytes_sent += bytes;
|
||||
}
|
||||
void BumpDropped() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.frames_dropped++;
|
||||
}
|
||||
void BumpAuthFailure() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.auth_failures++;
|
||||
}
|
||||
void BumpCommand() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.commands_handled++;
|
||||
}
|
||||
void BumpConnection() {
|
||||
std::lock_guard<std::mutex> lk(stats_mu);
|
||||
stats.connections_total++;
|
||||
}
|
||||
// Goi khi da giu sessions_mu. stats_mu la khoa khac nen khong deadlock,
|
||||
// nhung THU TU phai luon la sessions_mu -> stats_mu, khong bao gio nguoc.
|
||||
void BumpConnectionLocked() { BumpConnection(); }
|
||||
|
||||
// Bat doi xung co y: BAT e-stop luon duoc phep (fail-safe); GO e-stop va
|
||||
// reset bumper bat buoc co token. Mot endpoint e-stop khong xac thuc tren
|
||||
// WiFi LAN nghia la ai cung e-stop duoc -- chap nhan duoc; nhung ai cung
|
||||
// GO duoc e-stop cua nguoi khac thi khong.
|
||||
bool CommandNeedsAuth(const std::string& cmd, const std::string& body) const {
|
||||
if (cfg.auth_token.empty()) return false;
|
||||
if (cmd != "safety/estop") return true;
|
||||
|
||||
bool on = false;
|
||||
if (!JsonGetBool(body, "on", &on)) {
|
||||
// KHONG parse duoc -> DOI XAC THUC (fail closed).
|
||||
//
|
||||
// Ban dau cho nay mac dinh on=true roi bo qua xac thuc, va do la mot lo
|
||||
// hong that: handler dien giai cung mot body hong theo cach khac (no
|
||||
// tim chuoi "true") nen co the GO e-stop, trong khi lop xac thuc tuong
|
||||
// la dang BAT. Hai ben bat dong y nghia cua body la du de vuot xac thuc.
|
||||
//
|
||||
// Quy tac: khi khong chac y dinh la gi thi doi token. Chi mien xac thuc
|
||||
// cho truong hop da doc duoc TUONG MINH la on=true.
|
||||
return true;
|
||||
}
|
||||
return !on; // BAT e-stop: mien. GO e-stop: doi token.
|
||||
}
|
||||
|
||||
bool AuthOk(const std::string& provided) const {
|
||||
return cfg.auth_token.empty() || provided == cfg.auth_token;
|
||||
}
|
||||
|
||||
bool LoadAsset(const std::string& name, std::string* body, const char** mime) {
|
||||
*mime = MimeType(name);
|
||||
|
||||
if (!cfg.asset_dir.empty()) {
|
||||
const std::string path = cfg.asset_dir + "/" + name;
|
||||
std::ifstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
std::ostringstream ss;
|
||||
ss << f.rdbuf();
|
||||
*body = ss.str();
|
||||
return true;
|
||||
}
|
||||
|
||||
const auto& assets = EmbeddedAssets();
|
||||
const auto it = assets.find(name);
|
||||
if (it == assets.end()) return false;
|
||||
body->assign(reinterpret_cast<const char*>(it->second.data), it->second.size);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WsSession: mot ket noi WebSocket.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class WsSession : public std::enable_shared_from_this<WsSession>,
|
||||
public SessionBase {
|
||||
public:
|
||||
WsSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
|
||||
: ws_(std::move(socket)), impl_(std::move(impl)) {}
|
||||
|
||||
~WsSession() override { impl_->Unregister(this); }
|
||||
|
||||
void Run(http::request<http::string_body> req) {
|
||||
ws_.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));
|
||||
ws_.set_option(websocket::stream_base::decorator([](websocket::response_type& res) {
|
||||
res.set(http::field::server, "vslam");
|
||||
}));
|
||||
impl_->Register(this, std::weak_ptr<SessionBase>(
|
||||
std::static_pointer_cast<SessionBase>(shared_from_this())));
|
||||
auto self = shared_from_this();
|
||||
ws_.async_accept(req, [self](beast::error_code ec) { self->OnAccept(ec); });
|
||||
}
|
||||
|
||||
// Goi tu luong web_tx. Khong chan.
|
||||
void Send(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
|
||||
auto self = shared_from_this();
|
||||
asio::post(ws_.get_executor(), [self, payload, is_binary, is_map] {
|
||||
self->Enqueue(std::move(payload), is_binary, is_map);
|
||||
});
|
||||
}
|
||||
|
||||
uint32_t acked_map_version() const { return acked_map_version_.load(); }
|
||||
bool world_map_sent() const { return world_map_sent_.load(); }
|
||||
void mark_world_map_sent() { world_map_sent_.store(true); }
|
||||
void set_acked_map_version(uint32_t v) { acked_map_version_.store(v); }
|
||||
|
||||
void Close() override {
|
||||
auto self = shared_from_this();
|
||||
asio::post(ws_.get_executor(), [self] {
|
||||
beast::error_code ec;
|
||||
// close() tu te truoc; neu that bai thi dong tho de handler dang cho
|
||||
// hoan tat voi loi va nha shared_ptr ra.
|
||||
self->ws_.close(websocket::close_code::going_away, ec);
|
||||
if (ec) {
|
||||
beast::get_lowest_layer(self->ws_).close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
struct Frame {
|
||||
std::shared_ptr<const std::string> data;
|
||||
bool binary = true;
|
||||
bool is_map = false;
|
||||
};
|
||||
|
||||
void OnAccept(beast::error_code ec) {
|
||||
if (ec) {
|
||||
VSLAM_DEBUG("ws accept: " << ec.message());
|
||||
Remove();
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->ws_sessions.emplace(this, weak_from_this());
|
||||
impl_->BumpConnectionLocked();
|
||||
VSLAM_INFO("web: client ket noi (tong " << impl_->ws_sessions.size() << ")");
|
||||
}
|
||||
Read();
|
||||
}
|
||||
|
||||
void Read() {
|
||||
auto self = shared_from_this();
|
||||
ws_.async_read(buffer_, [self](beast::error_code ec, size_t n) {
|
||||
self->OnRead(ec, n);
|
||||
});
|
||||
}
|
||||
|
||||
void OnRead(beast::error_code ec, size_t /*n*/) {
|
||||
if (ec) {
|
||||
Remove();
|
||||
return;
|
||||
}
|
||||
const std::string msg = beast::buffers_to_string(buffer_.data());
|
||||
buffer_.consume(buffer_.size());
|
||||
HandleClientMessage(msg);
|
||||
Read();
|
||||
}
|
||||
|
||||
void HandleClientMessage(const std::string& msg) {
|
||||
std::string type;
|
||||
if (!JsonGetString(msg, "t", &type)) return;
|
||||
|
||||
if (type == "cmd") {
|
||||
// Joypad cam ung: gia tri chuan hoa [-1,1] o 20 Hz.
|
||||
// Toan bo shaping (ramp, deadman) lam o C++ trong teleop_shaper, khong
|
||||
// o JS -- khong bao gio tin browser ve dinh dang chuyen dong.
|
||||
double vx = 0.0, wz = 0.0;
|
||||
JsonGetNumber(msg, "vx", &vx);
|
||||
JsonGetNumber(msg, "wz", &wz);
|
||||
vx = std::max(-1.0, std::min(1.0, vx));
|
||||
wz = std::max(-1.0, std::min(1.0, wz));
|
||||
if (impl_->on_teleop) impl_->on_teleop(vx, wz);
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == "ack_map") {
|
||||
double v = 0.0;
|
||||
if (JsonGetNumber(msg, "version", &v) && v >= 0.0) {
|
||||
set_acked_map_version(static_cast<uint32_t>(v));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void Enqueue(std::shared_ptr<const std::string> payload, bool is_binary, bool is_map) {
|
||||
if (queue_.size() >= impl_->cfg.max_queued_frames) {
|
||||
// Day hang doi. Drop khung CU NHAT KHONG PHAI MAP.
|
||||
// MAP khong bao gio bi drop: mat mot khung scan la mat 100 ms du lieu,
|
||||
// mat khung MAP la client hien ban do sai cho toi lan doi version sau --
|
||||
// co the la vinh vien trong che do localization.
|
||||
auto it = std::find_if(queue_.begin(), queue_.end(),
|
||||
[](const Frame& f) { return !f.is_map; });
|
||||
if (it != queue_.end()) {
|
||||
queue_.erase(it);
|
||||
impl_->BumpDropped();
|
||||
} else if (!is_map) {
|
||||
impl_->BumpDropped();
|
||||
return; // hang doi toan MAP, bo khung moi
|
||||
}
|
||||
}
|
||||
|
||||
queue_.push_back(Frame{std::move(payload), is_binary, is_map});
|
||||
if (!writing_) Write();
|
||||
}
|
||||
|
||||
void Write() {
|
||||
if (queue_.empty()) {
|
||||
writing_ = false;
|
||||
return;
|
||||
}
|
||||
writing_ = true;
|
||||
const Frame& f = queue_.front();
|
||||
ws_.binary(f.binary);
|
||||
|
||||
auto self = shared_from_this();
|
||||
const size_t n = f.data->size();
|
||||
ws_.async_write(asio::buffer(*f.data), [self, n](beast::error_code ec, size_t) {
|
||||
if (ec) {
|
||||
self->Remove();
|
||||
return;
|
||||
}
|
||||
self->impl_->BumpSent(n);
|
||||
self->queue_.pop_front();
|
||||
self->Write();
|
||||
});
|
||||
}
|
||||
|
||||
void Remove() {
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->ws_sessions.erase(this);
|
||||
}
|
||||
|
||||
websocket::stream<beast::tcp_stream> ws_;
|
||||
std::shared_ptr<WebServerImpl> impl_;
|
||||
beast::flat_buffer buffer_;
|
||||
std::deque<Frame> queue_;
|
||||
bool writing_ = false;
|
||||
std::atomic<uint32_t> acked_map_version_{0};
|
||||
// Ban do the gioi la TINH trong mo phong -- gui mot lan la du, khong can
|
||||
// co che version/ACK nhu ban do SLAM.
|
||||
std::atomic<bool> world_map_sent_{false};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HttpSession: phuc vu asset tinh va POST /api/*.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class HttpSession : public std::enable_shared_from_this<HttpSession>,
|
||||
public SessionBase {
|
||||
public:
|
||||
HttpSession(tcp::socket&& socket, std::shared_ptr<WebServerImpl> impl)
|
||||
: stream_(std::move(socket)), impl_(std::move(impl)) {}
|
||||
|
||||
~HttpSession() override { impl_->Unregister(this); }
|
||||
|
||||
void Run() {
|
||||
// Dang ky de Stop() dong duoc. Phai lam o day chu khong o constructor:
|
||||
// shared_from_this() chua dung duoc trong constructor.
|
||||
impl_->Register(this, std::weak_ptr<SessionBase>(
|
||||
std::static_pointer_cast<SessionBase>(shared_from_this())));
|
||||
asio::dispatch(stream_.get_executor(),
|
||||
[self = shared_from_this()] { self->Read(); });
|
||||
}
|
||||
|
||||
void Close() override {
|
||||
auto self = shared_from_this();
|
||||
asio::post(stream_.get_executor(), [self] {
|
||||
beast::error_code ec;
|
||||
self->stream_.socket().shutdown(tcp::socket::shutdown_both, ec);
|
||||
self->stream_.close();
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
void Read() {
|
||||
req_ = {};
|
||||
stream_.expires_after(std::chrono::seconds(30));
|
||||
auto self = shared_from_this();
|
||||
http::async_read(stream_, buffer_, req_,
|
||||
[self](beast::error_code ec, size_t) { self->OnRead(ec); });
|
||||
}
|
||||
|
||||
void OnRead(beast::error_code ec) {
|
||||
if (ec == http::error::end_of_stream) {
|
||||
Finish();
|
||||
return;
|
||||
}
|
||||
if (ec) return;
|
||||
|
||||
if (websocket::is_upgrade(req_)) {
|
||||
// Token cho WS di qua query string vi browser khong dat header tuy y
|
||||
// duoc tren WebSocket handshake.
|
||||
if (!impl_->cfg.auth_token.empty()) {
|
||||
const std::string target(req_.target());
|
||||
const std::string want = "token=" + impl_->cfg.auth_token;
|
||||
if (target.find(want) == std::string::npos) {
|
||||
impl_->BumpAuthFailure();
|
||||
Respond(http::status::unauthorized, "text/plain", "thieu hoac sai token\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::make_shared<WsSession>(stream_.release_socket(), impl_)->Run(std::move(req_));
|
||||
return;
|
||||
}
|
||||
|
||||
HandleRequest();
|
||||
}
|
||||
|
||||
void HandleRequest() {
|
||||
const std::string target(req_.target());
|
||||
|
||||
if (req_.method() == http::verb::post && target.rfind("/api/", 0) == 0) {
|
||||
HandleApi(target.substr(5));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req_.method() == http::verb::get && target.rfind("/api/", 0) == 0) {
|
||||
HandleApiGet(target.substr(5));
|
||||
return;
|
||||
}
|
||||
|
||||
if (req_.method() != http::verb::get && req_.method() != http::verb::head) {
|
||||
Respond(http::status::method_not_allowed, "text/plain", "chi GET/POST\n");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string name;
|
||||
if (!SafeAssetPath(target, &name)) {
|
||||
Respond(http::status::bad_request, "text/plain", "duong dan khong hop le\n");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string body;
|
||||
const char* mime = nullptr;
|
||||
if (!impl_->LoadAsset(name, &body, &mime)) {
|
||||
Respond(http::status::not_found, "text/plain", "khong tim thay\n");
|
||||
return;
|
||||
}
|
||||
Respond(http::status::ok, mime, body);
|
||||
}
|
||||
|
||||
void HandleApi(const std::string& cmd) {
|
||||
const std::string body = req_.body();
|
||||
|
||||
if (impl_->CommandNeedsAuth(cmd, body)) {
|
||||
std::string provided;
|
||||
const auto it = req_.find("X-Auth-Token");
|
||||
if (it != req_.end()) provided = std::string(it->value());
|
||||
if (!impl_->AuthOk(provided)) {
|
||||
impl_->BumpAuthFailure();
|
||||
VSLAM_WARN("web: tu choi lenh khong co token: " << cmd);
|
||||
std::string out;
|
||||
WriteStatusJson(StatusResponse::Error(StatusCode::kUnauthenticated,
|
||||
"can X-Auth-Token"),
|
||||
&out);
|
||||
Respond(http::status::unauthorized, "application/json", out);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
StatusResponse st = StatusResponse::Error(StatusCode::kNotFound, "khong co handler");
|
||||
if (impl_->on_command) {
|
||||
// Handler chay TREN LUONG IO: phai tra ve ngay. Cach dung dung la day
|
||||
// vao hang doi lenh roi tra Ok -- luong web khong bao gio truc tiep sua
|
||||
// state cua estimator.
|
||||
st = impl_->on_command(cmd, body);
|
||||
}
|
||||
impl_->BumpCommand();
|
||||
|
||||
std::string out;
|
||||
WriteStatusJson(st, &out);
|
||||
Respond(st.ok() ? http::status::ok : http::status::bad_request,
|
||||
"application/json", out);
|
||||
}
|
||||
|
||||
void HandleApiGet(const std::string& cmd) {
|
||||
if (cmd == "status") {
|
||||
const WebServer::Stats s = [this] {
|
||||
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
||||
return impl_->stats;
|
||||
}();
|
||||
size_t clients = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
clients = impl_->ws_sessions.size();
|
||||
}
|
||||
std::ostringstream oss;
|
||||
oss << "{\"clients\":" << clients
|
||||
<< ",\"connections_total\":" << s.connections_total
|
||||
<< ",\"frames_sent\":" << s.frames_sent
|
||||
<< ",\"frames_dropped\":" << s.frames_dropped
|
||||
<< ",\"bytes_sent\":" << s.bytes_sent
|
||||
<< ",\"commands_handled\":" << s.commands_handled
|
||||
<< ",\"auth_failures\":" << s.auth_failures << "}";
|
||||
Respond(http::status::ok, "application/json", oss.str());
|
||||
return;
|
||||
}
|
||||
if (cmd == "world.bin") {
|
||||
std::string blob;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->world_mu);
|
||||
blob = impl_->world_blob;
|
||||
}
|
||||
if (blob.empty()) {
|
||||
Respond(http::status::not_found, "application/json",
|
||||
"{\"code\":2,\"message\":\"khong chay tu file .world\"}");
|
||||
return;
|
||||
}
|
||||
Respond(http::status::ok, "application/octet-stream", blob);
|
||||
return;
|
||||
}
|
||||
Respond(http::status::not_found, "application/json",
|
||||
"{\"code\":2,\"message\":\"khong co endpoint\"}");
|
||||
}
|
||||
|
||||
void Respond(http::status status, const char* mime, const std::string& body) {
|
||||
auto res = std::make_shared<http::response<http::string_body>>(status, req_.version());
|
||||
res->set(http::field::server, "vslam");
|
||||
res->set(http::field::content_type, mime);
|
||||
// UI la mot trang duy nhat trong LAN; khong cache de sua asset la thay ngay.
|
||||
res->set(http::field::cache_control, "no-store");
|
||||
res->keep_alive(req_.keep_alive());
|
||||
res->body() = body;
|
||||
res->prepare_payload();
|
||||
|
||||
auto self = shared_from_this();
|
||||
const bool keep = res->keep_alive();
|
||||
http::async_write(stream_, *res,
|
||||
[self, res, keep](beast::error_code ec, size_t) {
|
||||
if (ec || !keep) {
|
||||
self->Finish();
|
||||
return;
|
||||
}
|
||||
self->Read();
|
||||
});
|
||||
}
|
||||
|
||||
// Ket thuc binh thuong sau khi tra loi xong. Khac han Close() cong khai o
|
||||
// tren: cai do la dong CUONG BUC luc tat server.
|
||||
void Finish() {
|
||||
beast::error_code ec;
|
||||
stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
|
||||
}
|
||||
|
||||
beast::tcp_stream stream_;
|
||||
std::shared_ptr<WebServerImpl> impl_;
|
||||
beast::flat_buffer buffer_;
|
||||
http::request<http::string_body> req_;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WebServer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
WebServer::WebServer(WebConfig cfg, CommandHandler on_command, TeleopHandler on_teleop)
|
||||
: impl_(std::make_shared<WebServerImpl>(std::move(cfg), std::move(on_command),
|
||||
std::move(on_teleop))) {}
|
||||
|
||||
WebServer::~WebServer() { Stop(); }
|
||||
|
||||
StatusResponse WebServer::Start() {
|
||||
if (impl_->running.load()) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da chay roi");
|
||||
}
|
||||
|
||||
if (impl_->cfg.auth_token.empty()) {
|
||||
VSLAM_WARN("web: KHONG co auth_token -- bat ky ai trong LAN deu go duoc "
|
||||
"e-stop. Dat system.web.auth_token truoc khi chay that.");
|
||||
}
|
||||
|
||||
beast::error_code ec;
|
||||
const auto addr = asio::ip::make_address(impl_->cfg.bind_address, ec);
|
||||
if (ec) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"bind_address khong hop le: " + ec.message());
|
||||
}
|
||||
|
||||
impl_->acceptor = std::make_unique<tcp::acceptor>(impl_->ioc);
|
||||
const tcp::endpoint ep(addr, impl_->cfg.port);
|
||||
|
||||
impl_->acceptor->open(ep.protocol(), ec);
|
||||
if (ec) return StatusResponse::Error(StatusCode::kInternal, "open: " + ec.message());
|
||||
|
||||
impl_->acceptor->set_option(asio::socket_base::reuse_address(true), ec);
|
||||
impl_->acceptor->bind(ep, ec);
|
||||
if (ec) {
|
||||
return StatusResponse::Error(StatusCode::kUnavailable,
|
||||
"bind cong " + std::to_string(impl_->cfg.port) + ": " +
|
||||
ec.message());
|
||||
}
|
||||
impl_->acceptor->listen(asio::socket_base::max_listen_connections, ec);
|
||||
if (ec) return StatusResponse::Error(StatusCode::kInternal, "listen: " + ec.message());
|
||||
|
||||
impl_->bound_port = impl_->acceptor->local_endpoint().port();
|
||||
impl_->running.store(true);
|
||||
|
||||
DoAccept();
|
||||
|
||||
const int n = std::max(1, impl_->cfg.io_threads);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
impl_->threads.emplace_back([impl = impl_] { impl->ioc.run(); });
|
||||
}
|
||||
|
||||
VSLAM_INFO("web: dang nghe tren " << impl_->cfg.bind_address << ":"
|
||||
<< impl_->bound_port);
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
void WebServer::DoAccept() {
|
||||
impl_->acceptor->async_accept(
|
||||
asio::make_strand(impl_->ioc),
|
||||
[this](beast::error_code ec, tcp::socket socket) {
|
||||
if (!impl_->running.load()) return;
|
||||
if (!ec) {
|
||||
std::make_shared<HttpSession>(std::move(socket), impl_)->Run();
|
||||
}
|
||||
DoAccept();
|
||||
});
|
||||
}
|
||||
|
||||
void WebServer::Stop() {
|
||||
if (!impl_ || !impl_->running.exchange(false)) return;
|
||||
|
||||
// THU TU O DAY LA QUAN TRONG, khong duoc doi.
|
||||
//
|
||||
// 1. Dung nhan ket noi moi.
|
||||
beast::error_code ec;
|
||||
if (impl_->acceptor) impl_->acceptor->close(ec);
|
||||
|
||||
// 2. Dong moi phien, va lam TRUOC khi dung io_context.
|
||||
//
|
||||
// Moi phien giu mot shared_ptr<WebServerImpl>, ma io_context lai la
|
||||
// thanh vien cua WebServerImpl. ioc.stop() KHONG huy handler dang cho --
|
||||
// chung nam lai trong hang doi cho toi khi io_context bi huy, ma
|
||||
// io_context khong the bi huy vi chinh chung dang giu no. Ket qua la ca
|
||||
// server (io_context, thread, session) ro vinh vien sau moi lan Stop().
|
||||
//
|
||||
// Dong socket lam cac async op dang cho hoan tat voi loi, handler chay,
|
||||
// session nha con tro, chu trinh dut.
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
for (const auto& kv : impl_->all_sessions) {
|
||||
if (auto s = kv.second.lock()) s->Close();
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Cho io_context can viec mot cach tu nhien. KHONG goi ioc.stop() o day:
|
||||
// stop() lam run() tra ve ngay va bo lai handler chua chay, dung lai
|
||||
// dung van de o tren.
|
||||
for (auto& t : impl_->threads) {
|
||||
if (t.joinable()) t.join();
|
||||
}
|
||||
impl_->threads.clear();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
impl_->all_sessions.clear();
|
||||
impl_->ws_sessions.clear();
|
||||
}
|
||||
VSLAM_INFO("web: da dung");
|
||||
}
|
||||
|
||||
void WebServer::SetWorldMesh(std::string blob) {
|
||||
std::lock_guard<std::mutex> lk(impl_->world_mu);
|
||||
impl_->world_blob = std::move(blob);
|
||||
}
|
||||
|
||||
void WebServer::Publish(const WebSnapshot& snap) {
|
||||
// Khong co client thi KHONG serialize gi ca. Serialize mot cloud 4000 diem
|
||||
// va mot map cho khong ai xem la lang phi that o 10 Hz tren Jetson.
|
||||
std::vector<std::shared_ptr<WsSession>> targets;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
if (impl_->ws_sessions.empty()) return;
|
||||
targets.reserve(impl_->ws_sessions.size());
|
||||
for (const auto& kv : impl_->ws_sessions) {
|
||||
if (auto s = kv.second.lock()) targets.push_back(std::move(s));
|
||||
}
|
||||
if (targets.empty()) return;
|
||||
}
|
||||
|
||||
auto state = std::make_shared<std::string>();
|
||||
WriteStateJson(snap, state.get());
|
||||
for (const auto& s : targets) s->Send(state, /*binary=*/false, /*is_map=*/false);
|
||||
|
||||
if (snap.scan) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeScan(*snap.scan, snap.stamp, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
if (snap.cloud) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodeCloud(*snap.cloud, snap.stamp, impl_->cfg.cloud_max_points,
|
||||
impl_->cfg.cloud_quant_m, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
if (!snap.trajectory.empty()) {
|
||||
auto buf = std::make_shared<std::string>();
|
||||
EncodePath(snap.trajectory, snap.stamp, impl_->cfg.path_min_step_m, buf.get());
|
||||
for (const auto& s : targets) s->Send(buf, true, false);
|
||||
}
|
||||
|
||||
// BAN DO THE GIOI -- khung nhin "Gazebo". Gui MOT lan cho moi client.
|
||||
//
|
||||
// Tach khoi ban do SLAM co y: hai thu tra loi hai cau hoi khac nhau, va
|
||||
// doi chieu chung chinh la ly do nguoi ta mo ca Gazebo lan RViz.
|
||||
if (snap.world_map) {
|
||||
std::shared_ptr<std::string> buf;
|
||||
for (const auto& s : targets) {
|
||||
if (s->world_map_sent()) continue;
|
||||
if (!buf) {
|
||||
buf = std::make_shared<std::string>();
|
||||
EncodeMapFull(*snap.world_map, snap.stamp, buf.get(), BinaryType::kWorldMap);
|
||||
}
|
||||
s->Send(buf, true, /*is_map=*/true);
|
||||
s->mark_world_map_sent();
|
||||
}
|
||||
}
|
||||
|
||||
// MAP chi gui cho client chua xac nhan phien ban nay. Ma hoa mot lan roi
|
||||
// dung chung -- 62 kB cho ban do lon nhat (do tren map_hospital.db).
|
||||
if (snap.map && snap.slam.map_version != 0) {
|
||||
std::shared_ptr<std::string> buf;
|
||||
for (const auto& s : targets) {
|
||||
if (s->acked_map_version() == snap.slam.map_version) continue;
|
||||
if (!buf) {
|
||||
buf = std::make_shared<std::string>();
|
||||
EncodeMapFull(*snap.map, snap.stamp, buf.get());
|
||||
}
|
||||
s->Send(buf, true, /*is_map=*/true);
|
||||
s->set_acked_map_version(snap.slam.map_version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
size_t WebServer::client_count() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->sessions_mu);
|
||||
return impl_->ws_sessions.size();
|
||||
}
|
||||
|
||||
uint16_t WebServer::port() const { return impl_->bound_port; }
|
||||
|
||||
WebServer::Stats WebServer::stats() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
||||
return impl_->stats;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user