#include #include #include #include #include namespace route_graph { bool loadBundleJson(const std::string& path, robot_sensor_msgs::RouteGraph* msg, std::string* err) { if (msg == nullptr) return false; auto fail = [&](const std::string& why) { if (err) *err = path + ": " + why; return false; }; std::ifstream in(path); if (!in) return fail("cannot open"); nlohmann::json j; try { in >> j; } catch (const std::exception& e) { return fail(std::string("parse error: ") + e.what()); } try { robot_sensor_msgs::RouteGraph out; out.version = j.at("version").get(); if (out.version != kSupportedVersion) return fail("bundle version " + std::to_string(out.version) + " unsupported"); out.source = j.value("source", std::string()); if (!hexToHash(j.at("map_hash").get(), &out.map_hash)) return fail("map_hash is not 16 hex digits"); const nlohmann::json& info = j.at("info"); out.width = info.at("width").get(); out.height = info.at("height").get(); out.resolution = info.at("resolution").get(); const nlohmann::json& origin = info.at("origin"); out.origin_x = origin.at(0).get(); out.origin_y = origin.at(1).get(); out.origin_yaw = origin.size() > 2 ? origin.at(2).get() : 0.0; if (out.width == 0 || out.height == 0) return fail("info.width/height is 0"); const int h = static_cast(out.height); auto flipY = [h](int y_img) { return h - 1 - y_img; }; const nlohmann::json& nodes = j.at("nodes"); out.node_x.reserve(nodes.size()); out.node_y.reserve(nodes.size()); for (const auto& nd : nodes) { out.node_x.push_back(nd.at(0).get()); out.node_y.push_back(flipY(nd.at(1).get())); } const nlohmann::json& edges = j.at("edges"); out.edge_u.reserve(edges.size()); out.edge_v.reserve(edges.size()); out.edge_length_cells.reserve(edges.size()); out.edge_min_clearance_cells.reserve(edges.size()); out.edge_cell_offset.reserve(edges.size() + 1); out.edge_cell_offset.push_back(0); for (const auto& e : edges) { out.edge_u.push_back(e.at("u").get()); out.edge_v.push_back(e.at("v").get()); out.edge_length_cells.push_back(e.at("length_cells").get()); out.edge_min_clearance_cells.push_back(e.at("min_clearance_cells").get()); const nlohmann::json& cells = e.at("cells"); for (const auto& c : cells) { out.cell_x.push_back(c.at(0).get()); out.cell_y.push_back(flipY(c.at(1).get())); } out.edge_cell_offset.push_back(static_cast(out.cell_x.size())); } // Validate the same way the consumer will, so a bad bundle is refused at the host with a // readable reason instead of being pushed and rejected inside the core. Graph check; std::string why; if (!check.fromMsg(out, &why)) return fail("invalid graph: " + why); *msg = std::move(out); return true; } catch (const std::exception& e) { return fail(std::string("bad field: ") + e.what()); } } } // namespace route_graph