upload
This commit is contained in:
330
libs/vslam_web/src/binary_codec.cc
Normal file
330
libs/vslam_web/src/binary_codec.cc
Normal file
@@ -0,0 +1,330 @@
|
||||
#include "vslam/binary_codec.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
#include "vslam/rle.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
void PutU8(std::string* out, uint8_t v) { out->push_back(static_cast<char>(v)); }
|
||||
|
||||
void PutU16(std::string* out, uint16_t v) {
|
||||
out->push_back(static_cast<char>(v & 0xFF));
|
||||
out->push_back(static_cast<char>((v >> 8) & 0xFF));
|
||||
}
|
||||
|
||||
void PutU32(std::string* out, uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
void PutI32(std::string* out, int32_t v) { PutU32(out, static_cast<uint32_t>(v)); }
|
||||
|
||||
void PutU64(std::string* out, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) out->push_back(static_cast<char>((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
void PutF32(std::string* out, float v) {
|
||||
uint32_t bits;
|
||||
std::memcpy(&bits, &v, 4);
|
||||
PutU32(out, bits);
|
||||
}
|
||||
|
||||
void PutI16(std::string* out, int16_t v) { PutU16(out, static_cast<uint16_t>(v)); }
|
||||
|
||||
uint16_t GetU16(const std::string& b, size_t o) {
|
||||
return static_cast<uint16_t>(static_cast<uint8_t>(b[o])) |
|
||||
(static_cast<uint16_t>(static_cast<uint8_t>(b[o + 1])) << 8);
|
||||
}
|
||||
|
||||
uint32_t GetU32(const std::string& b, size_t o) {
|
||||
uint32_t v = 0;
|
||||
for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
|
||||
uint64_t GetU64(const std::string& b, size_t o) {
|
||||
uint64_t v = 0;
|
||||
for (int i = 0; i < 8; ++i) v |= static_cast<uint64_t>(static_cast<uint8_t>(b[o + i])) << (8 * i);
|
||||
return v;
|
||||
}
|
||||
|
||||
float GetF32(const std::string& b, size_t o) {
|
||||
const uint32_t bits = GetU32(b, o);
|
||||
float f;
|
||||
std::memcpy(&f, &bits, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
int32_t GetI32(const std::string& b, size_t o) {
|
||||
return static_cast<int32_t>(GetU32(b, o));
|
||||
}
|
||||
|
||||
void PutHeader(std::string* out, BinaryType type, UnixTime stamp, uint16_t flags = 0) {
|
||||
out->append("VSL1", 4);
|
||||
PutU8(out, static_cast<uint8_t>(type));
|
||||
PutU8(out, kBinaryVersion);
|
||||
PutU16(out, flags);
|
||||
PutU64(out, static_cast<uint64_t>(stamp.toNSec()));
|
||||
}
|
||||
|
||||
// Ba ngu nghia cua mot tia -> ba gia tri canh bien. Xem vslam_common.h.
|
||||
uint16_t RangeToMm(float r, float range_max) {
|
||||
if (std::isnan(r)) return kRangeNaN;
|
||||
if (std::isinf(r)) return kRangeInf;
|
||||
// Sentinel "bi che boi than robot" la range_max + 1.0, dat boi sector mask
|
||||
// cua ScanSanitizer. Phai phan biet duoc voi inf: inf nghia la "nhin duoc
|
||||
// nhung khong co gi", sentinel nghia la "khong duoc phep nhin".
|
||||
if (r > range_max + 0.5f) return kRangeBlanked;
|
||||
if (r < 0.0f) return kRangeNaN;
|
||||
|
||||
const float mm = r * 1000.0f;
|
||||
if (mm >= static_cast<float>(kRangeMaxValid)) return kRangeMaxValid;
|
||||
return static_cast<uint16_t>(mm + 0.5f);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void EncodeScan(const LaserScan& scan, UnixTime stamp, std::string* out) {
|
||||
PutHeader(out, BinaryType::kScan, stamp);
|
||||
PutF32(out, scan.angle_min);
|
||||
PutF32(out, scan.angle_increment);
|
||||
PutF32(out, scan.range_min);
|
||||
PutF32(out, scan.range_max);
|
||||
PutU32(out, static_cast<uint32_t>(scan.ranges.size()));
|
||||
for (const float r : scan.ranges) {
|
||||
PutU16(out, RangeToMm(r, scan.range_max));
|
||||
}
|
||||
}
|
||||
|
||||
void EncodeCloud(const PointCloudXYZ& cloud, UnixTime stamp, uint32_t max_points,
|
||||
float quant_m, std::string* out) {
|
||||
if (quant_m <= 0.0f) quant_m = 0.01f;
|
||||
|
||||
// Lay buoc deu thay vi cat duoi: cat duoi lam mat ca mot vung khong gian,
|
||||
// buoc deu giu duoc hinh dang tong the.
|
||||
const size_t n_in = cloud.points.size();
|
||||
const size_t stride =
|
||||
(max_points > 0 && n_in > max_points) ? (n_in + max_points - 1) / max_points : 1;
|
||||
|
||||
// Dem truoc so diem hop le de khong phai sua lai truong n sau khi ghi.
|
||||
uint32_t n_out = 0;
|
||||
for (size_t i = 0; i < n_in; i += stride) {
|
||||
const PointXYZ& p = cloud.points[i];
|
||||
if (std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z)) ++n_out;
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kCloud, stamp);
|
||||
// Goc = (0,0,0): cloud da o frame base_footprint sau gravity_align.
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, 0.0f);
|
||||
PutF32(out, quant_m);
|
||||
PutU32(out, n_out);
|
||||
|
||||
const float inv = 1.0f / quant_m;
|
||||
constexpr float kLim = 32767.0f;
|
||||
for (size_t i = 0; i < n_in; i += stride) {
|
||||
const PointXYZ& p = cloud.points[i];
|
||||
if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) continue;
|
||||
// Kep vao dai i16. Voi quant 0.01 m thi dai la +-327 m -- khong bao gio
|
||||
// cham toi trong nha, nhung kep van re hon la de tran am tham.
|
||||
const float qx = std::max(-kLim, std::min(kLim, p.x * inv));
|
||||
const float qy = std::max(-kLim, std::min(kLim, p.y * inv));
|
||||
const float qz = std::max(-kLim, std::min(kLim, p.z * inv));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qx)));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qy)));
|
||||
PutI16(out, static_cast<int16_t>(std::lround(qz)));
|
||||
}
|
||||
}
|
||||
|
||||
void EncodeMapFull(const OccupancyGrid& map, UnixTime stamp, std::string* out,
|
||||
BinaryType type) {
|
||||
PutHeader(out, type, stamp);
|
||||
PutF32(out, map.resolution);
|
||||
PutI32(out, static_cast<int32_t>(map.width));
|
||||
PutI32(out, static_cast<int32_t>(map.height));
|
||||
PutF32(out, static_cast<float>(map.origin.position.x));
|
||||
PutF32(out, static_cast<float>(map.origin.position.y));
|
||||
// Goc quay cua ban do: RTAB-Map luon tra ban do truc giao nen thuong la 0,
|
||||
// nhung giu truong nay de khong phai doi dinh dang neu sau co xoay.
|
||||
PutF32(out, 0.0f);
|
||||
|
||||
// Ghi truoc so run = 0 roi vá lai sau khi ma hoa: khong phai ma hoa hai lan.
|
||||
const size_t run_count_off = out->size();
|
||||
PutU32(out, 0);
|
||||
|
||||
const size_t runs = RleEncode(map.data, out);
|
||||
|
||||
const uint32_t r32 = static_cast<uint32_t>(runs);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
(*out)[run_count_off + static_cast<size_t>(i)] =
|
||||
static_cast<char>((r32 >> (8 * i)) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
bool EncodeMapPatch(const OccupancyGrid& map, const OccupancyGrid& prev,
|
||||
UnixTime stamp, std::string* out) {
|
||||
// Kich thuoc doi -> khong vá duoc, phai gui full.
|
||||
if (map.width != prev.width || map.height != prev.height ||
|
||||
map.data.size() != prev.data.size() ||
|
||||
std::abs(map.resolution - prev.resolution) > 1e-6f ||
|
||||
std::abs(map.origin.position.x - prev.origin.position.x) > 1e-6 ||
|
||||
std::abs(map.origin.position.y - prev.origin.position.y) > 1e-6) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Vung bao cac o doi.
|
||||
int32_t x0 = static_cast<int32_t>(map.width);
|
||||
int32_t y0 = static_cast<int32_t>(map.height);
|
||||
int32_t x1 = -1, y1 = -1;
|
||||
|
||||
for (uint32_t y = 0; y < map.height; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (uint32_t x = 0; x < map.width; ++x) {
|
||||
if (map.data[row + x] == prev.data[row + x]) continue;
|
||||
const int32_t xi = static_cast<int32_t>(x);
|
||||
const int32_t yi = static_cast<int32_t>(y);
|
||||
if (xi < x0) x0 = xi;
|
||||
if (yi < y0) y0 = yi;
|
||||
if (xi > x1) x1 = xi;
|
||||
if (yi > y1) y1 = yi;
|
||||
}
|
||||
}
|
||||
|
||||
if (x1 < 0) return false; // khong o nao doi
|
||||
|
||||
const int32_t w = x1 - x0 + 1;
|
||||
const int32_t h = y1 - y0 + 1;
|
||||
|
||||
std::vector<int8_t> patch;
|
||||
patch.reserve(static_cast<size_t>(w) * static_cast<size_t>(h));
|
||||
for (int32_t y = y0; y <= y1; ++y) {
|
||||
const size_t row = static_cast<size_t>(y) * map.width;
|
||||
for (int32_t x = x0; x <= x1; ++x) {
|
||||
patch.push_back(map.data[row + static_cast<size_t>(x)]);
|
||||
}
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kMapPatch, stamp);
|
||||
PutI32(out, x0);
|
||||
PutI32(out, y0);
|
||||
PutI32(out, w);
|
||||
PutI32(out, h);
|
||||
|
||||
const size_t run_count_off = out->size();
|
||||
PutU32(out, 0);
|
||||
const size_t runs = RleEncode(patch, out);
|
||||
const uint32_t r32 = static_cast<uint32_t>(runs);
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
(*out)[run_count_off + static_cast<size_t>(i)] =
|
||||
static_cast<char>((r32 >> (8 * i)) & 0xFF);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void EncodePath(const std::vector<Pose2D>& path, UnixTime stamp, double min_step_m,
|
||||
std::string* out) {
|
||||
std::vector<const Pose2D*> kept;
|
||||
kept.reserve(path.size());
|
||||
|
||||
const double min_sq = min_step_m * min_step_m;
|
||||
const Pose2D* last = nullptr;
|
||||
for (const auto& p : path) {
|
||||
if (last != nullptr) {
|
||||
const double dx = p.x - last->x, dy = p.y - last->y;
|
||||
if (dx * dx + dy * dy < min_sq) continue;
|
||||
}
|
||||
kept.push_back(&p);
|
||||
last = &p;
|
||||
}
|
||||
// Luon giu diem cuoi: do la vi tri hien tai, mat no thi duong di trong nhu
|
||||
// dang tut hau.
|
||||
if (!path.empty() && (kept.empty() || kept.back() != &path.back())) {
|
||||
kept.push_back(&path.back());
|
||||
}
|
||||
|
||||
PutHeader(out, BinaryType::kPath, stamp);
|
||||
PutU32(out, static_cast<uint32_t>(kept.size()));
|
||||
for (const Pose2D* p : kept) {
|
||||
PutF32(out, static_cast<float>(p->x));
|
||||
PutF32(out, static_cast<float>(p->y));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Giai ma (test) --------------------------------------------------------
|
||||
|
||||
bool DecodeHeader(const std::string& buf, size_t offset, BinaryHeader* out) {
|
||||
if (buf.size() < offset + kBinaryHeaderSize) return false;
|
||||
if (std::memcmp(buf.data() + offset, "VSL1", 4) != 0) return false;
|
||||
out->type = static_cast<BinaryType>(static_cast<uint8_t>(buf[offset + 4]));
|
||||
out->version = static_cast<uint8_t>(buf[offset + 5]);
|
||||
out->flags = GetU16(buf, offset + 6);
|
||||
out->stamp_ns = GetU64(buf, offset + 8);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DecodeScan(const std::string& buf, LaserScan* out) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kScan) return false;
|
||||
|
||||
size_t o = kBinaryHeaderSize;
|
||||
if (buf.size() < o + 20) return false;
|
||||
|
||||
out->angle_min = GetF32(buf, o); o += 4;
|
||||
out->angle_increment = GetF32(buf, o); o += 4;
|
||||
out->range_min = GetF32(buf, o); o += 4;
|
||||
out->range_max = GetF32(buf, o); o += 4;
|
||||
const uint32_t n = GetU32(buf, o); o += 4;
|
||||
|
||||
if (buf.size() < o + static_cast<size_t>(n) * 2) return false;
|
||||
|
||||
out->ranges.clear();
|
||||
out->ranges.reserve(n);
|
||||
for (uint32_t i = 0; i < n; ++i) {
|
||||
const uint16_t v = GetU16(buf, o + static_cast<size_t>(i) * 2);
|
||||
switch (v) {
|
||||
case kRangeNaN:
|
||||
out->ranges.push_back(std::numeric_limits<float>::quiet_NaN());
|
||||
break;
|
||||
case kRangeInf:
|
||||
out->ranges.push_back(std::numeric_limits<float>::infinity());
|
||||
break;
|
||||
case kRangeBlanked:
|
||||
out->ranges.push_back(out->range_max + 1.0f);
|
||||
break;
|
||||
default:
|
||||
out->ranges.push_back(static_cast<float>(v) * 0.001f);
|
||||
break;
|
||||
}
|
||||
}
|
||||
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DecodeMapFull(const std::string& buf, OccupancyGrid* out) {
|
||||
BinaryHeader h;
|
||||
if (!DecodeHeader(buf, 0, &h) || h.type != BinaryType::kMapFull) return false;
|
||||
|
||||
size_t o = kBinaryHeaderSize;
|
||||
if (buf.size() < o + 28) return false;
|
||||
|
||||
out->resolution = GetF32(buf, o); o += 4;
|
||||
out->width = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
|
||||
out->height = static_cast<uint32_t>(GetI32(buf, o)); o += 4;
|
||||
out->origin.position.x = GetF32(buf, o); o += 4;
|
||||
out->origin.position.y = GetF32(buf, o); o += 4;
|
||||
o += 4; // oyaw
|
||||
const uint32_t runs = GetU32(buf, o); o += 4;
|
||||
|
||||
const size_t expected = static_cast<size_t>(out->width) * out->height;
|
||||
if (!RleDecode(buf, o, runs, expected, &out->data)) return false;
|
||||
|
||||
out->header.stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
213
libs/vslam_web/src/json_writer.cc
Normal file
213
libs/vslam_web/src/json_writer.cc
Normal file
@@ -0,0 +1,213 @@
|
||||
#include "json_writer.h"
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
void Key(const char* k, std::string* out) {
|
||||
out->push_back('"');
|
||||
out->append(k);
|
||||
out->append("\":");
|
||||
}
|
||||
|
||||
void Comma(std::string* out) { out->push_back(','); }
|
||||
|
||||
void Str(const char* k, const std::string& v, std::string* out) {
|
||||
Key(k, out);
|
||||
out->push_back('"');
|
||||
JsonEscape(v, out);
|
||||
out->push_back('"');
|
||||
}
|
||||
|
||||
void Num(const char* k, double v, int dec, std::string* out) {
|
||||
Key(k, out);
|
||||
JsonNumber(v, dec, out);
|
||||
}
|
||||
|
||||
void Int(const char* k, long long v, std::string* out) {
|
||||
Key(k, out);
|
||||
char buf[24];
|
||||
std::snprintf(buf, sizeof(buf), "%lld", v);
|
||||
out->append(buf);
|
||||
}
|
||||
|
||||
void Bool(const char* k, bool v, std::string* out) {
|
||||
Key(k, out);
|
||||
out->append(v ? "true" : "false");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void JsonEscape(const std::string& in, std::string* out) {
|
||||
for (const char c : in) {
|
||||
switch (c) {
|
||||
case '"': out->append("\\\""); break;
|
||||
case '\\': out->append("\\\\"); break;
|
||||
case '\n': out->append("\\n"); break;
|
||||
case '\r': out->append("\\r"); break;
|
||||
case '\t': out->append("\\t"); break;
|
||||
default:
|
||||
if (static_cast<unsigned char>(c) < 0x20) {
|
||||
char buf[8];
|
||||
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
|
||||
out->append(buf);
|
||||
} else {
|
||||
out->push_back(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void JsonNumber(double v, int decimals, std::string* out) {
|
||||
// JSON khong co NaN/Infinity. De nguyen thi JSON.parse() nem loi va browser
|
||||
// mat CA khung chu khong chi mot truong -- mot min_front = inf (hop le, co
|
||||
// nghia "khong thay gi") se lam ca bang trang thai bien mat.
|
||||
if (!std::isfinite(v)) {
|
||||
out->append("null");
|
||||
return;
|
||||
}
|
||||
char buf[40];
|
||||
std::snprintf(buf, sizeof(buf), "%.*f", decimals, v);
|
||||
out->append(buf);
|
||||
}
|
||||
|
||||
void WriteStateJson(const WebSnapshot& s, std::string* out) {
|
||||
out->append("{\"t\":\"state\",");
|
||||
Num("stamp", s.stamp.toSec(), 3, out); Comma(out);
|
||||
|
||||
// Hinh hoc robot -- trinh duyet KHONG duoc tu doan kich thuoc.
|
||||
//
|
||||
// Chi xuat khi `valid`: mot trinh ve nhan so 0 se dung ban kinh 0 va ve ra
|
||||
// mot cham, con nhan KHONG GI thi biet la chua co du lieu va bao ro.
|
||||
if (s.robot.valid) {
|
||||
Key("robot", out);
|
||||
out->push_back('{');
|
||||
Num("radius", s.robot.radius, 4, out); Comma(out);
|
||||
Num("wheel_radius", s.robot.wheel_radius, 4, out); Comma(out);
|
||||
Num("wheel_sep", s.robot.wheel_separation, 4, out); Comma(out);
|
||||
Num("half_width", s.robot.body_half_width, 4, out); Comma(out);
|
||||
Num("laser_x", s.robot.laser_x, 4, out); Comma(out);
|
||||
Num("laser_y", s.robot.laser_y, 4, out); Comma(out);
|
||||
Num("laser_z", s.robot.laser_z, 4, out); Comma(out);
|
||||
Num("cam_x", s.robot.camera_x, 4, out); Comma(out);
|
||||
Num("cam_y", s.robot.camera_y, 4, out); Comma(out);
|
||||
Num("cam_z", s.robot.camera_z, 4, out); Comma(out);
|
||||
Num("cam_pitch", s.robot.camera_pitch, 4, out); Comma(out);
|
||||
Num("cam_hfov", s.robot.camera_hfov, 4, out); Comma(out);
|
||||
Num("cam_vfov", s.robot.camera_vfov, 4, out); Comma(out);
|
||||
Num("cliff_min", s.robot.cliff_min, 3, out); Comma(out);
|
||||
Num("cliff_max", s.robot.cliff_max, 3, out);
|
||||
out->push_back('}');
|
||||
Comma(out);
|
||||
}
|
||||
|
||||
Key("pose", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.pose_map.x, 3, out); Comma(out);
|
||||
Num("y", s.pose_map.y, 3, out); Comma(out);
|
||||
Num("yaw", s.pose_map.theta, 4, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
// Ground truth chi xuat khi CO. Xuat 0 khi khong co la noi doi: client
|
||||
// khong phan biet duoc "dung o goc" voi "khong biet".
|
||||
if (s.have_ground_truth) {
|
||||
Key("gt", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.ground_truth.x, 3, out); Comma(out);
|
||||
Num("y", s.ground_truth.y, 3, out); Comma(out);
|
||||
Num("yaw", s.ground_truth.theta, 4, out); Comma(out);
|
||||
Num("roll", s.gt_roll, 4, out); Comma(out);
|
||||
Num("pitch", s.gt_pitch, 4, out); Comma(out);
|
||||
// Sai so vi tri cua uoc luong so voi su that. Tinh o day thay vi de
|
||||
// client tu tru: neu sau nay map va gt khac goc toa do thi phep tru
|
||||
// ngay tren client se sai am tham.
|
||||
Num("err", Distance2D(s.pose_map, s.ground_truth), 4, out);
|
||||
out->push_back('}');
|
||||
Comma(out);
|
||||
}
|
||||
|
||||
Key("odom", out);
|
||||
out->push_back('{');
|
||||
Num("x", s.pose_odom.x, 3, out); Comma(out);
|
||||
Num("y", s.pose_odom.y, 3, out); Comma(out);
|
||||
Num("yaw", s.pose_odom.theta, 4, out); Comma(out);
|
||||
Num("vx", s.vx, 3, out); Comma(out);
|
||||
Num("vyaw", s.vyaw, 3, out); Comma(out);
|
||||
Num("slip", s.slip_metric, 3, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("tilt", out);
|
||||
out->push_back('{');
|
||||
Num("roll", s.roll, 4, out); Comma(out);
|
||||
Num("pitch", s.pitch, 4, out); Comma(out);
|
||||
Bool("accel_ok", s.accel_ok, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("safety", out);
|
||||
out->push_back('{');
|
||||
Str("state", s.safety.state, out); Comma(out);
|
||||
Str("detail", s.safety.detail, out); Comma(out);
|
||||
Num("min_front", s.safety.min_front, 3, out); Comma(out);
|
||||
Int("front_rays", s.safety.front_rays, out); Comma(out);
|
||||
Int("front_blanked", s.safety.front_blanked, out); Comma(out);
|
||||
Int("front_usable", s.safety.front_usable, out); Comma(out);
|
||||
Bool("estop", s.safety.estop, out); Comma(out);
|
||||
Bool("bumper_latched", s.safety.bumper_latched, out); Comma(out);
|
||||
Bool("cliff", s.safety.cliff, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("slam", out);
|
||||
out->push_back('{');
|
||||
Str("mode", s.slam.mode, out); Comma(out);
|
||||
Bool("localized", s.slam.localized, out); Comma(out);
|
||||
Num("score", s.slam.score, 3, out); Comma(out);
|
||||
Int("loop_id", s.slam.loop_closure_id, out); Comma(out);
|
||||
Int("map_version", s.slam.map_version, out); Comma(out);
|
||||
Num("process_ms", s.slam.process_ms, 1, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("teleop", out);
|
||||
out->push_back('{');
|
||||
Num("linear_speed", s.teleop.linear_speed, 3, out); Comma(out);
|
||||
Num("angular_speed", s.teleop.angular_speed, 3, out); Comma(out);
|
||||
Num("max_linear_speed", s.teleop.max_linear_speed, 3, out); Comma(out);
|
||||
Num("max_angular_speed", s.teleop.max_angular_speed, 3, out);
|
||||
out->push_back('}'); Comma(out);
|
||||
|
||||
Key("health", out);
|
||||
out->push_back('{');
|
||||
Num("lidar_hz", s.health.lidar_hz, 1, out); Comma(out);
|
||||
Num("camera_hz", s.health.camera_hz, 1, out); Comma(out);
|
||||
Num("imu_hz", s.health.imu_hz, 1, out); Comma(out);
|
||||
Num("ekf_hz", s.health.ekf_hz, 1, out); Comma(out);
|
||||
Num("clock_skew", s.health.clock_skew, 7, out); Comma(out);
|
||||
Num("cpu_pct", s.health.cpu_pct, 1, out); Comma(out);
|
||||
Num("rss_mb", s.health.rss_mb, 0, out); Comma(out);
|
||||
|
||||
Key("drops", out);
|
||||
out->push_back('{');
|
||||
bool first = true;
|
||||
for (const auto& kv : s.health.drops) {
|
||||
if (!first) Comma(out);
|
||||
first = false;
|
||||
Int(kv.first.c_str(), static_cast<long long>(kv.second), out);
|
||||
}
|
||||
out->push_back('}');
|
||||
out->push_back('}');
|
||||
|
||||
out->push_back('}');
|
||||
}
|
||||
|
||||
void WriteStatusJson(const StatusResponse& st, std::string* out) {
|
||||
out->push_back('{');
|
||||
Int("code", static_cast<long long>(st.code), out);
|
||||
Comma(out);
|
||||
Str("message", st.message, out);
|
||||
out->push_back('}');
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
36
libs/vslam_web/src/json_writer.h
Normal file
36
libs/vslam_web/src/json_writer.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef VSLAM_JSON_WRITER_H_
|
||||
#define VSLAM_JSON_WRITER_H_
|
||||
|
||||
// Sinh JSON bang cach noi chuoi. Header NOI BO, khong phat hanh.
|
||||
//
|
||||
// Vi sao khong dung nlohmann/json: no khong co san tren may nao trong hai may
|
||||
// (dev focal lan Jetson jammy), va schema o day co dinh va nho -- mot
|
||||
// serializer ~150 dong khong phai danh doi gi dang ke.
|
||||
//
|
||||
// Chi ho tro chieu GHI. Doc JSON (body cua POST /api/*) lam bang json_parse.h,
|
||||
// cung mot ly do.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/web_snapshot.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Escape theo RFC 8259: ", \, va cac ky tu dieu khien < 0x20.
|
||||
void JsonEscape(const std::string& in, std::string* out);
|
||||
|
||||
// Ghi so thuc voi so chu so co dinh. Tra "null" neu NaN hoac inf -- JSON
|
||||
// khong co hai gia tri do, va de nguyen thi JSON.parse() cua browser nem loi
|
||||
// lam mat CA khung, khong chi mot truong.
|
||||
void JsonNumber(double v, int decimals, std::string* out);
|
||||
|
||||
// Toan bo khung trang thai, khop schema mo ta trong ke hoach.
|
||||
void WriteStateJson(const WebSnapshot& snap, std::string* out);
|
||||
|
||||
// Tra loi cho POST /api/*.
|
||||
void WriteStatusJson(const StatusResponse& st, std::string* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_JSON_WRITER_H_
|
||||
85
libs/vslam_web/src/rle.cc
Normal file
85
libs/vslam_web/src/rle.cc
Normal file
@@ -0,0 +1,85 @@
|
||||
#include "vslam/rle.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr uint16_t kMaxRun = 65535;
|
||||
|
||||
void PutU16(std::string* out, uint16_t v) {
|
||||
out->push_back(static_cast<char>(v & 0xFF));
|
||||
out->push_back(static_cast<char>((v >> 8) & 0xFF));
|
||||
}
|
||||
|
||||
uint16_t GetU16(const std::string& buf, size_t off) {
|
||||
return static_cast<uint16_t>(static_cast<uint8_t>(buf[off])) |
|
||||
(static_cast<uint16_t>(static_cast<uint8_t>(buf[off + 1])) << 8);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
size_t RleEncode(const std::vector<int8_t>& data, std::string* out) {
|
||||
if (data.empty()) return 0;
|
||||
|
||||
size_t runs = 0;
|
||||
int8_t value = data[0];
|
||||
uint32_t len = 1;
|
||||
|
||||
for (size_t i = 1; i < data.size(); ++i) {
|
||||
if (data[i] == value && len < kMaxRun) {
|
||||
++len;
|
||||
continue;
|
||||
}
|
||||
PutU16(out, static_cast<uint16_t>(len));
|
||||
out->push_back(static_cast<char>(value));
|
||||
++runs;
|
||||
value = data[i];
|
||||
len = 1;
|
||||
}
|
||||
|
||||
PutU16(out, static_cast<uint16_t>(len));
|
||||
out->push_back(static_cast<char>(value));
|
||||
++runs;
|
||||
return runs;
|
||||
}
|
||||
|
||||
size_t RleEncodedSize(const std::vector<int8_t>& data) {
|
||||
if (data.empty()) return 0;
|
||||
|
||||
size_t runs = 1;
|
||||
int8_t value = data[0];
|
||||
uint32_t len = 1;
|
||||
|
||||
for (size_t i = 1; i < data.size(); ++i) {
|
||||
if (data[i] == value && len < kMaxRun) {
|
||||
++len;
|
||||
continue;
|
||||
}
|
||||
++runs;
|
||||
value = data[i];
|
||||
len = 1;
|
||||
}
|
||||
return runs * 3;
|
||||
}
|
||||
|
||||
bool RleDecode(const std::string& buf, size_t offset, size_t run_count,
|
||||
size_t expected_size, std::vector<int8_t>* out) {
|
||||
if (offset + run_count * 3 > buf.size()) return false;
|
||||
|
||||
out->clear();
|
||||
out->reserve(expected_size);
|
||||
|
||||
for (size_t r = 0; r < run_count; ++r) {
|
||||
const size_t off = offset + r * 3;
|
||||
const uint16_t len = GetU16(buf, off);
|
||||
const int8_t value = static_cast<int8_t>(buf[off + 2]);
|
||||
// Chan phinh bo nho neu du lieu hong: khong reserve theo len chua kiem.
|
||||
if (out->size() + len > expected_size) return false;
|
||||
out->insert(out->end(), len, value);
|
||||
}
|
||||
|
||||
return out->size() == expected_size;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
29
libs/vslam_web/src/web_assets.h
Normal file
29
libs/vslam_web/src/web_assets.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef VSLAM_WEB_ASSETS_H_
|
||||
#define VSLAM_WEB_ASSETS_H_
|
||||
|
||||
// Asset tinh (html/js/css) nhung trong .so luc build boi vslam_embed_assets()
|
||||
// trong cmake/vslam_helpers.cmake.
|
||||
//
|
||||
// Vi sao nhung chu khong doc tu dia: Jetson ngoai hien truong phai phuc vu
|
||||
// duoc UI ke ca khi /var/lib chua duoc .deb dien, va lech phien ban giua .so
|
||||
// voi UI la chi phi ho tro co that.
|
||||
//
|
||||
// Cua hau: WebConfig::asset_dir khac rong thi doc tu dia (che do dev).
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct EmbeddedAsset {
|
||||
const unsigned char* data;
|
||||
std::size_t size;
|
||||
};
|
||||
|
||||
// Dinh nghia nam trong web_assets_generated.cc do CMake sinh.
|
||||
const std::map<std::string, EmbeddedAsset>& EmbeddedAssets();
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WEB_ASSETS_H_
|
||||
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