luxb: navigation core for the luxb robot

Single-commit snapshot of the luxb branch (was 62 commits: new-1.0 up to
e948f32 plus 8470d73).

Compared with new-1.0 it drops the submodules this robot does not use
(mppi_local_planner, priest_local_planner, priest_mpcc_local_planner,
stanley_local_planner, trolley_detection_action,
wall_reflector_detection_action) and their config. The position profile
uses CustomPlanner + PNKXLocalPlanner; EnvMonitor and recovery are off.
This commit is contained in:
2026-11-18 09:54:28 +07:00
commit b676b14723
512 changed files with 84231 additions and 0 deletions

View File

@@ -0,0 +1,287 @@
using System;
using System.Runtime.InteropServices;
using NavigationExample;
namespace NavigationExample
{
/// <summary>
/// C# P/Invoke wrapper for Navigation C API
/// </summary>
public class NavigationAPI
{
private const string DllName = "/usr/local/lib/libnav_c_api.so"; // Linux
// For Windows: "nav_c_api.dll"
// For macOS: "libnav_c_api.dylib"
// ============================================================================
// Enums
// ============================================================================
public enum NavigationState
{
Pending = 0,
Active = 1,
Preempted = 2,
Succeeded = 3,
Aborted = 4,
Rejected = 5,
Preempting = 6,
Recalling = 7,
Recalled = 8,
Lost = 9,
Planning = 10,
Controlling = 11,
Clearing = 12,
Paused = 13
}
[StructLayout(LayoutKind.Sequential)]
public struct NavFeedback
{
public NavigationState navigation_state;
public IntPtr feed_back_str; // char*; free with nav_c_api_free_string
public Pose2D current_pose;
[MarshalAs(UnmanagedType.I1)]
public bool goal_checked;
[MarshalAs(UnmanagedType.I1)]
public bool is_ready;
}
/// <summary>Planner data output (plan, costmap, footprint).</summary>
[StructLayout(LayoutKind.Sequential)]
public struct PlannerDataOutput
{
public Path2D plan;
public OccupancyGrid costmap;
public OccupancyGridUpdate costmap_update;
[MarshalAs(UnmanagedType.I1)]
public bool is_costmap_updated;
public PolygonStamped footprint;
}
[StructLayout(LayoutKind.Sequential)]
public struct NavigationHandle
{
public IntPtr ptr;
}
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern Header header_create(string frame_id);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern Header header_set_data(
uint seq,
uint sec,
uint nsec,
string frame_id);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern Time time_create();
/// <summary>Free a string allocated by the API (strdup).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void nav_c_api_free_string(IntPtr str);
/// <summary>Convert NavigationState to string; caller must free with nav_c_api_free_string.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr navigation_state_to_string(NavigationState state);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_feedback(NavigationHandle handle, ref NavFeedback out_feedback);
/// <summary>Helper: copy unmanaged char* to managed string; does not free the pointer.</summary>
public static string MarshalString(IntPtr p)
{
if (p == IntPtr.Zero) return string.Empty;
return Marshal.PtrToStringAnsi(p) ?? string.Empty;
}
/// <summary>Free strings inside NavFeedback (feed_back_str). Call after navigation_get_feedback when done.</summary>
public static void navigation_free_feedback(ref NavFeedback feedback)
{
if (feedback.feed_back_str != IntPtr.Zero)
{
nav_c_api_free_string(feedback.feed_back_str);
feedback.feed_back_str = IntPtr.Zero;
}
}
// ============================================================================
// Navigation Handle Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern NavigationHandle navigation_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_destroy(NavigationHandle handle);
/// <summary>Initialize navigation using an existing tf3 buffer (from libtf3). Caller owns the buffer and must call tf3_buffer_destroy after navigation_destroy.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_initialize(NavigationHandle handle, IntPtr tf3_buffer);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_robot_footprint(NavigationHandle handle, Point[] points, UIntPtr point_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_footprint(NavigationHandle handle, ref Point[] out_points, ref UIntPtr out_count);
/// <summary>Send a goal for the robot to navigate to (global frame).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to(NavigationHandle handle, PoseStamped goal);
/// <summary>Navigate using an Order message (graph nodes/edges). Order must be built or obtained from native side; call order_free when done if it was allocated by native.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to_order(NavigationHandle handle, Order order, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to_nodes_edges(NavigationHandle handle, IntPtr nodes, UIntPtr node_count, IntPtr edges, UIntPtr edge_count, PoseStamped goal);
// navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
// navigation_move_straight_to and navigation_rotate_to no longer exist in the native
// library. They pushed a goal past the mission layer, so one of them arriving mid-route
// replaced the leg the mission queue was running without the queue noticing.
//
// Docking, go-straight and rotate are per-leg properties of an order now: set `profile:`
// on the leg (`docking | go_straight | rotate`) plus `marker` for docking, then send it
// through navigation_move_to_order or navigation_move_to_nodes_edges.
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_pause(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_resume(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_cancel(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_linear(NavigationHandle handle, double linear_x, double linear_y, double linear_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_angular(NavigationHandle handle, double angular_x, double angular_y, double angular_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_stamped(NavigationHandle handle, ref PoseStamped out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_2d(NavigationHandle handle, ref Pose2D out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_twist(NavigationHandle handle, ref Twist2DStamped out_twist);
// ============================================================================
// Navigation Data Management
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_laser_scan(NavigationHandle handle, string laser_scan_name, LaserScan laser_scan);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_odometry(NavigationHandle handle, string odometry_name, Odometry odometry);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_static_map(NavigationHandle handle, string map_name, OccupancyGrid occupancy_grid);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_static_map(NavigationHandle handle, string map_name, ref OccupancyGrid occupancy_grid);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_point_cloud(NavigationHandle handle, string point_cloud_name, PointCloud point_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_point_cloud2(NavigationHandle handle, string point_cloud2_name, PointCloud2 point_cloud2);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_laser_scan(NavigationHandle handle, string laser_scan_name, ref LaserScan out_scan);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_point_cloud(NavigationHandle handle, string point_cloud_name, ref PointCloud out_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_point_cloud2(NavigationHandle handle, string point_cloud2_name, ref PointCloud2 out_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_static_map(NavigationHandle handle, string map_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_laser_scan(NavigationHandle handle, string laser_scan_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_point_cloud(NavigationHandle handle, string point_cloud_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_point_cloud2(NavigationHandle handle, string point_cloud2_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_static_maps(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_laser_scans(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_point_clouds(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_point_cloud2s(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_data(NavigationHandle handle);
/// <summary>Get all static maps. out_maps must be pre-allocated; use navigation_get_all_static_maps_count or similar to get count first if needed.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_static_maps(NavigationHandle handle, [Out] NamedOccupancyGrid[] out_maps, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_laser_scans(NavigationHandle handle, [Out] NamedLaserScan[] out_scans, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_point_clouds(NavigationHandle handle, [Out] NamedPointCloud[] out_clouds, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_point_cloud2s(NavigationHandle handle, [Out] NamedPointCloud2[] out_clouds, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_global_data(NavigationHandle handle, ref PlannerDataOutput out_data);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_local_data(NavigationHandle handle, ref PlannerDataOutput out_data);
}
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</ItemGroup>
<ItemGroup>
<None Include="libnav_c_api.so">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,498 @@
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using NavigationExample;
namespace NavigationExample
{
/// <summary>Thông tin map đọc từ file YAML (maze.yaml).</summary>
public struct MazeMapConfig
{
public string ImagePath; // đường dẫn đầy đủ tới file ảnh
public float Resolution;
public double OriginX, OriginY, OriginZ;
public int Negate; // 0 hoặc 1
public double OccupiedThresh;
public double FreeThresh;
}
// ============================================================================
// Example Usage
// ============================================================================
class Program
{
/// <summary>
/// Đọc file maze.yaml (image, resolution, origin, negate, occupied_thresh, free_thresh).
/// ImagePath được resolve tuyệt đối theo thư mục chứa file yaml.
/// </summary>
static bool TryLoadMazeYaml(string yamlPath, out MazeMapConfig config)
{
config = default;
if (string.IsNullOrEmpty(yamlPath) || !File.Exists(yamlPath))
return false;
string dir = Path.GetDirectoryName(Path.GetFullPath(yamlPath)) ?? "";
try
{
string[] lines = File.ReadAllLines(yamlPath);
foreach (string line in lines)
{
string trimmed = line.Trim();
if (trimmed.Length == 0 || trimmed.StartsWith("#")) continue;
int colon = trimmed.IndexOf(':');
if (colon <= 0) continue;
string key = trimmed.Substring(0, colon).Trim();
string value = trimmed.Substring(colon + 1).Trim();
if (key == "image")
config.ImagePath = Path.Combine(dir, value);
else if (key == "resolution" && float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float res))
config.Resolution = res;
else if (key == "origin")
{
var m = Regex.Match(value, @"\[\s*([-\d.]+\s*),\s*([-\d.]+\s*),\s*([-\d.]+)\s*\]");
if (m.Success)
{
config.OriginX = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
config.OriginY = double.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
config.OriginZ = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
}
}
else if (key == "negate" && int.TryParse(value, out int neg))
config.Negate = neg;
else if (key == "occupied_thresh" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double ot))
config.OccupiedThresh = ot;
else if (key == "free_thresh" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double ft))
config.FreeThresh = ft;
}
return !string.IsNullOrEmpty(config.ImagePath);
}
catch
{
return false;
}
}
/// <summary>
/// Đọc file ảnh PNG và chuyển pixel sang byte[] occupancy (0=free, 100=occupied, 255=unknown).
/// Dùng negate, occupied_thresh, free_thresh từ maze.yaml nếu cung cấp.
/// </summary>
static byte[] LoadMazePixelsAsOccupancy(string imagePath, out int width, out int height,
int negate = 0, double occupiedThresh = 0.65, double freeThresh = 0.196)
{
width = 0;
height = 0;
if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
{
LogError($"File not found: {imagePath}");
return null;
}
try
{
using var image = Image.Load<Rgba32>(imagePath);
int w = image.Width;
int h = image.Height;
width = w;
height = h;
byte[] data = new byte[w * h];
image.ProcessPixelRows(accessor =>
{
for (int y = 0; y < accessor.Height; y++)
{
Span<Rgba32> row = accessor.GetRowSpan(y);
for (int x = 0; x < row.Length; x++)
{
ref readonly Rgba32 p = ref row[x];
double gray = (p.R + p.G + p.B) / 255.0 / 3.0;
if (negate != 0) gray = 1.0 - gray;
byte occ;
if (gray <= freeThresh) occ = 0;
else if (gray >= occupiedThresh) occ = 100;
else occ = 255; // unknown
data[y * w + x] = occ;
}
}
});
return data;
}
catch (Exception ex)
{
LogError($"Load image failed: {ex.Message}");
return null;
}
}
// Helper method để hiển thị file và line number tự động
static void LogError(string message,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "")
{
// Lấy tên file từ đường dẫn đầy đủ
string fileName = System.IO.Path.GetFileName(filePath);
Console.WriteLine($"[{fileName}:{lineNumber}] {memberName}: {message}");
}
static void Main(string[] args)
{
// Create tf3 buffer (replaces TF listener; used for all static transforms and navigation init)
IntPtr tf3Buffer = TF3API.tf3_buffer_create(10);
if (tf3Buffer == IntPtr.Zero)
{
LogError("Failed to create tf3 buffer (libtf3.so may be missing)");
return;
}
Console.WriteLine($"[NavigationExample] TF3 buffer created, handle = 0x{tf3Buffer.ToInt64():X16}");
string version = Marshal.PtrToStringAnsi(TF3API.tf3_get_version()) ?? "?";
Console.WriteLine($"[TF3] {version}");
// Inject static transforms: map -> odom -> base_footprint -> base_link
var tMapOdom = TF3API.CreateStaticTransform("map", "odom", 0, 0, 0, 0, 0, 0, 1);
var tOdomFoot = TF3API.CreateStaticTransform("odom", "base_footprint", 0, 0, 0, 0, 0, 0, 1);
var tFootLink = TF3API.CreateStaticTransform("base_footprint", "base_link", 0, 0, 0, 0, 0, 0, 1);
if (!TF3API.tf3_set_transform(tf3Buffer, ref tMapOdom, "NavigationExample", true) ||
!TF3API.tf3_set_transform(tf3Buffer, ref tOdomFoot, "NavigationExample", true) ||
!TF3API.tf3_set_transform(tf3Buffer, ref tFootLink, "NavigationExample", true))
{
LogError("Failed to set static TF");
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
// Create navigation instance and initialize with tf3 buffer
NavigationAPI.NavigationHandle navHandle = NavigationAPI.navigation_create();
if (navHandle.ptr == IntPtr.Zero)
{
LogError("Failed to create navigation instance");
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
if (!NavigationAPI.navigation_initialize(navHandle, tf3Buffer))
{
LogError("Failed to initialize navigation with tf3 buffer");
NavigationAPI.navigation_destroy(navHandle);
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
while (true)
{
NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
{
if (feedback.is_ready)
{
Console.WriteLine("Navigation is ready");
break;
}
else
{
Console.WriteLine("Navigation is not ready");
}
}
System.Threading.Thread.Sleep(100);
}
Console.WriteLine("[NavigationExample] Navigation initialized successfully");
// Set robot footprint
Point[] footprint = new Point[]
{
new Point { x = 0.3, y = -0.2, z = 0.0 },
new Point { x = 0.3, y = 0.2, z = 0.0 },
new Point { x = -0.3, y = 0.2, z = 0.0 },
new Point { x = -0.3, y = -0.2, z = 0.0 }
};
NavigationAPI.navigation_set_robot_footprint(navHandle, footprint, new UIntPtr((uint)footprint.Length));
IntPtr fFrameId = Marshal.StringToHGlobalAnsi("fscan");
Header fscanHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(fFrameId));
LaserScan fscanHandle;
fscanHandle.header = fscanHeader;
fscanHandle.angle_min = -1.57f;
fscanHandle.angle_max = 1.57f;
fscanHandle.angle_increment = 0.785f;
fscanHandle.time_increment = 0.0f;
fscanHandle.scan_time = 0.1f;
fscanHandle.range_min = 0.05f;
fscanHandle.range_max = 10.0f;
fscanHandle.ranges = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 1.0f, 1.2f, 1.1f, 0.9f, 1.3f }, 0, fscanHandle.ranges, 5);
fscanHandle.ranges_count = new UIntPtr(5);
fscanHandle.intensities = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 100.0f, 120.0f, 110.0f, 90.0f, 130.0f }, 0, fscanHandle.intensities, 5);
fscanHandle.intensities_count = new UIntPtr(5);
NavigationAPI.navigation_add_laser_scan(navHandle, "/fscan", fscanHandle);
IntPtr bFrameId = Marshal.StringToHGlobalAnsi("bscan");
Header bscanHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(bFrameId));
LaserScan bscanHandle;
bscanHandle.header = bscanHeader;
bscanHandle.angle_min = 1.57f;
bscanHandle.angle_max = -1.57f;
bscanHandle.angle_increment = -0.785f;
bscanHandle.time_increment = 0.0f;
bscanHandle.scan_time = 0.1f;
bscanHandle.range_min = 0.05f;
bscanHandle.range_max = 10.0f;
bscanHandle.ranges = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 1.0f, 1.2f, 1.1f, 0.9f, 1.3f }, 0, bscanHandle.ranges, 5);
bscanHandle.ranges_count = new UIntPtr(5);
bscanHandle.intensities = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 100.0f, 120.0f, 110.0f, 90.0f, 130.0f }, 0, bscanHandle.intensities, 5);
bscanHandle.intensities_count = new UIntPtr(5);
NavigationAPI.navigation_add_laser_scan(navHandle, "/bscan", bscanHandle);
IntPtr oFrameId = Marshal.StringToHGlobalAnsi("odom");
Header odometryHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(oFrameId));
Odometry odometryHandle = new Odometry();
odometryHandle.header = odometryHeader;
IntPtr childFrameId = Marshal.StringToHGlobalAnsi("base_footprint");
odometryHandle.child_frame_id = childFrameId;
odometryHandle.pose.pose.position.x = 0.0;
odometryHandle.pose.pose.position.y = 0.0;
odometryHandle.pose.pose.position.z = 0.0;
odometryHandle.pose.pose.orientation.x = 0.0;
odometryHandle.pose.pose.orientation.y = 0.0;
odometryHandle.pose.pose.orientation.z = 0.0;
odometryHandle.pose.pose.orientation.w = 1.0;
double[] pose_covariance = new double[36];
for(int i = 0; i < pose_covariance.Length; i++) {
pose_covariance[i] = 0.0;
}
odometryHandle.pose.covariance = Marshal.AllocHGlobal(sizeof(double) * pose_covariance.Length);
Marshal.Copy(pose_covariance, 0, odometryHandle.pose.covariance, pose_covariance.Length);
odometryHandle.pose.covariance_count = new UIntPtr((uint)pose_covariance.Length);
odometryHandle.twist.twist.linear.x = 0.0;
odometryHandle.twist.twist.linear.y = 0.0;
odometryHandle.twist.twist.linear.z = 0.0;
odometryHandle.twist.twist.angular.x = 0.0;
odometryHandle.twist.twist.angular.y = 0.0;
odometryHandle.twist.twist.angular.z = 0.0;
double[] twist_covariance = new double[36];
for(int i = 0; i < twist_covariance.Length; i++) {
twist_covariance[i] = 0.0;
}
odometryHandle.twist.covariance = Marshal.AllocHGlobal(sizeof(double) * twist_covariance.Length);
Marshal.Copy(twist_covariance, 0, odometryHandle.twist.covariance, twist_covariance.Length);
odometryHandle.twist.covariance_count = new UIntPtr((uint)twist_covariance.Length);
NavigationAPI.navigation_add_odometry(navHandle, "odometry", odometryHandle);
// Add static map: đọc maze.yaml rồi load ảnh và cập nhật mapMetaData
string mapYamlPath = "maze.yaml";
int mapWidth, mapHeight;
byte[] data;
MazeMapConfig mapConfig;
if (TryLoadMazeYaml(mapYamlPath, out mapConfig))
{
data = LoadMazePixelsAsOccupancy(mapConfig.ImagePath, out mapWidth, out mapHeight,
mapConfig.Negate, mapConfig.OccupiedThresh, mapConfig.FreeThresh);
if (data == null)
{
mapWidth = 3;
mapHeight = 10;
data = new byte[30];
for (int i = 0; i < data.Length; i++) data[i] = 100;
Console.WriteLine("YAML loaded but image failed; using default map 3x10");
}
else
{
Console.WriteLine("Loaded map from {0}: {1}x{2}, resolution={3}, origin=({4},{5},{6})",
mapConfig.ImagePath, mapWidth, mapHeight, mapConfig.Resolution,
mapConfig.OriginX, mapConfig.OriginY, mapConfig.OriginZ);
}
}
else
{
mapWidth = 3;
mapHeight = 10;
data = new byte[30];
for (int i = 0; i < data.Length; i++) data[i] = 100;
mapConfig = default;
mapConfig.Resolution = 0.05f;
mapConfig.OriginX = mapConfig.OriginY = mapConfig.OriginZ = 0.0;
Console.WriteLine("maze.yaml not found, using default map 3x10");
}
Time mapLoadTime = NavigationAPI.time_create();
MapMetaData mapMetaData = new MapMetaData();
mapMetaData.map_load_time = mapLoadTime;
mapMetaData.resolution = mapConfig.Resolution;
mapMetaData.width = (uint)mapWidth;
mapMetaData.height = (uint)mapHeight;
mapMetaData.origin = new Pose();
mapMetaData.origin.position.x = mapConfig.OriginX;
mapMetaData.origin.position.y = mapConfig.OriginY;
mapMetaData.origin.position.z = mapConfig.OriginZ;
mapMetaData.origin.orientation.x = 0.0;
mapMetaData.origin.orientation.y = 0.0;
mapMetaData.origin.orientation.z = 0.0;
mapMetaData.origin.orientation.w = 1.0;
OccupancyGrid occupancyGrid = new OccupancyGrid();
IntPtr mapFrameId = Marshal.StringToHGlobalAnsi("map");
occupancyGrid.header = NavigationAPI.header_create(Marshal.PtrToStringAnsi(mapFrameId));
occupancyGrid.info = mapMetaData;
occupancyGrid.data = Marshal.AllocHGlobal(sizeof(byte) * data.Length);
Marshal.Copy(data, 0, occupancyGrid.data, data.Length);
occupancyGrid.data_count = new UIntPtr((uint)data.Length);
Console.WriteLine("data length: {0} {1}", data.Length, occupancyGrid.data_count);
Console.WriteLine("C# OccupancyGrid sizeof={0} data_off={1} data_count_off={2}",
Marshal.SizeOf<OccupancyGrid>(),
Marshal.OffsetOf<OccupancyGrid>("data"),
Marshal.OffsetOf<OccupancyGrid>("data_count"));
NavigationAPI.navigation_add_static_map(navHandle, "/map", occupancyGrid);
Twist2DStamped twist = new Twist2DStamped();
if (NavigationAPI.navigation_get_twist(navHandle, ref twist))
{
Console.WriteLine(
"Twist: {0}, {1}, {2}, {3}",
NavigationAPI.MarshalString(twist.header.frame_id), twist.velocity.x, twist.velocity.y, twist.velocity.theta);
}
// Build order (thao cách bom order): header + nodes + edges giống C++
Order order = new Order();
order.headerId = 1;
order.timestamp = Marshal.StringToHGlobalAnsi("2026-02-28 10:00:00");
order.version = Marshal.StringToHGlobalAnsi("1.0.0");
order.manufacturer = Marshal.StringToHGlobalAnsi("Manufacturer");
order.serialNumber = Marshal.StringToHGlobalAnsi("Serial Number");
order.orderId = Marshal.StringToHGlobalAnsi("Order ID");
order.orderUpdateId = 1;
// Nodes: giống for (auto node : order.nodes) { node_msg.nodeId = ...; node_msg.nodePosition.x = ...; order_msg.nodes.push_back(node_msg); }
int nodeCount = 1;
order.nodes = Marshal.AllocHGlobal(Marshal.SizeOf<Node>() * nodeCount);
order.nodes_count = new UIntPtr((uint)nodeCount);
Node node1 = new Node();
node1.nodeId = Marshal.StringToHGlobalAnsi("node-1");
node1.sequenceId = 0;
node1.nodeDescription = Marshal.StringToHGlobalAnsi("Goal node");
node1.released = 0;
node1.nodePosition.x = 1.0;
node1.nodePosition.y = 1.0;
node1.nodePosition.theta = 0.0;
node1.nodePosition.allowedDeviationXY = 0.1f;
node1.nodePosition.allowedDeviationTheta = 0.05f;
node1.nodePosition.mapId = Marshal.StringToHGlobalAnsi("map");
node1.nodePosition.mapDescription = Marshal.StringToHGlobalAnsi("");
node1.actions = IntPtr.Zero;
node1.actions_count = UIntPtr.Zero;
Marshal.StructureToPtr(node1, order.nodes, false);
// Edges: rỗng trong ví dụ này; nếu cần thì alloc và fill tương tự (edge_msg.edgeId, trajectory.controlPoints, ...)
order.edges = IntPtr.Zero;
order.edges_count = UIntPtr.Zero;
order.zoneSetId = Marshal.StringToHGlobalAnsi("");
PoseStamped goal = new PoseStamped();
goal.header = NavigationAPI.header_create(Marshal.PtrToStringAnsi(mapFrameId));
goal.pose.position.x = 0.01;
goal.pose.position.y = 0.01;
goal.pose.position.z = 0.0;
goal.pose.orientation.x = 0.0;
goal.pose.orientation.y = 0.0;
goal.pose.orientation.z = 0.0;
goal.pose.orientation.w = 1.0;
// Docking used to be its own call, navigation_dock_to(navHandle, "charger", goal).
// It is a per-leg property of the order now: put `profile: docking` and `marker:
// charger` on the leg and send the order, so the leg gets the same mission id,
// lifecycle and cancel path as every other leg.
NavigationAPI.navigation_move_to(navHandle, goal);
// NavigationAPI.navigation_move_to_nodes_edges(navHandle, order.nodes, order.nodes_count, order.edges, order.edges_count, goal);
// NavigationAPI.navigation_move_to_order(navHandle, order, goal);
NavigationAPI.navigation_set_twist_linear(navHandle, 0.1, 0.0, 0.0);
NavigationAPI.navigation_set_twist_angular(navHandle, 0.0, 0.0, 0.2);
while (true)
{
System.Threading.Thread.Sleep(100);
// NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
// if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
// {
// if (feedback.navigation_state == NavigationAPI.NavigationState.Succeeded)
// {
// Console.WriteLine("Navigation is Succeeded");
// break;
// }
// }
// NavigationAPI.PlannerDataOutput globalData = new NavigationAPI.PlannerDataOutput();
// if (NavigationAPI.navigation_get_global_data(navHandle, ref globalData))
// {
// int n = (int)(uint)globalData.plan.poses_count;
// int poseSize = Marshal.SizeOf<Pose2DStamped>();
// for (int i = 0; i < n; i++)
// {
// IntPtr posePtr = IntPtr.Add(globalData.plan.poses, i * poseSize);
// Pose2DStamped p = Marshal.PtrToStructure<Pose2DStamped>(posePtr);
// double p_x = p.pose.x;
// double p_y = p.pose.y;
// double p_theta = p.pose.theta;
// Console.WriteLine("Plan: {0}, {1}, {2}", p_x, p_y, p_theta);
// }
// if(globalData.is_costmap_updated) {
// for(int i = 0; i < (int)(uint)globalData.costmap.data_count; i++) {
// byte cellValue = Marshal.ReadByte(globalData.costmap.data, i);
// Console.WriteLine("Costmap: {0} {1}", i, cellValue);
// }
// }
// else {
// Console.WriteLine("Global Costmap is not updated");
// }
// }
// NavigationAPI.PlannerDataOutput localData = new NavigationAPI.PlannerDataOutput();
// if(NavigationAPI.navigation_get_local_data(navHandle, ref localData))
// {
// int n = (int)(uint)localData.plan.poses_count;
// int poseSize = Marshal.SizeOf<Pose2DStamped>();
// for (int i = 0; i < n; i++)
// {
// IntPtr posePtr = IntPtr.Add(localData.plan.poses, i * poseSize);
// Pose2DStamped p = Marshal.PtrToStructure<Pose2DStamped>(posePtr);
// double p_x = p.pose.x;
// double p_y = p.pose.y;
// double p_theta = p.pose.theta;
// Console.WriteLine("Plan: {0}, {1}, {2}", p_x, p_y, p_theta);
// }
// if(localData.is_costmap_updated) {
// for(int i = 0; i < (int)(uint)localData.costmap.data_count; i++) {
// byte cellValue = Marshal.ReadByte(localData.costmap.data, i);
// Console.WriteLine("Costmap: {0} {1}", i, cellValue);
// }
// }
// else {
// Console.WriteLine("Local Costmap is not updated");
// }
// }
}
// Cleanup (destroy nav first, then tf3 buffer)
NavigationAPI.navigation_destroy(navHandle);
TF3API.tf3_buffer_destroy(tf3Buffer);
Console.WriteLine("Press any key to exit...");
try
{
Console.ReadKey(intercept: true);
}
catch (InvalidOperationException)
{
// Running without a real console (e.g. redirected/automated run).
}
}
}
}

View File

@@ -0,0 +1,133 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
// ============================================================================
// TF3 C API - P/Invoke wrapper for libtf3 (tf3 BufferCore)
// ============================================================================
public static class TF3API
{
private const string Tf3DllName = "/usr/local/lib/libtf3.so"; // Linux; Windows: tf3.dll, macOS: libtf3.dylib
public enum TF3_ErrorCode
{
TF3_OK = 0,
TF3_ERROR_LOOKUP = 1,
TF3_ERROR_CONNECTIVITY = 2,
TF3_ERROR_EXTRAPOLATION = 3,
TF3_ERROR_INVALID_ARGUMENT = 4,
TF3_ERROR_TIMEOUT = 5,
TF3_ERROR_UNKNOWN = 99
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TF3_Transform
{
public long timestamp_sec;
public long timestamp_nsec;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string frame_id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string child_frame_id;
public double translation_x;
public double translation_y;
public double translation_z;
public double rotation_x;
public double rotation_y;
public double rotation_z;
public double rotation_w;
}
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf3_buffer_create(int cache_time_sec);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_buffer_destroy(IntPtr buffer);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_set_transform(
IntPtr buffer,
ref TF3_Transform transform,
string authority,
[MarshalAs(UnmanagedType.I1)] bool is_static);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_lookup_transform(
IntPtr buffer,
string target_frame,
string source_frame,
long time_sec,
long time_nsec,
out TF3_Transform transform,
out TF3_ErrorCode error_code);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_lookup_transform_full(
IntPtr buffer,
string target_frame,
long target_time_sec,
long target_time_nsec,
string source_frame,
long source_time_sec,
long source_time_nsec,
string fixed_frame,
out TF3_Transform transform,
out TF3_ErrorCode error_code);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_can_transform(
IntPtr buffer,
string target_frame,
string source_frame,
long time_sec,
long time_nsec,
System.Text.StringBuilder error_msg,
int error_msg_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int tf3_get_all_frame_names(IntPtr buffer, System.Text.StringBuilder frames, int frames_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_get_frame_tree(IntPtr buffer, System.Text.StringBuilder output, int output_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_clear(IntPtr buffer);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_get_current_time(out long sec, out long nsec);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_get_last_error(IntPtr buffer, System.Text.StringBuilder error_msg, int error_msg_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf3_get_version();
/// <summary>Helper: create TF3_Transform for static transform (identity or given pose).</summary>
public static TF3_Transform CreateStaticTransform(string parentFrame, string childFrame,
double tx = 0, double ty = 0, double tz = 0,
double qx = 0, double qy = 0, double qz = 0, double qw = 1)
{
var t = new TF3_Transform();
t.timestamp_sec = 0;
t.timestamp_nsec = 0;
t.frame_id = parentFrame ?? "";
t.child_frame_id = childFrame ?? "";
t.translation_x = tx;
t.translation_y = ty;
t.translation_z = tz;
t.rotation_x = qx;
t.rotation_y = qy;
t.rotation_z = qz;
t.rotation_w = qw;
return t;
}
}
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,6 @@
image: maze.png
resolution: 0.05
origin: [0.0, 0.0, 0.0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196

View File

@@ -0,0 +1,274 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
// ============================================================================
// Structures
// ============================================================================
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion
{
public double x;
public double y;
public double z;
public double w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Position
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose
{
public Point position;
public Quaternion orientation;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist
{
public Vector3 linear;
public Vector3 angular;
}
[StructLayout(LayoutKind.Sequential)]
public struct Header
{
public uint seq;
public uint sec;
public uint nsec;
public IntPtr frame_id; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseStamped
{
public Header header;
public Pose pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist2DStamped
{
public Header header;
public Twist2D velocity;
}
[StructLayout(LayoutKind.Sequential)]
public struct LaserScan
{
public Header header;
public float angle_min;
public float angle_max;
public float angle_increment;
public float time_increment;
public float scan_time;
public float range_min;
public float range_max;
public IntPtr ranges;
public UIntPtr ranges_count;
public IntPtr intensities;
public UIntPtr intensities_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PointCloud
{
public Header header;
public IntPtr points;
public UIntPtr points_count;
public IntPtr channels;
public UIntPtr channels_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PointCloud2
{
public Header header;
public uint height;
public uint width;
public IntPtr fields;
public UIntPtr fields_count;
[MarshalAs(UnmanagedType.I1)]
public bool is_bigendian;
public uint point_step;
public uint row_step;
public IntPtr data;
public UIntPtr data_count;
[MarshalAs(UnmanagedType.I1)]
public bool is_dense;
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseWithCovariance
{
public Pose pose;
public IntPtr covariance;
public UIntPtr covariance_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct TwistWithCovariance {
public Twist twist;
public IntPtr covariance;
public UIntPtr covariance_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Odometry
{
public Header header;
public IntPtr child_frame_id;
public PoseWithCovariance pose;
public TwistWithCovariance twist;
}
[StructLayout(LayoutKind.Sequential)]
public struct OccupancyGrid
{
public Header header;
public MapMetaData info;
public IntPtr data;
public UIntPtr data_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct MapMetaData
{
public Time map_load_time;
public float resolution;
public uint width;
public uint height;
public Pose origin;
}
[StructLayout(LayoutKind.Sequential)]
public struct Time
{
public uint sec;
public uint nsec;
}
[StructLayout(LayoutKind.Sequential)]
public struct Point32
{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2DStamped
{
public Header header;
public Pose2D pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Polygon
{
public IntPtr points;
public UIntPtr points_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PolygonStamped
{
public Header header;
public Polygon polygon;
}
[StructLayout(LayoutKind.Sequential)]
public struct OccupancyGridUpdate
{
public Header header;
public int x;
public int y;
public uint width;
public uint height;
public IntPtr data;
public UIntPtr data_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Path2D
{
public Header header;
public IntPtr poses;
public UIntPtr poses_count;
}
/// <summary>Name (char*) + OccupancyGrid for static map list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedOccupancyGrid
{
public IntPtr name;
public OccupancyGrid grid;
}
/// <summary>Name (char*) + LaserScan for laser scan list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedLaserScan
{
public IntPtr name;
public LaserScan scan;
}
/// <summary>Name (char*) + PointCloud for point cloud list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedPointCloud
{
public IntPtr name;
public PointCloud cloud;
}
/// <summary>Name (char*) + PointCloud2 for point cloud2 list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedPointCloud2
{
public IntPtr name;
public PointCloud2 cloud;
}
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
/// <summary>
/// C# struct layout cho protocol_msgs (robot_protocol_msgs C API).
/// Khớp với pnkx_nav_core/src/APIs/c_api/include/protocol_msgs/*.h
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ControlPoint
{
public double x;
public double y;
public double weight;
}
[StructLayout(LayoutKind.Sequential)]
public struct ActionParameter
{
public IntPtr key; // char*
public IntPtr value; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct NodePosition
{
public double x;
public double y;
public double theta;
public float allowedDeviationXY;
public float allowedDeviationTheta;
public IntPtr mapId; // char*
public IntPtr mapDescription; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct Trajectory
{
public uint degree;
public IntPtr knotVector; // double*
public UIntPtr knotVector_count;
public IntPtr controlPoints; // ControlPoint*
public UIntPtr controlPoints_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Action
{
public IntPtr actionType; // char*
public IntPtr actionId; // char*
public IntPtr actionDescription;// char*
public IntPtr blockingType; // char*
public IntPtr actionParameters; // ActionParameter*
public UIntPtr actionParameters_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Node
{
public IntPtr nodeId; // char*
public int sequenceId;
public IntPtr nodeDescription; // char*
public byte released;
public NodePosition nodePosition;
public IntPtr actions; // Action*
public UIntPtr actions_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Edge
{
public IntPtr edgeId; // char*
public int sequenceId;
public IntPtr edgeDescription; // char*
public byte released;
public IntPtr startNodeId; // char*
public IntPtr endNodeId; // char*
public double maxSpeed;
public double maxHeight;
public double minHeight;
public double orientation;
public IntPtr orientationType; // char*
public IntPtr direction; // char*
public byte rotationAllowed;
public double maxRotationSpeed;
public Trajectory trajectory;
public double length;
public IntPtr actions; // Action*
public UIntPtr actions_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Order
{
public int headerId;
public IntPtr timestamp; // char*
public IntPtr version; // char*
public IntPtr manufacturer; // char*
public IntPtr serialNumber; // char*
public IntPtr orderId; // char*
public uint orderUpdateId;
public IntPtr nodes; // Node*
public UIntPtr nodes_count;
public IntPtr edges; // Edge*
public UIntPtr edges_count;
public IntPtr zoneSetId; // char*
}
}

148
examples/QUICK_START.md Normal file
View File

@@ -0,0 +1,148 @@
# Quick Start - Chạy C# Example
## Bước 1: Cài đặt .NET SDK (nếu chưa có)
### Ubuntu/Debian:
```bash
# Cài đặt .NET 6.0 hoặc mới hơn
wget https://dot.net/v1/dotnet-install.sh
chmod +x dotnet-install.sh
./dotnet-install.sh --channel 6.0
# Thêm vào PATH
export PATH=$PATH:$HOME/.dotnet
export DOTNET_ROOT=$HOME/.dotnet
# Hoặc cài qua apt (nếu có)
sudo apt-get update
sudo apt-get install -y dotnet-sdk-6.0
```
### Kiểm tra:
```bash
dotnet --version
```
## Bước 2: Build C API Library
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core
mkdir -p build
cd build
cmake ..
make nav_c_api
```
Library sẽ ở: `build/src/APIs/c_api/libnav_c_api.so`
## Bước 3: Chạy C# Example
### Cách 1: Dùng script tự động (Khuyến nghị)
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
chmod +x run_example.sh
./run_example.sh
```
Script sẽ tự động:
- ✅ Build library nếu chưa có
- ✅ Tạo C# project
- ✅ Copy library và source code
- ✅ Set LD_LIBRARY_PATH cho tất cả dependencies
- ✅ Build và chạy example
### Cách 2: Chạy thủ công
```bash
# 1. Tạo project
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
dotnet new console -n NavigationExample
cd NavigationExample
# 2. Copy source code
cp ../CSharpExample.cs Program.cs
# 3. Tạo .csproj
cat > NavigationExample.csproj << 'EOF'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<None Include="libnav_c_api.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
EOF
# 4. Copy library
cp ../../build/src/APIs/c_api/libnav_c_api.so .
# 5. Set library path (quan trọng!)
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_time:$LD_LIBRARY_PATH
# 6. Build và chạy
dotnet build
dotnet run
```
## Bước 4: Kiểm tra kết quả
Nếu chạy thành công, bạn sẽ thấy output như:
```
Robot pose: x=0.0, y=0.0, theta=0.0
State: PENDING, Feedback: ...
```
## Troubleshooting
### Lỗi: "dotnet: command not found"
→ Cài đặt .NET SDK (xem Bước 1)
### Lỗi: "Unable to load DLL 'libnav_c_api.so'"
```bash
# Kiểm tra library có tồn tại không
ls -la ../../build/src/APIs/c_api/libnav_c_api.so
# Set LD_LIBRARY_PATH (bao gồm tất cả dependencies)
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_time:$LD_LIBRARY_PATH
# Hoặc copy vào system lib
sudo cp libnav_c_api.so /usr/local/lib/
sudo ldconfig
```
### Lỗi: "Missing dependencies"
```bash
# Kiểm tra dependencies
ldd libnav_c_api.so
# Đảm bảo tất cả dependencies đều có sẵn
```
### Lỗi: "Failed to create navigation instance"
→ Đã được sửa! `navigation_create()` bây giờ tạo instance của `move_base::MoveBase`.
Nếu vẫn gặp lỗi, kiểm tra:
- Library đã được build đầy đủ: `make nav_c_api` trong build directory
- Dependencies đã được build: `make move_base robot_costmap_2d`
- LD_LIBRARY_PATH đã được set đúng

142
examples/README.md Normal file
View File

@@ -0,0 +1,142 @@
# Hướng dẫn chạy C# Example
## Yêu cầu
1. **.NET SDK** (version 6.0 trở lên hoặc .NET 10)
2. **C API Library** đã được build (`libnav_c_api.so`)
3. **Linux environment** (hoặc WSL nếu dùng Windows)
## Bước 1: Build C API Library
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core
mkdir -p build
cd build
cmake ..
make nav_c_api
```
Library sẽ được tạo tại: `build/src/APIs/c_api/libnav_c_api.so`
## Bước 2: Chạy script tự động (Khuyến nghị)
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
chmod +x run_example.sh
./run_example.sh
```
Script sẽ tự động:
- Build library nếu chưa có
- Tạo C# project
- Copy library và source code
- Set LD_LIBRARY_PATH cho tất cả dependencies
- Build và chạy example
## Bước 3: Hoặc chạy thủ công
### Tạo C# Project
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
dotnet new console -n NavigationExample
cd NavigationExample
```
### Copy file và library
```bash
# Copy C# source code
cp ../CSharpExample.cs Program.cs
# Copy library vào thư mục project
cp ../../build/src/APIs/c_api/libnav_c_api.so .
```
## Bước 4: Cập nhật .csproj (nếu cần)
Tạo file `NavigationExample.csproj`:
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<None Include="libnav_c_api.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
```
## Bước 4: Build và chạy
```bash
# Set LD_LIBRARY_PATH để tìm được tất cả dependencies
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_time:$LD_LIBRARY_PATH
# Build
dotnet build
# Chạy
dotnet run
```
## Lưu ý
1. **Library path**: Đảm bảo `libnav_c_api.so` có thể được tìm thấy:
- Copy vào cùng thư mục với executable
- Hoặc set `LD_LIBRARY_PATH` environment variable
- Hoặc copy vào `/usr/local/lib` và chạy `ldconfig`
2. **Dependencies**: Library cần các dependencies khác:
```bash
# Kiểm tra dependencies
ldd libnav_c_api.so
# Đảm bảo tất cả dependencies đều có sẵn
```
3. **Permissions**: Đảm bảo file có quyền execute:
```bash
chmod +x libnav_c_api.so
```
## Troubleshooting
### Lỗi: "Unable to load DLL 'libnav_c_api.so'"
**Giải pháp:**
```bash
# Set LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/build/src/APIs/c_api:$LD_LIBRARY_PATH
# Hoặc copy library vào system path
sudo cp libnav_c_api.so /usr/local/lib/
sudo ldconfig
```
### Lỗi: "DllNotFoundException"
**Giải pháp:**
- Kiểm tra tên file library có đúng không
- Kiểm tra architecture (x64 vs x86)
- Kiểm tra dependencies: `ldd libnav_c_api.so`
### Lỗi: "Symbol not found"
**Giải pháp:**
- Đảm bảo library đã được build đầy đủ
- Kiểm tra tên hàm trong C# có khớp với C API không

83
examples/START_HERE.md Normal file
View File

@@ -0,0 +1,83 @@
# 🚀 Hướng dẫn chạy thử C API Navigation
## Cách nhanh nhất (1 lệnh)
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
chmod +x run_example.sh
./run_example.sh
```
## Chi tiết các bước
### Bước 1: Build C API Library
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/build
cmake ..
make nav_c_api
```
Library sẽ được tạo tại: `build/src/APIs/c_api/libnav_c_api.so`
### Bước 2: Chạy C# Example
Script `run_example.sh` sẽ tự động:
- ✅ Kiểm tra và build library nếu cần
- ✅ Tạo C# project
- ✅ Copy library và source code
- ✅ Set LD_LIBRARY_PATH cho tất cả dependencies
- ✅ Build và chạy example
```bash
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_nav_core/examples
./run_example.sh
```
## Kết quả mong đợi
Nếu chạy thành công, bạn sẽ thấy:
```
==========================================
Building and Running C# Navigation Example
==========================================
Library already exists: .../build/src/APIs/c_api/libnav_c_api.so
C# project already exists
Copying library...
Building C# project...
Running example...
==========================================
Robot pose: x=0, y=0, theta=0
State: PENDING, Feedback:
==========================================
Done!
```
## Yêu cầu
1. **.NET SDK 6.0+** (script sẽ kiểm tra và hướng dẫn nếu thiếu)
2. **Library đã được build** (script sẽ tự động build nếu thiếu)
3. **Linux environment**
## Troubleshooting
### Lỗi: "dotnet: command not found"
→ Script sẽ hiển thị hướng dẫn cài đặt .NET SDK
### Lỗi: "Failed to create navigation instance"
→ Đảm bảo `move_base` đã được build:
```bash
cd build && make move_base
```
### Lỗi: "Cannot load library"
→ Kiểm tra LD_LIBRARY_PATH đã được set đúng (script tự động set)
## Xem thêm
- `README.md` - Hướng dẫn chi tiết
- `QUICK_START.md` - Quick start guide
- `run_example.sh` - Script tự động

1887
examples/dotnet-install.sh vendored Executable file

File diff suppressed because it is too large Load Diff

123
examples/run_example.sh Executable file
View File

@@ -0,0 +1,123 @@
#!/bin/bash
# Script để build và chạy C# example
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
BUILD_DIR="$PROJECT_ROOT/build"
LIB_DIR="$BUILD_DIR"
EXAMPLE_DIR="$SCRIPT_DIR"
echo "=========================================="
echo "Building and Running C# Navigation Example"
echo "=========================================="
echo ""
echo "📁 Paths:"
echo " SCRIPT_DIR: $SCRIPT_DIR"
echo " PROJECT_ROOT: $PROJECT_ROOT"
echo " BUILD_DIR: $BUILD_DIR"
echo " LIB_DIR: $LIB_DIR"
echo " EXAMPLE_DIR: $EXAMPLE_DIR"
echo ""
echo "Building C API library..."
cd "$BUILD_DIR"
cmake ..
make
sudo make install
echo "Library built successfully!"
# Kiểm tra dotnet có được cài đặt không
if ! command -v dotnet &> /dev/null; then
echo "=========================================="
echo "WARNING: .NET SDK not found!"
echo "=========================================="
echo "To run the C# example, please install .NET SDK:"
echo ""
echo " Ubuntu/Debian:"
echo " wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh"
echo " chmod +x dotnet-install.sh"
echo " ./dotnet-install.sh --channel 6.0"
echo " export PATH=\$PATH:\$HOME/.dotnet"
echo ""
echo " Or visit: https://dotnet.microsoft.com/download"
echo ""
echo "Skipping C# example. Library is available at:"
echo " $LIB_DIR/libnav_c_api.so"
echo "=========================================="
exit 0
fi
# Bước 2: Tạo C# project nếu chưa có
if [ ! -d "$EXAMPLE_DIR/NavigationExample" ]; then
echo "Creating C# project..."
cd "$EXAMPLE_DIR"
dotnet new console -n NavigationExample
cd NavigationExample
# Tạo .csproj file
cat > NavigationExample.csproj << 'EOF'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<None Include="libnav_c_api.so">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
EOF
echo "C# project created!"
else
echo "C# project already exists"
fi
# Luôn copy source code mới nhất (cập nhật file nếu đã có)
cd "$EXAMPLE_DIR/NavigationExample"
# # Bước 3: Copy library
# echo "Copying library..."
# cp "$LIB_DIR/libnav_c_api.so" .
# Bước 4: Set LD_LIBRARY_PATH để tìm được tất cả dependencies
# Main build directory (contains libtf3.so, librobot_cpp.so, etc.)
export LD_LIBRARY_PATH="$BUILD_DIR:$LD_LIBRARY_PATH"
# Library directories for dependencies
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/robot_time:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/xmlrpcpp:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH"
# Also add the example directory where the library is copied
export LD_LIBRARY_PATH="$EXAMPLE_DIR/NavigationExample:$LD_LIBRARY_PATH"
# Add the output directory where .NET places the library
export LD_LIBRARY_PATH="$EXAMPLE_DIR/NavigationExample/bin/Debug/net6.0/linux-x64:$LD_LIBRARY_PATH"
# Bước 5: Build và chạy
echo "Building C# project..."
dotnet build
echo ""
echo "Running example..."
echo "=========================================="
echo "LD_LIBRARY_PATH includes:"
echo "$LD_LIBRARY_PATH" | tr ':' '\n' | head -5
echo "..."
echo "=========================================="
dotnet run
echo "=========================================="
echo "Done!"