# amcl_nav2_params.yaml — Complete Nav2 + AMCL parameter file (Issue #655)
#
# AMCL localises on a pre-built static map using /scan (RPLIDAR A1M8).
# Odometry source: /odom from vesc_can_odometry (VESC CAN IDs 61/79, Issue #646).
#
# Launch with:
#   ros2 launch saltybot_nav2_slam nav2_amcl_bringup.launch.py
#   ros2 launch saltybot_nav2_slam nav2_amcl_bringup.launch.py \
#       map:=/mnt/nvme/saltybot/maps/my_map.yaml
#
# Costmaps (inline — required by nav2_bringup navigation_launch.py):
#   global: static_layer + obstacle_layer (LiDAR) + inflation_layer
#   local:  obstacle_layer (LiDAR) + inflation_layer, 4m rolling window

# ── AMCL ─────────────────────────────────────────────────────────────────────
amcl:
  ros__parameters:
    use_sim_time: false

    # Particle filter bounds
    min_particles:   500
    max_particles:   3000

    # Motion model noise (alpha1–5: low = trust odometry more)
    # Tuned for VESC differential drive (Issue #646): encoder slip ~5%
    alpha1: 0.10   # rot noise from rot
    alpha2: 0.10   # rot noise from trans
    alpha3: 0.05   # trans noise from trans
    alpha4: 0.05   # trans noise from rot
    alpha5: 0.10   # (omni only)

    # Sensor model — likelihood field
    laser_model_type:        "likelihood_field"
    laser_likelihood_max_dist: 2.0
    max_beams:               60
    sigma_hit:               0.2
    z_hit:                   0.50   # beam hit weight
    z_rand:                  0.45   # random noise weight
    z_max:                   0.025  # max-range weight  (z_hit+z_rand+z_max+z_short = 1.0)
    z_short:                 0.025  # short-read weight
    sigma_short:             0.05
    do_beamskip:             false
    beam_search_increment:   0.1

    # Frame IDs
    global_frame_id:  "map"
    odom_frame_id:    "odom"
    base_frame_id:    "base_link"

    # Update triggers
    update_min_d:  0.20   # m — update after moving this far
    update_min_a:  0.15   # rad — update after rotating this much
    resample_interval: 1

    # Particle filter convergence
    pf_err: 0.05
    pf_z:   0.99

    # Transform
    tf_broadcast:       true
    transform_tolerance: 0.5    # s — relaxed for slower Nav2 loop
    save_pose_rate:     0.5     # Hz — save last pose for fast re-init

    # Recovery particle injection (0 = disabled)
    recovery_alpha_fast: 0.0
    recovery_alpha_slow: 0.0

    # Robot model
    robot_model_type: "nav2_amcl::DifferentialMotionModel"

    # Scan topic
    scan_topic: /scan

# ── Map Server ────────────────────────────────────────────────────────────────
map_server:
  ros__parameters:
    use_sim_time: false
    yaml_filename: ""   # overridden by launch argument --map

# ── BT Navigator ─────────────────────────────────────────────────────────────
bt_navigator:
  ros__parameters:
    use_sim_time: false
    global_frame:      map
    robot_base_frame:  base_link
    odom_topic:        /odom
    enable_groot_monitoring: false
    default_nav_to_pose_bt_xml: >-
      $(find-pkg-share nav2_bt_navigator)/behavior_trees/navigate_to_pose_w_replanning_and_recovery.xml
    default_nav_through_poses_bt_xml: >-
      $(find-pkg-share nav2_bt_navigator)/behavior_trees/navigate_through_poses_w_replanning_and_recovery.xml
    plugin_lib_names:
      - nav2_compute_path_to_pose_action_bt_node
      - nav2_compute_path_through_poses_action_bt_node
      - nav2_follow_path_action_bt_node
      - nav2_spin_action_bt_node
      - nav2_wait_action_bt_node
      - nav2_back_up_action_bt_node
      - nav2_drive_on_heading_bt_node
      - nav2_clear_costmap_service_bt_node
      - nav2_is_stuck_condition_bt_node
      - nav2_goal_updated_condition_bt_node
      - nav2_initial_pose_received_condition_bt_node
      - nav2_reinitialize_global_localization_service_bt_node
      - nav2_rate_controller_bt_node
      - nav2_distance_controller_bt_node
      - nav2_speed_controller_bt_node
      - nav2_truncate_path_action_bt_node
      - nav2_remove_passed_goals_action_bt_node
      - nav2_goal_checker_selector_bt_node
      - nav2_controller_selector_bt_node
      - nav2_planner_selector_bt_node

# ── Controller Server (DWB local planner) ─────────────────────────────────────
controller_server:
  ros__parameters:
    use_sim_time: false
    controller_frequency: 20.0
    min_x_velocity_threshold: 0.001
    min_y_velocity_threshold: 0.5
    min_theta_velocity_threshold: 0.001
    failure_tolerance: 0.3
    progress_checker_plugin: "progress_checker"
    goal_checker_plugins:    ["general_goal_checker"]
    controller_plugins:      ["FollowPath"]

    progress_checker:
      plugin: "nav2_controller::SimpleProgressChecker"
      required_movement_radius: 0.3
      movement_time_allowance: 15.0

    general_goal_checker:
      stateful: true
      plugin: "nav2_controller::SimpleGoalChecker"
      xy_goal_tolerance:  0.20
      yaw_goal_tolerance: 0.20

    # DWB — tuned for VESC differential drive on Saltybot
    FollowPath:
      plugin:                       "dwb_core::DWBLocalPlanner"
      debug_trajectory_details:     false
      min_vel_x:                    0.0
      min_vel_y:                    0.0
      max_vel_x:                    1.0    # m/s — conservative indoor nav
      max_vel_y:                    0.0    # diff drive: no lateral
      max_vel_theta:                1.5    # rad/s
      min_speed_xy:                 0.0
      max_speed_xy:                 1.0
      min_speed_theta:              0.0
      acc_lim_x:                    2.0
      acc_lim_y:                    0.0
      acc_lim_theta:                2.0
      decel_lim_x:                 -2.0
      decel_lim_theta:             -2.0
      vx_samples:                   20
      vy_samples:                   1      # diff drive: no lateral
      vtheta_samples:               40
      sim_time:                     1.7
      linear_granularity:           0.05
      angular_granularity:          0.025
      transform_tolerance:          0.2
      trans_stopped_velocity:       0.25
      short_circuit_trajectory_evaluation: true
      stateful:                     true
      critics: ["RotateToGoal", "Oscillation", "BaseObstacle", "GoalAlign",
                "PathAlign", "PathDist", "GoalDist"]
      BaseObstacle.scale:   0.02
      PathAlign.scale:      32.0
      PathAlign.forward_point_distance: 0.1
      GoalAlign.scale:      24.0
      GoalAlign.forward_point_distance: 0.1
      PathDist.scale:       32.0
      GoalDist.scale:       24.0
      RotateToGoal.scale:   32.0
      RotateToGoal.slowing_factor: 5.0
      RotateToGoal.lookahead_time: -1.0

# ── Planner Server (NavFn A*) ─────────────────────────────────────────────────
planner_server:
  ros__parameters:
    use_sim_time: false
    expected_planner_frequency: 20.0
    planner_plugins: ["GridBased"]
    GridBased:
      plugin:        "nav2_navfn_planner/NavfnPlanner"
      tolerance:     0.5
      use_astar:     true
      allow_unknown: true

# ── Behavior Server (recovery behaviors) ──────────────────────────────────────
behavior_server:
  ros__parameters:
    use_sim_time:      false
    costmap_topic:     local_costmap/costmap_raw
    footprint_topic:   local_costmap/published_footprint
    cycle_frequency:   10.0
    global_frame:      odom
    robot_base_frame:  base_link
    transform_timeout: 0.1
    simulate_ahead_time: 2.0
    behavior_plugins: ["spin", "backup", "wait"]
    spin:
      plugin:           "nav2_behaviors/Spin"
    backup:
      plugin:           "nav2_behaviors/BackUp"
    wait:
      plugin:           "nav2_behaviors/Wait"
    # Spin recovery
    max_rotations:       2.0    # full rotations before giving up
    # Backup recovery
    max_backup_dist:     0.30   # m
    backup_speed:        0.15   # m/s — slow for a balancing robot

# ── Global Costmap ────────────────────────────────────────────────────────────
# Uses /scan (RPLIDAR) for obstacle detection.
# Layers: static (from /map) + obstacle (LiDAR) + inflation.
global_costmap:
  global_costmap:
    ros__parameters:
      use_sim_time:        false
      global_frame:        map
      robot_base_frame:    base_link
      update_frequency:    5.0    # Hz
      publish_frequency:   2.0    # Hz
      rolling_window:      false
      resolution:          0.05   # m/cell
      robot_radius:        0.35   # m — inscribed circle
      track_unknown_space: true
      unknown_cost_value:  -1
      lethal_cost_threshold: 100
      plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
      static_layer:
        plugin:                     "nav2_costmap_2d::StaticLayer"
        map_subscribe_transient_local: true
        enabled:                    true
      obstacle_layer:
        plugin:           "nav2_costmap_2d::ObstacleLayer"
        enabled:          true
        observation_sources: scan
        scan:
          topic:                /scan
          data_type:            "LaserScan"
          max_obstacle_height:  2.0
          min_obstacle_height:  0.0
          obstacle_max_range:   9.5
          obstacle_min_range:   0.0
          raytrace_max_range:   10.0
          raytrace_min_range:   0.0
          clearing:             true
          marking:              true
      inflation_layer:
        plugin:               "nav2_costmap_2d::InflationLayer"
        enabled:              true
        inflation_radius:     0.55   # m — clears obstacles wider than robot
        cost_scaling_factor:  10.0
        inflate_unknown:      false
        inflate_around_unknown: true

# ── Local Costmap ─────────────────────────────────────────────────────────────
# Rolling 4m window in odom frame.  LiDAR obstacle layer + inflation.
local_costmap:
  local_costmap:
    ros__parameters:
      use_sim_time:        false
      global_frame:        odom
      robot_base_frame:    base_link
      update_frequency:    10.0   # Hz
      publish_frequency:   5.0    # Hz
      rolling_window:      true
      width:               4      # m
      height:              4      # m
      resolution:          0.05   # m/cell
      robot_radius:        0.35
      track_unknown_space: true
      unknown_cost_value:  0      # treat unknown as free locally
      lethal_cost_threshold: 100
      plugins: ["obstacle_layer", "inflation_layer"]
      obstacle_layer:
        plugin:           "nav2_costmap_2d::ObstacleLayer"
        enabled:          true
        observation_sources: scan
        scan:
          topic:                /scan
          data_type:            "LaserScan"
          max_obstacle_height:  2.0
          min_obstacle_height:  0.0
          obstacle_max_range:   5.0
          obstacle_min_range:   0.0
          raytrace_max_range:   6.0
          raytrace_min_range:   0.0
          clearing:             true
          marking:              true
          observation_persistence: 0.0
          expected_update_rate: 5.5   # RPLIDAR A1M8 scan rate
      inflation_layer:
        plugin:               "nav2_costmap_2d::InflationLayer"
        enabled:              true
        inflation_radius:     0.55
        cost_scaling_factor:  10.0
        inflate_unknown:      false
        inflate_around_unknown: false

# ── Velocity Smoother ─────────────────────────────────────────────────────────
velocity_smoother:
  ros__parameters:
    use_sim_time:        false
    smoothing_frequency: 20.0
    scale_velocities:    false
    feedback:            "OPEN_LOOP"
    max_velocity:        [1.0, 0.0, 1.5]
    min_velocity:       [-1.0, 0.0, -1.5]
    max_accel:           [2.0, 0.0, 2.0]
    max_decel:          [-2.0, 0.0, -2.0]
    odom_topic:          "odom"
    odom_duration:       0.1
    deadband_velocity:   [0.0, 0.0, 0.0]
    velocity_timeout:    1.0

# ── Lifecycle Managers ────────────────────────────────────────────────────────
lifecycle_manager_localization:
  ros__parameters:
    use_sim_time: false
    autostart:    true
    node_names:   ["map_server", "amcl"]

lifecycle_manager_navigation:
  ros__parameters:
    use_sim_time: false
    autostart:    true
    node_names:   ["controller_server", "planner_server", "behavior_server",
                   "bt_navigator", "velocity_smoother"]
