feat: add two-floor elevator simulation
This commit is contained in:
242
src/elevator_cpp_example.cpp
Normal file
242
src/elevator_cpp_example.cpp
Normal file
@@ -0,0 +1,242 @@
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
#include <ros/ros.h>
|
||||
|
||||
#include <two_floor_elevator_sim/CallElevator.h>
|
||||
#include <two_floor_elevator_sim/DoorCommand.h>
|
||||
#include <two_floor_elevator_sim/SelectFloor.h>
|
||||
#include <two_floor_elevator_sim/SimElevatorState.h>
|
||||
|
||||
namespace sim = two_floor_elevator_sim;
|
||||
|
||||
// Standalone example: use one callback thread. Wait methods pump spinOnce();
|
||||
// do not call them from a subscriber callback or combine them with AsyncSpinner.
|
||||
class ElevatorApi
|
||||
{
|
||||
public:
|
||||
ElevatorApi(ros::NodeHandle& nh, const std::string& api_namespace,
|
||||
const std::string& elevator_id, const std::string& car_id)
|
||||
: api_nh_(nh, api_namespace), elevator_id_(elevator_id), car_id_(car_id)
|
||||
{
|
||||
call_client_ = api_nh_.serviceClient<sim::CallElevator>("call");
|
||||
select_client_ = api_nh_.serviceClient<sim::SelectFloor>("select_floor");
|
||||
door_client_ = api_nh_.serviceClient<sim::DoorCommand>("door_command");
|
||||
state_sub_ = api_nh_.subscribe("state", 1, &ElevatorApi::onState, this);
|
||||
}
|
||||
|
||||
// True means acceptance only. Observe state to confirm arrival/open doors.
|
||||
bool callFloor(const std::string& floor, const std::string& request_id)
|
||||
{
|
||||
sim::CallElevator srv;
|
||||
srv.request.elevator_id = elevator_id_;
|
||||
srv.request.pickup_floor = floor;
|
||||
srv.request.direction = "ANY";
|
||||
srv.request.request_id = request_id;
|
||||
if (!send(call_client_, srv)) return false;
|
||||
car_id_ = srv.response.car_id;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reuse the hall call's request_id; the server checks robot pose and speed.
|
||||
bool selectFloor(const std::string& floor, const std::string& request_id)
|
||||
{
|
||||
sim::SelectFloor srv;
|
||||
srv.request.elevator_id = elevator_id_;
|
||||
srv.request.car_id = car_id_;
|
||||
srv.request.floor_id = floor;
|
||||
srv.request.request_id = request_id;
|
||||
return send(select_client_, srv);
|
||||
}
|
||||
|
||||
bool doorCommand(std::uint8_t command, float lease_seconds,
|
||||
const std::string& request_id)
|
||||
{
|
||||
if (command == sim::DoorCommand::Request::HOLD_OPEN &&
|
||||
(!std::isfinite(lease_seconds) || lease_seconds <= 0.0f || lease_seconds > 120.0f))
|
||||
{
|
||||
ROS_ERROR("hold_seconds must be finite and in (0, 120] simulation seconds");
|
||||
return false;
|
||||
}
|
||||
sim::DoorCommand srv;
|
||||
srv.request.elevator_id = elevator_id_;
|
||||
srv.request.car_id = car_id_;
|
||||
srv.request.command = command;
|
||||
srv.request.lease_seconds = lease_seconds;
|
||||
srv.request.request_id = request_id;
|
||||
return send(door_client_, srv);
|
||||
}
|
||||
|
||||
bool readState(sim::SimElevatorState& output, double timeout_seconds)
|
||||
{
|
||||
return waitState([](const sim::SimElevatorState&) { return true; },
|
||||
timeout_seconds, output, false);
|
||||
}
|
||||
|
||||
bool waitForArrival(const std::string& floor, const std::string& request_id,
|
||||
double timeout_seconds)
|
||||
{
|
||||
sim::SimElevatorState arrived;
|
||||
return waitState([&](const sim::SimElevatorState& s)
|
||||
{
|
||||
return s.request_id == request_id && s.current_floor == floor &&
|
||||
s.level_aligned && s.door_state == sim::SimElevatorState::DOOR_OPEN &&
|
||||
(s.state == sim::SimElevatorState::WAITING_BOARDING ||
|
||||
s.state == sim::SimElevatorState::WAITING_EXIT);
|
||||
}, timeout_seconds, arrived, true);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Service>
|
||||
bool send(ros::ServiceClient& client, Service& srv)
|
||||
{
|
||||
// This bounds discovery only; ROS 1 ServiceClient::call is synchronous
|
||||
// and has no per-call timeout. Use a worker outside a robot control loop.
|
||||
if (!client.waitForExistence(ros::Duration(5.0)))
|
||||
{
|
||||
ROS_ERROR_STREAM("Service unavailable: " << client.getService());
|
||||
return false;
|
||||
}
|
||||
if (!client.call(srv))
|
||||
{
|
||||
ROS_ERROR_STREAM("Transport failure: " << client.getService()
|
||||
<< "; execution is unknown, inspect state before retrying");
|
||||
return false;
|
||||
}
|
||||
if (!srv.response.accepted)
|
||||
{
|
||||
ROS_ERROR_STREAM("Command rejected: " << srv.response.message);
|
||||
return false;
|
||||
}
|
||||
ROS_INFO_STREAM("Command accepted: " << srv.response.message);
|
||||
return true;
|
||||
}
|
||||
|
||||
void onState(const sim::SimElevatorState::ConstPtr& msg)
|
||||
{
|
||||
if (msg->elevator_id != elevator_id_ || msg->car_id != car_id_) return;
|
||||
state_ = *msg;
|
||||
++state_generation_;
|
||||
}
|
||||
|
||||
bool waitState(const std::function<bool(const sim::SimElevatorState&)>& predicate,
|
||||
double timeout_seconds, sim::SimElevatorState& output, bool fail_on_fault)
|
||||
{
|
||||
if (!std::isfinite(timeout_seconds) || timeout_seconds <= 0.0) return false;
|
||||
// Drain the initial latched message, then require another publication.
|
||||
// A cached state alone does not establish that the simulator is still alive.
|
||||
ros::spinOnce();
|
||||
std::uint64_t seen = state_generation_;
|
||||
const ros::WallTime deadline = ros::WallTime::now() + ros::WallDuration(timeout_seconds);
|
||||
while (ros::ok() && ros::WallTime::now() < deadline)
|
||||
{
|
||||
ros::spinOnce();
|
||||
if (state_generation_ != seen)
|
||||
{
|
||||
seen = state_generation_;
|
||||
const ros::Time now = ros::Time::now();
|
||||
const double age = (now - state_.header.stamp).toSec();
|
||||
if (!now.isZero() && !state_.header.stamp.isZero() && age >= 0.0 && age <= 2.0)
|
||||
{
|
||||
if (fail_on_fault && (!state_.fault_code.empty() ||
|
||||
state_.state == sim::SimElevatorState::FAULT ||
|
||||
state_.state == sim::SimElevatorState::EMERGENCY_STOP))
|
||||
{
|
||||
ROS_ERROR_STREAM("Elevator fault: " << state_.fault_code);
|
||||
return false;
|
||||
}
|
||||
if (predicate(state_))
|
||||
{
|
||||
output = state_;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
ros::WallDuration(0.02).sleep();
|
||||
}
|
||||
ROS_ERROR("State wait ended without confirmation; the accepted command is not cancelled");
|
||||
return false;
|
||||
}
|
||||
|
||||
ros::NodeHandle api_nh_;
|
||||
std::string elevator_id_;
|
||||
std::string car_id_;
|
||||
ros::ServiceClient call_client_;
|
||||
ros::ServiceClient select_client_;
|
||||
ros::ServiceClient door_client_;
|
||||
ros::Subscriber state_sub_;
|
||||
sim::SimElevatorState state_;
|
||||
std::uint64_t state_generation_{0};
|
||||
};
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
ros::init(argc, argv, "elevator_cpp_example", ros::init_options::AnonymousName);
|
||||
ros::NodeHandle nh;
|
||||
ros::NodeHandle pnh("~");
|
||||
std::string command, floor, request_id, api_namespace, elevator_id, car_id;
|
||||
double timeout_seconds, hold_seconds;
|
||||
bool hold_on_arrival;
|
||||
pnh.param<std::string>("command", command, "status");
|
||||
pnh.param<std::string>("floor", floor, "floor_2");
|
||||
pnh.param<std::string>("request_id", request_id, "");
|
||||
pnh.param<std::string>("api_namespace", api_namespace, "/sim_elevator");
|
||||
pnh.param<std::string>("elevator_id", elevator_id, "sim_elevator");
|
||||
pnh.param<std::string>("car_id", car_id, "sim_car_1");
|
||||
pnh.param("timeout_seconds", timeout_seconds, 60.0);
|
||||
pnh.param("hold_seconds", hold_seconds, 30.0);
|
||||
pnh.param("hold_on_arrival", hold_on_arrival, false);
|
||||
if (!std::isfinite(timeout_seconds) || timeout_seconds <= 0.0 ||
|
||||
!std::isfinite(hold_seconds) || hold_seconds <= 0.0 || hold_seconds > 120.0)
|
||||
{
|
||||
ROS_ERROR("timeout_seconds must be positive; hold_seconds must be in (0, 120]");
|
||||
return 2;
|
||||
}
|
||||
if (command == "select" && request_id.empty())
|
||||
{
|
||||
ROS_ERROR("select requires _request_id:=<the request ID used for call>");
|
||||
return 2;
|
||||
}
|
||||
if (request_id.empty())
|
||||
request_id = ros::this_node::getName() + "-" + std::to_string(ros::WallTime::now().toNSec());
|
||||
|
||||
ElevatorApi elevator(nh, api_namespace, elevator_id, car_id);
|
||||
if (command == "status")
|
||||
{
|
||||
sim::SimElevatorState state;
|
||||
if (!elevator.readState(state, timeout_seconds)) return 1;
|
||||
ROS_INFO_STREAM("floor=" << state.current_floor << " target=" << state.target_floor
|
||||
<< " state=" << static_cast<int>(state.state)
|
||||
<< " door=" << static_cast<int>(state.door_state)
|
||||
<< " aligned=" << state.level_aligned << " boarded=" << state.robot_boarded
|
||||
<< " request_id=" << state.request_id << " fault=" << state.fault_code);
|
||||
return 0;
|
||||
}
|
||||
if (command == "call" || command == "select")
|
||||
{
|
||||
ROS_INFO_STREAM("Using request_id=" << request_id);
|
||||
const bool accepted = command == "call" ? elevator.callFloor(floor, request_id)
|
||||
: elevator.selectFloor(floor, request_id);
|
||||
if (!accepted || !elevator.waitForArrival(floor, request_id, timeout_seconds)) return 1;
|
||||
ROS_INFO_STREAM("Confirmed arrival at " << floor << ", level aligned and doors fully open");
|
||||
if (hold_on_arrival)
|
||||
return elevator.doorCommand(sim::DoorCommand::Request::HOLD_OPEN,
|
||||
static_cast<float>(hold_seconds), request_id) ? 0 : 1;
|
||||
return 0;
|
||||
}
|
||||
std::uint8_t door_command;
|
||||
if (command == "open") door_command = sim::DoorCommand::Request::OPEN;
|
||||
else if (command == "close") door_command = sim::DoorCommand::Request::CLOSE;
|
||||
else if (command == "hold") door_command = sim::DoorCommand::Request::HOLD_OPEN;
|
||||
else if (command == "release") door_command = sim::DoorCommand::Request::RELEASE_HOLD;
|
||||
else
|
||||
{
|
||||
ROS_ERROR("command must be status, call, select, open, close, hold, or release");
|
||||
return 2;
|
||||
}
|
||||
return elevator.doorCommand(door_command,
|
||||
command == "hold" ? static_cast<float>(hold_seconds) : 0.0f,
|
||||
request_id) ? 0 : 1;
|
||||
}
|
||||
936
src/elevator_gazebo_plugin.cpp
Normal file
936
src/elevator_gazebo_plugin.cpp
Normal file
@@ -0,0 +1,936 @@
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <gazebo/common/Events.hh>
|
||||
#include <gazebo/common/Plugin.hh>
|
||||
#include <gazebo/physics/physics.hh>
|
||||
#include <gazebo/gazebo.hh>
|
||||
#include <ros/ros.h>
|
||||
|
||||
#include <two_floor_elevator_sim/CallElevator.h>
|
||||
#include <two_floor_elevator_sim/DoorCommand.h>
|
||||
#include <two_floor_elevator_sim/EmergencyStop.h>
|
||||
#include <two_floor_elevator_sim/InjectFault.h>
|
||||
#include <two_floor_elevator_sim/ReserveElevator.h>
|
||||
#include <two_floor_elevator_sim/ResetElevator.h>
|
||||
#include <two_floor_elevator_sim/SelectFloor.h>
|
||||
#include <two_floor_elevator_sim/SimElevatorState.h>
|
||||
|
||||
namespace gazebo
|
||||
{
|
||||
class ElevatorWorldPlugin final : public WorldPlugin
|
||||
{
|
||||
public:
|
||||
void Load(physics::WorldPtr world, sdf::ElementPtr sdf) override
|
||||
{
|
||||
world_ = std::move(world);
|
||||
elevator_id_ = ReadString(sdf, "elevator_id", "sim_elevator");
|
||||
car_id_ = ReadString(sdf, "car_id", "sim_car_1");
|
||||
car_model_name_ = ReadString(sdf, "car_model", "elevator_car");
|
||||
robot_model_name_ = ReadString(sdf, "robot_model", "robot");
|
||||
door_floor_1_left_name_ = ReadString(sdf, "door_floor_1_left_model", "landing_door_floor_1_left");
|
||||
door_floor_1_right_name_ = ReadString(sdf, "door_floor_1_right_model", "landing_door_floor_1_right");
|
||||
door_floor_2_left_name_ = ReadString(sdf, "door_floor_2_left_model", "landing_door_floor_2_left");
|
||||
door_floor_2_right_name_ = ReadString(sdf, "door_floor_2_right_model", "landing_door_floor_2_right");
|
||||
car_door_left_name_ = ReadString(sdf, "car_door_left_model", "elevator_car_door_left");
|
||||
car_door_right_name_ = ReadString(sdf, "car_door_right_model", "elevator_car_door_right");
|
||||
floor_1_id_ = ReadString(sdf, "floor_1_id", "floor_1");
|
||||
floor_2_id_ = ReadString(sdf, "floor_2_id", "floor_2");
|
||||
floor_1_z_ = ReadDouble(sdf, "floor_1_z", 0.0);
|
||||
floor_2_z_ = ReadDouble(sdf, "floor_2_z", 14.0);
|
||||
travel_speed_ = std::max(0.1, ReadDouble(sdf, "travel_speed", 1.1));
|
||||
door_travel_time_ = std::max(0.1, ReadDouble(sdf, "door_travel_time", 1.0));
|
||||
door_leaf_open_offset_ = ReadDouble(sdf, "door_leaf_open_offset", 1.4);
|
||||
door_pocket_offset_x_ = ReadDouble(sdf, "door_pocket_offset_x", 0.15);
|
||||
cabin_half_x_ = ReadDouble(sdf, "cabin_half_x", 1.4);
|
||||
cabin_half_y_ = ReadDouble(sdf, "cabin_half_y", 1.4);
|
||||
robot_half_x_ = ReadDouble(sdf, "robot_half_x", 0.60);
|
||||
robot_half_y_ = ReadDouble(sdf, "robot_half_y", 0.50);
|
||||
door_half_width_ = ReadDouble(sdf, "door_half_width", 1.4);
|
||||
boarding_timeout_ = std::max(2.0, ReadDouble(sdf, "boarding_timeout", 25.0));
|
||||
travel_timeout_ = std::max(5.0, ReadDouble(sdf, "travel_timeout", 30.0));
|
||||
door_open_timeout_ = std::max(1.0, ReadDouble(sdf, "door_open_timeout", 12.0));
|
||||
|
||||
if (!ros::isInitialized())
|
||||
{
|
||||
ROS_FATAL("ROS is not initialized; load gazebo_ros_api_plugin before the elevator world plugin");
|
||||
return;
|
||||
}
|
||||
|
||||
node_.reset(new ros::NodeHandle("/sim_elevator"));
|
||||
spinner_.reset(new ros::AsyncSpinner(1));
|
||||
spinner_->start();
|
||||
|
||||
car_model_ = world_->ModelByName(car_model_name_);
|
||||
door_floor_1_left_ = world_->ModelByName(door_floor_1_left_name_);
|
||||
door_floor_1_right_ = world_->ModelByName(door_floor_1_right_name_);
|
||||
door_floor_2_left_ = world_->ModelByName(door_floor_2_left_name_);
|
||||
door_floor_2_right_ = world_->ModelByName(door_floor_2_right_name_);
|
||||
car_door_left_ = world_->ModelByName(car_door_left_name_);
|
||||
car_door_right_ = world_->ModelByName(car_door_right_name_);
|
||||
if (!car_model_ || !door_floor_1_left_ || !door_floor_1_right_ ||
|
||||
!door_floor_2_left_ || !door_floor_2_right_ || !car_door_left_ || !car_door_right_)
|
||||
{
|
||||
ROS_FATAL_STREAM("Missing elevator world models or door panels for car=" << car_model_name_);
|
||||
return;
|
||||
}
|
||||
|
||||
car_x_ = car_model_->WorldPose().Pos().X();
|
||||
car_y_ = car_model_->WorldPose().Pos().Y();
|
||||
car_rotation_ = car_model_->WorldPose().Rot();
|
||||
landing_door_closed_poses_ = {{door_floor_1_left_->WorldPose(), door_floor_1_right_->WorldPose(),
|
||||
door_floor_2_left_->WorldPose(), door_floor_2_right_->WorldPose()}};
|
||||
car_model_->SetWorldPose(CarPose(floor_1_z_));
|
||||
const ignition::math::Pose3d floor_1_car_pose = CarPose(floor_1_z_);
|
||||
car_door_left_local_pose_ = floor_1_car_pose.Inverse() * car_door_left_->WorldPose();
|
||||
car_door_right_local_pose_ = floor_1_car_pose.Inverse() * car_door_right_->WorldPose();
|
||||
SetCarDoorPoses(floor_1_z_);
|
||||
|
||||
state_pub_ = node_->advertise<two_floor_elevator_sim::SimElevatorState>("state", 1, true);
|
||||
call_srv_ = node_->advertiseService("call", &ElevatorWorldPlugin::Call, this);
|
||||
select_floor_srv_ = node_->advertiseService("select_floor", &ElevatorWorldPlugin::SelectFloor, this);
|
||||
door_srv_ = node_->advertiseService("door_command", &ElevatorWorldPlugin::DoorCommand, this);
|
||||
reserve_srv_ = node_->advertiseService("reserve", &ElevatorWorldPlugin::Reserve, this);
|
||||
reset_srv_ = node_->advertiseService("reset", &ElevatorWorldPlugin::Reset, this);
|
||||
fault_srv_ = node_->advertiseService("inject_fault", &ElevatorWorldPlugin::InjectFault, this);
|
||||
emergency_stop_srv_ = node_->advertiseService("emergency_stop", &ElevatorWorldPlugin::EmergencyStop, this);
|
||||
|
||||
update_connection_ = event::Events::ConnectWorldUpdateBegin(
|
||||
std::bind(&ElevatorWorldPlugin::OnUpdate, this, std::placeholders::_1));
|
||||
ROS_INFO_STREAM("Sim elevator API ready at /sim_elevator for floors "
|
||||
<< floor_1_id_ << " and " << floor_2_id_);
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string ReadString(const sdf::ElementPtr& sdf, const std::string& key,
|
||||
const std::string& fallback)
|
||||
{
|
||||
return sdf && sdf->HasElement(key) ? sdf->Get<std::string>(key) : fallback;
|
||||
}
|
||||
|
||||
static double ReadDouble(const sdf::ElementPtr& sdf, const std::string& key, double fallback)
|
||||
{
|
||||
return sdf && sdf->HasElement(key) ? sdf->Get<double>(key) : fallback;
|
||||
}
|
||||
|
||||
ignition::math::Pose3d CarPose(double z) const
|
||||
{
|
||||
return ignition::math::Pose3d(car_x_, car_y_, z, car_rotation_.Roll(),
|
||||
car_rotation_.Pitch(), car_rotation_.Yaw());
|
||||
}
|
||||
|
||||
ignition::math::Pose3d ShiftDoor(const ignition::math::Pose3d& pose) const
|
||||
{
|
||||
const double direction = pose.Pos().Y() < car_y_ ? -1.0 : 1.0;
|
||||
return ignition::math::Pose3d(pose.Pos().X() + door_pocket_offset_x_,
|
||||
pose.Pos().Y() + direction * door_leaf_open_offset_,
|
||||
pose.Pos().Z(), pose.Rot().Roll(),
|
||||
pose.Rot().Pitch(), pose.Rot().Yaw());
|
||||
}
|
||||
|
||||
bool ValidFloor(const std::string& floor) const
|
||||
{
|
||||
return floor == floor_1_id_ || floor == floor_2_id_;
|
||||
}
|
||||
|
||||
double FloorZ(const std::string& floor) const
|
||||
{
|
||||
return floor == floor_2_id_ ? floor_2_z_ : floor_1_z_;
|
||||
}
|
||||
|
||||
std::string OtherFloor(const std::string& floor) const
|
||||
{
|
||||
return floor == floor_1_id_ ? floor_2_id_ : floor_1_id_;
|
||||
}
|
||||
|
||||
struct DoorPair
|
||||
{
|
||||
physics::ModelPtr left;
|
||||
physics::ModelPtr right;
|
||||
};
|
||||
|
||||
DoorPair LandingDoorsForFloor(const std::string& floor) const
|
||||
{
|
||||
return floor == floor_2_id_ ? DoorPair{door_floor_2_left_, door_floor_2_right_}
|
||||
: DoorPair{door_floor_1_left_, door_floor_1_right_};
|
||||
}
|
||||
|
||||
std::array<physics::ModelPtr, 4> ActiveDoorPanels(const std::string& floor) const
|
||||
{
|
||||
const DoorPair landing = LandingDoorsForFloor(floor);
|
||||
return {{landing.left, landing.right, car_door_left_, car_door_right_}};
|
||||
}
|
||||
|
||||
ignition::math::Pose3d ClosedDoorPose(const std::string& floor, std::size_t panel_index) const
|
||||
{
|
||||
if (panel_index < 2)
|
||||
{
|
||||
const std::size_t floor_offset = floor == floor_2_id_ ? 2 : 0;
|
||||
return landing_door_closed_poses_[floor_offset + panel_index];
|
||||
}
|
||||
const ignition::math::Pose3d car_pose = CarPose(FloorZ(floor));
|
||||
return panel_index == 2 ? car_pose * car_door_left_local_pose_
|
||||
: car_pose * car_door_right_local_pose_;
|
||||
}
|
||||
|
||||
void SetCarDoorPoses(double car_z)
|
||||
{
|
||||
if (!car_door_left_ || !car_door_right_) return;
|
||||
const ignition::math::Pose3d car_pose = CarPose(car_z);
|
||||
car_door_left_->SetWorldPose(car_pose * car_door_left_local_pose_);
|
||||
car_door_right_->SetWorldPose(car_pose * car_door_right_local_pose_);
|
||||
}
|
||||
|
||||
void SetDoorPanelsOpenImmediately(const std::string& floor)
|
||||
{
|
||||
active_door_floor_ = floor;
|
||||
active_door_panels_ = ActiveDoorPanels(floor);
|
||||
for (std::size_t i = 0; i < active_door_panels_.size(); ++i)
|
||||
active_door_panels_[i]->SetWorldPose(ShiftDoor(ClosedDoorPose(floor, i)));
|
||||
}
|
||||
|
||||
bool IsAligned(const std::string& floor) const
|
||||
{
|
||||
if (!car_model_ || !ValidFloor(floor)) return false;
|
||||
return std::abs(car_model_->WorldPose().Pos().Z() - FloorZ(floor)) < 0.025;
|
||||
}
|
||||
|
||||
bool RobotPoseInCar(ignition::math::Pose3d* relative_pose = nullptr) const
|
||||
{
|
||||
if (!robot_model_ || !car_model_) return false;
|
||||
const ignition::math::Pose3d car_pose = car_model_->WorldPose();
|
||||
const ignition::math::Pose3d relative = car_pose.Inverse() * robot_model_->WorldPose();
|
||||
if (relative_pose) *relative_pose = relative;
|
||||
return std::abs(relative.Pos().Z()) <= 0.25 &&
|
||||
std::abs(relative.Pos().X()) <= cabin_half_x_ - robot_half_x_ &&
|
||||
std::abs(relative.Pos().Y()) <= cabin_half_y_ - robot_half_y_;
|
||||
}
|
||||
|
||||
bool RobotBlocksDoor() const
|
||||
{
|
||||
if (!robot_model_ || !car_model_) return false;
|
||||
const ignition::math::Pose3d relative = car_model_->WorldPose().Inverse() * robot_model_->WorldPose();
|
||||
if (std::abs(relative.Pos().Z()) > 1.2) return false;
|
||||
const bool near_threshold = relative.Pos().X() < -cabin_half_x_ + robot_half_x_ + 0.35 &&
|
||||
relative.Pos().X() > -cabin_half_x_ - robot_half_x_ - 0.35;
|
||||
return near_threshold && std::abs(relative.Pos().Y()) < door_half_width_ + robot_half_y_;
|
||||
}
|
||||
|
||||
bool RobotStopped() const
|
||||
{
|
||||
if (!robot_model_) return false;
|
||||
const ignition::math::Vector3d linear = robot_model_->WorldLinearVel();
|
||||
const ignition::math::Vector3d angular = robot_model_->WorldAngularVel();
|
||||
return std::hypot(linear.X(), linear.Y()) < 0.06 && std::abs(angular.Z()) < 0.08;
|
||||
}
|
||||
|
||||
bool IsBusyFault() const { return fault_code_ == "BUSY"; }
|
||||
|
||||
bool Call(two_floor_elevator_sim::CallElevator::Request& req,
|
||||
two_floor_elevator_sim::CallElevator::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (req.elevator_id != elevator_id_ || !ValidFloor(req.pickup_floor))
|
||||
{
|
||||
res.message = "unknown elevator or pickup floor";
|
||||
return true;
|
||||
}
|
||||
const std::string expected_direction = req.pickup_floor == floor_1_id_ ? "UP" : "DOWN";
|
||||
if (req.request_id.empty() || (!req.direction.empty() && req.direction != "ANY" &&
|
||||
req.direction != expected_direction))
|
||||
{
|
||||
res.message = "request_id is required and direction must match the pickup floor";
|
||||
return true;
|
||||
}
|
||||
if (reserved_ && reserved_by_ != req.request_id)
|
||||
{
|
||||
res.message = "elevator is reserved by another request";
|
||||
return true;
|
||||
}
|
||||
if (!req.request_id.empty() && req.request_id == request_id_)
|
||||
{
|
||||
res.accepted = true;
|
||||
res.car_id = car_id_;
|
||||
res.message = "duplicate request acknowledged";
|
||||
return true;
|
||||
}
|
||||
if (IsBusyFault() || state_ != two_floor_elevator_sim::SimElevatorState::IDLE)
|
||||
{
|
||||
res.message = "elevator is busy";
|
||||
return true;
|
||||
}
|
||||
|
||||
request_id_ = req.request_id;
|
||||
pickup_floor_ = req.pickup_floor;
|
||||
target_floor_.clear();
|
||||
move_after_close_ = false;
|
||||
res.accepted = true;
|
||||
res.car_id = car_id_;
|
||||
res.message = "call accepted";
|
||||
if (current_floor_ == pickup_floor_ && IsAligned(pickup_floor_))
|
||||
{
|
||||
BeginOpen(pickup_floor_, world_->SimTime().Double());
|
||||
}
|
||||
else
|
||||
{
|
||||
BeginTravel(pickup_floor_, two_floor_elevator_sim::SimElevatorState::CALLING,
|
||||
world_->SimTime().Double());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SelectFloor(two_floor_elevator_sim::SelectFloor::Request& req,
|
||||
two_floor_elevator_sim::SelectFloor::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (req.elevator_id != elevator_id_ || req.car_id != car_id_ || !ValidFloor(req.floor_id))
|
||||
{
|
||||
res.message = "unknown elevator, car, or floor";
|
||||
return true;
|
||||
}
|
||||
if (req.request_id.empty() || req.request_id != request_id_ ||
|
||||
(reserved_ && reserved_by_ != req.request_id))
|
||||
{
|
||||
res.message = "request_id does not own this elevator ride";
|
||||
return true;
|
||||
}
|
||||
const bool boarding = state_ == two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING;
|
||||
const bool onboard_at_floor = state_ == two_floor_elevator_sim::SimElevatorState::WAITING_EXIT;
|
||||
if ((!boarding && !onboard_at_floor) ||
|
||||
!RobotPoseInCar() || !RobotStopped())
|
||||
{
|
||||
res.message = "floor selection requires a stopped robot fully inside the car at a floor";
|
||||
return true;
|
||||
}
|
||||
if (req.floor_id == current_floor_)
|
||||
{
|
||||
res.message = "destination is already the current floor";
|
||||
return true;
|
||||
}
|
||||
if (fault_code_ == "DOOR_BLOCKED" || RobotBlocksDoor())
|
||||
{
|
||||
res.message = "cannot select a floor while the doorway is blocked";
|
||||
return true;
|
||||
}
|
||||
target_floor_ = req.floor_id;
|
||||
robot_relative_pose_ = car_model_->WorldPose().Inverse() * robot_model_->WorldPose();
|
||||
robot_boarded_ = true;
|
||||
move_after_close_ = true;
|
||||
BeginClose(world_->SimTime().Double());
|
||||
if (door_state_ != two_floor_elevator_sim::SimElevatorState::DOOR_CLOSING &&
|
||||
state_ != two_floor_elevator_sim::SimElevatorState::MOVING)
|
||||
{
|
||||
move_after_close_ = false;
|
||||
robot_boarded_ = false;
|
||||
res.message = "destination rejected because the car door did not close";
|
||||
return true;
|
||||
}
|
||||
res.accepted = true;
|
||||
res.message = "destination floor accepted";
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DoorCommand(two_floor_elevator_sim::DoorCommand::Request& req,
|
||||
two_floor_elevator_sim::DoorCommand::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (req.elevator_id != elevator_id_ || req.car_id != car_id_)
|
||||
{
|
||||
res.message = "unknown elevator or car";
|
||||
res.door_state = door_state_;
|
||||
return true;
|
||||
}
|
||||
const double now = world_->SimTime().Double();
|
||||
switch (req.command)
|
||||
{
|
||||
case two_floor_elevator_sim::DoorCommand::Request::OPEN:
|
||||
if (state_ == two_floor_elevator_sim::SimElevatorState::MOVING ||
|
||||
state_ == two_floor_elevator_sim::SimElevatorState::EMERGENCY_STOP ||
|
||||
!IsAligned(current_floor_))
|
||||
{
|
||||
res.message = "cannot open doors while moving or not level with a floor";
|
||||
break;
|
||||
}
|
||||
BeginOpen(current_floor_, now);
|
||||
door_open_since_ = now + door_travel_time_;
|
||||
res.accepted = true;
|
||||
res.message = "open request accepted";
|
||||
break;
|
||||
case two_floor_elevator_sim::DoorCommand::Request::CLOSE:
|
||||
if (RobotBlocksDoor() || fault_code_ == "DOOR_BLOCKED")
|
||||
{
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_BLOCKED;
|
||||
res.message = "door close rejected: threshold is blocked";
|
||||
break;
|
||||
}
|
||||
BeginClose(now);
|
||||
res.accepted = true;
|
||||
res.message = "close request accepted";
|
||||
break;
|
||||
case two_floor_elevator_sim::DoorCommand::Request::HOLD_OPEN:
|
||||
if (door_state_ != two_floor_elevator_sim::SimElevatorState::DOOR_OPEN || req.lease_seconds <= 0.0)
|
||||
{
|
||||
res.message = "hold requires an open door and a positive lease";
|
||||
break;
|
||||
}
|
||||
door_hold_until_ = now + std::min<double>(req.lease_seconds, 120.0);
|
||||
res.accepted = true;
|
||||
res.message = "door hold lease started";
|
||||
break;
|
||||
case two_floor_elevator_sim::DoorCommand::Request::RELEASE_HOLD:
|
||||
door_hold_until_ = 0.0;
|
||||
res.accepted = true;
|
||||
res.message = "door hold released";
|
||||
break;
|
||||
default:
|
||||
res.message = "unsupported door command";
|
||||
break;
|
||||
}
|
||||
res.door_state = door_state_;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Reserve(two_floor_elevator_sim::ReserveElevator::Request& req,
|
||||
two_floor_elevator_sim::ReserveElevator::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (req.elevator_id != elevator_id_ || req.car_id != car_id_)
|
||||
{
|
||||
res.message = "unknown elevator or car";
|
||||
return true;
|
||||
}
|
||||
const double now = world_->SimTime().Double();
|
||||
if (req.reserve)
|
||||
{
|
||||
if (req.owner_id.empty() || req.lease_seconds <= 0.0 ||
|
||||
(reserved_ && reserved_by_ != req.owner_id) ||
|
||||
(state_ != two_floor_elevator_sim::SimElevatorState::IDLE &&
|
||||
(!reserved_ || reserved_by_ != req.owner_id)))
|
||||
{
|
||||
res.message = "invalid owner, lease, or car already reserved";
|
||||
return true;
|
||||
}
|
||||
reserved_ = true;
|
||||
reserved_by_ = req.owner_id;
|
||||
reserve_expiry_ = now + std::min<double>(req.lease_seconds, 180.0);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (reserved_ && !req.owner_id.empty() && reserved_by_ != req.owner_id)
|
||||
{
|
||||
res.message = "reservation belongs to another owner";
|
||||
return true;
|
||||
}
|
||||
reserved_ = false;
|
||||
reserved_by_.clear();
|
||||
reserve_expiry_ = 0.0;
|
||||
}
|
||||
res.accepted = true;
|
||||
res.reserved_by = reserved_by_;
|
||||
res.lease_remaining = reserved_ ? std::max(0.0, reserve_expiry_ - now) : 0.0;
|
||||
res.message = reserved_ ? "car reserved" : "reservation released";
|
||||
return true;
|
||||
}
|
||||
|
||||
struct CarriedModel
|
||||
{
|
||||
physics::ModelPtr model;
|
||||
ignition::math::Pose3d relative_pose;
|
||||
};
|
||||
|
||||
void CaptureCargo()
|
||||
{
|
||||
carried_cargo_.clear();
|
||||
const auto car_pose = car_model_->WorldPose();
|
||||
// The cabin is axis aligned in this world. Only dynamic models resting
|
||||
// wholly on its floor are carried; fixed world geometry is never moved.
|
||||
for (const auto& model : world_->Models())
|
||||
{
|
||||
if (!model || model->IsStatic() || model == car_model_ ||
|
||||
model->GetName() == robot_model_name_) continue;
|
||||
const auto box = model->BoundingBox();
|
||||
const double floor_z = car_pose.Pos().Z();
|
||||
if (box.Min().X() < car_x_ - cabin_half_x_ + 0.08 ||
|
||||
box.Max().X() > car_x_ + cabin_half_x_ - 0.08 ||
|
||||
box.Min().Y() < car_y_ - cabin_half_y_ + 0.08 ||
|
||||
box.Max().Y() > car_y_ + cabin_half_y_ - 0.08 ||
|
||||
!std::isfinite(box.Min().X()) || !std::isfinite(box.Max().X()) ||
|
||||
!std::isfinite(box.Min().Y()) || !std::isfinite(box.Max().Y()) ||
|
||||
!std::isfinite(box.Min().Z()) || !std::isfinite(box.Max().Z()) ||
|
||||
box.Max().X() <= box.Min().X() || box.Max().Y() <= box.Min().Y() ||
|
||||
box.Min().Z() < floor_z - 0.08 || box.Min().Z() > floor_z + 0.15 ||
|
||||
box.Max().Z() > floor_z + 2.30 || box.Max().Z() <= box.Min().Z()) continue;
|
||||
carried_cargo_.push_back({model, car_pose.Inverse() * model->WorldPose()});
|
||||
ROS_INFO_STREAM("Elevator carrying model " << model->GetName());
|
||||
}
|
||||
}
|
||||
|
||||
void MoveCargo(const ignition::math::Pose3d& car_pose)
|
||||
{
|
||||
for (const auto& cargo : carried_cargo_)
|
||||
{
|
||||
if (!cargo.model || world_->ModelByName(cargo.model->GetName()) != cargo.model) continue;
|
||||
cargo.model->SetWorldPose(car_pose * cargo.relative_pose);
|
||||
cargo.model->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
cargo.model->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
}
|
||||
}
|
||||
|
||||
bool Reset(two_floor_elevator_sim::ResetElevator::Request&,
|
||||
two_floor_elevator_sim::ResetElevator::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
ignition::math::Pose3d robot_relative;
|
||||
const bool evacuate_robot = RobotPoseInCar(&robot_relative);
|
||||
CaptureCargo();
|
||||
const bool evacuate_cargo = !carried_cargo_.empty();
|
||||
const double car_z = car_model_->WorldPose().Pos().Z();
|
||||
const std::string reset_floor = (evacuate_robot || evacuate_cargo) &&
|
||||
std::abs(car_z - floor_2_z_) < std::abs(car_z - floor_1_z_) ? floor_2_id_ : floor_1_id_;
|
||||
const ignition::math::Pose3d reset_pose = CarPose(FloorZ(reset_floor));
|
||||
car_model_->SetWorldPose(reset_pose);
|
||||
car_model_->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
car_model_->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
MoveCargo(reset_pose);
|
||||
carried_cargo_.clear();
|
||||
if (evacuate_robot && robot_model_)
|
||||
{
|
||||
robot_model_->SetWorldPose(reset_pose * robot_relative);
|
||||
robot_model_->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
robot_model_->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
}
|
||||
door_floor_1_left_->SetWorldPose(landing_door_closed_poses_[0]);
|
||||
door_floor_1_right_->SetWorldPose(landing_door_closed_poses_[1]);
|
||||
door_floor_2_left_->SetWorldPose(landing_door_closed_poses_[2]);
|
||||
door_floor_2_right_->SetWorldPose(landing_door_closed_poses_[3]);
|
||||
SetCarDoorPoses(FloorZ(reset_floor));
|
||||
current_floor_ = reset_floor;
|
||||
pickup_floor_.clear();
|
||||
target_floor_.clear();
|
||||
request_id_.clear();
|
||||
reserved_ = false;
|
||||
reserved_by_.clear();
|
||||
reserve_expiry_ = 0.0;
|
||||
door_hold_until_ = 0.0;
|
||||
robot_boarded_ = evacuate_robot;
|
||||
fault_code_.clear();
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::IDLE;
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED;
|
||||
if (evacuate_robot || evacuate_cargo) BeginOpen(reset_floor, world_->SimTime().Double());
|
||||
res.accepted = true;
|
||||
res.message = evacuate_robot ? "elevator reset to nearest floor and opened for robot evacuation"
|
||||
: evacuate_cargo ? "elevator reset to nearest floor and opened for cargo"
|
||||
: "empty elevator reset to floor_1";
|
||||
return true;
|
||||
}
|
||||
|
||||
bool InjectFault(two_floor_elevator_sim::InjectFault::Request& req,
|
||||
two_floor_elevator_sim::InjectFault::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const std::string supported[] = {"BUSY", "DOOR_BLOCKED", "TRAVEL_TIMEOUT", "WRONG_FLOOR"};
|
||||
const bool known = std::find(std::begin(supported), std::end(supported), req.fault_code) !=
|
||||
std::end(supported);
|
||||
if (!known)
|
||||
{
|
||||
res.message = "unsupported fault code";
|
||||
return true;
|
||||
}
|
||||
if (req.active)
|
||||
{
|
||||
fault_code_ = req.fault_code;
|
||||
if (fault_code_ == "DOOR_BLOCKED" && door_state_ != two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED &&
|
||||
ValidFloor(current_floor_) && IsAligned(current_floor_))
|
||||
ReopenBlockedDoor(world_->SimTime().Double());
|
||||
}
|
||||
else if (fault_code_ == req.fault_code)
|
||||
{
|
||||
fault_code_.clear();
|
||||
if (door_state_ == two_floor_elevator_sim::SimElevatorState::DOOR_BLOCKED)
|
||||
{
|
||||
if (ValidFloor(current_floor_) && IsAligned(current_floor_))
|
||||
{
|
||||
SetDoorPanelsOpenImmediately(current_floor_);
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_OPEN;
|
||||
state_ = robot_boarded_ ? two_floor_elevator_sim::SimElevatorState::WAITING_EXIT
|
||||
: two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING;
|
||||
door_open_since_ = world_->SimTime().Double();
|
||||
}
|
||||
else
|
||||
{
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED;
|
||||
}
|
||||
}
|
||||
}
|
||||
res.accepted = true;
|
||||
res.message = req.active ? "fault injected" : "fault cleared";
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EmergencyStop(two_floor_elevator_sim::EmergencyStop::Request& req,
|
||||
two_floor_elevator_sim::EmergencyStop::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (state_ == two_floor_elevator_sim::SimElevatorState::MOVING && car_model_)
|
||||
{
|
||||
const double z = car_model_->WorldPose().Pos().Z();
|
||||
const ignition::math::Pose3d stopped_pose = CarPose(z);
|
||||
car_model_->SetWorldPose(stopped_pose);
|
||||
SetCarDoorPoses(z);
|
||||
if (robot_boarded_ && robot_model_)
|
||||
robot_model_->SetWorldPose(stopped_pose * robot_relative_pose_);
|
||||
}
|
||||
if (car_model_)
|
||||
{
|
||||
car_model_->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
car_model_->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
}
|
||||
fault_code_ = req.reason.empty() ? "EMERGENCY_STOP" : req.reason;
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::EMERGENCY_STOP;
|
||||
res.accepted = true;
|
||||
res.message = "simulated elevator emergency stop latched; reset required";
|
||||
return true;
|
||||
}
|
||||
|
||||
void BeginTravel(const std::string& floor, uint8_t state, double now)
|
||||
{
|
||||
CaptureCargo();
|
||||
target_floor_ = floor;
|
||||
travel_start_z_ = car_model_->WorldPose().Pos().Z();
|
||||
travel_target_z_ = FloorZ(floor);
|
||||
state_ = state;
|
||||
state_start_time_ = now;
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED;
|
||||
}
|
||||
|
||||
void BeginOpen(const std::string& floor, double now)
|
||||
{
|
||||
if (!ValidFloor(floor) || !IsAligned(floor)) return;
|
||||
current_floor_ = floor;
|
||||
active_door_floor_ = floor;
|
||||
active_door_panels_ = ActiveDoorPanels(floor);
|
||||
for (std::size_t i = 0; i < active_door_panels_.size(); ++i)
|
||||
{
|
||||
door_start_poses_[i] = active_door_panels_[i]->WorldPose();
|
||||
door_target_poses_[i] = ShiftDoor(door_start_poses_[i]);
|
||||
}
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::OPENING;
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_OPENING;
|
||||
state_start_time_ = now;
|
||||
door_hold_until_ = 0.0;
|
||||
door_open_since_ = now + door_travel_time_;
|
||||
}
|
||||
|
||||
void BeginClose(double now)
|
||||
{
|
||||
if (!ValidFloor(current_floor_) || door_state_ == two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED)
|
||||
{
|
||||
if (move_after_close_) BeginTravel(target_floor_, two_floor_elevator_sim::SimElevatorState::MOVING, now);
|
||||
return;
|
||||
}
|
||||
if (RobotBlocksDoor() || fault_code_ == "DOOR_BLOCKED")
|
||||
{
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_BLOCKED;
|
||||
return;
|
||||
}
|
||||
active_door_floor_ = current_floor_;
|
||||
active_door_panels_ = ActiveDoorPanels(active_door_floor_);
|
||||
for (std::size_t i = 0; i < active_door_panels_.size(); ++i)
|
||||
{
|
||||
door_start_poses_[i] = active_door_panels_[i]->WorldPose();
|
||||
door_target_poses_[i] = ClosedDoorPose(active_door_floor_, i);
|
||||
}
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::CLOSING;
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_CLOSING;
|
||||
state_start_time_ = now;
|
||||
door_hold_until_ = 0.0;
|
||||
}
|
||||
|
||||
void UpdateDoor(double now)
|
||||
{
|
||||
const double alpha = std::clamp((now - state_start_time_) / door_travel_time_, 0.0, 1.0);
|
||||
const double eased_alpha = alpha * alpha * (3.0 - 2.0 * alpha);
|
||||
for (std::size_t i = 0; i < active_door_panels_.size(); ++i)
|
||||
{
|
||||
const ignition::math::Vector3d start = door_start_poses_[i].Pos();
|
||||
const ignition::math::Vector3d target = door_target_poses_[i].Pos();
|
||||
const ignition::math::Pose3d pose(start.X() + eased_alpha * (target.X() - start.X()),
|
||||
start.Y() + eased_alpha * (target.Y() - start.Y()),
|
||||
start.Z() + eased_alpha * (target.Z() - start.Z()),
|
||||
door_start_poses_[i].Rot().Roll(),
|
||||
door_start_poses_[i].Rot().Pitch(),
|
||||
door_start_poses_[i].Rot().Yaw());
|
||||
active_door_panels_[i]->SetWorldPose(pose);
|
||||
}
|
||||
if (alpha < 1.0) return;
|
||||
|
||||
const bool opening = state_ == two_floor_elevator_sim::SimElevatorState::OPENING;
|
||||
door_state_ = opening ? two_floor_elevator_sim::SimElevatorState::DOOR_OPEN
|
||||
: two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED;
|
||||
if (opening)
|
||||
{
|
||||
state_ = robot_boarded_ ? two_floor_elevator_sim::SimElevatorState::WAITING_EXIT
|
||||
: two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING;
|
||||
boarding_started_at_ = now;
|
||||
if (fault_code_ == "TRAVEL_TIMEOUT")
|
||||
{
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::FAULT;
|
||||
}
|
||||
}
|
||||
else if (move_after_close_)
|
||||
{
|
||||
move_after_close_ = false;
|
||||
BeginTravel(target_floor_, two_floor_elevator_sim::SimElevatorState::MOVING, now);
|
||||
}
|
||||
else
|
||||
{
|
||||
state_ = robot_boarded_ ? two_floor_elevator_sim::SimElevatorState::WAITING_EXIT
|
||||
: two_floor_elevator_sim::SimElevatorState::IDLE;
|
||||
if (!robot_boarded_)
|
||||
{
|
||||
pickup_floor_.clear();
|
||||
target_floor_.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReopenBlockedDoor(double now)
|
||||
{
|
||||
SetDoorPanelsOpenImmediately(current_floor_);
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_BLOCKED;
|
||||
state_ = robot_boarded_ ? two_floor_elevator_sim::SimElevatorState::WAITING_EXIT
|
||||
: two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING;
|
||||
door_open_since_ = now;
|
||||
}
|
||||
|
||||
void UpdateTravel(double now)
|
||||
{
|
||||
if (fault_code_ == "TRAVEL_TIMEOUT")
|
||||
{
|
||||
if (now - state_start_time_ >= std::min(3.0, travel_timeout_))
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::FAULT;
|
||||
return;
|
||||
}
|
||||
const double distance = travel_target_z_ - travel_start_z_;
|
||||
const double duration = std::abs(distance) / travel_speed_;
|
||||
const double alpha = duration <= 1e-6 ? 1.0 : std::clamp((now - state_start_time_) / duration, 0.0, 1.0);
|
||||
const double eased_alpha = alpha * alpha * (3.0 - 2.0 * alpha);
|
||||
const double z = travel_start_z_ + eased_alpha * distance;
|
||||
const ignition::math::Pose3d car_pose = CarPose(z);
|
||||
car_model_->SetWorldPose(car_pose);
|
||||
SetCarDoorPoses(z);
|
||||
car_model_->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
car_model_->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
MoveCargo(car_pose);
|
||||
if (robot_boarded_ && robot_model_)
|
||||
{
|
||||
robot_model_->SetWorldPose(car_pose * robot_relative_pose_);
|
||||
robot_model_->SetLinearVel(ignition::math::Vector3d::Zero);
|
||||
robot_model_->SetAngularVel(ignition::math::Vector3d::Zero);
|
||||
}
|
||||
if (alpha < 1.0) return;
|
||||
|
||||
carried_cargo_.clear();
|
||||
|
||||
const uint8_t travel_state = state_;
|
||||
const std::string arrived_floor = target_floor_;
|
||||
if (fault_code_ == "WRONG_FLOOR")
|
||||
{
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::FAULT;
|
||||
return;
|
||||
}
|
||||
current_floor_ = arrived_floor;
|
||||
if (state_ == two_floor_elevator_sim::SimElevatorState::CALLING)
|
||||
{
|
||||
BeginOpen(pickup_floor_, now);
|
||||
}
|
||||
else if (travel_state == two_floor_elevator_sim::SimElevatorState::MOVING)
|
||||
{
|
||||
BeginOpen(arrived_floor, now);
|
||||
}
|
||||
}
|
||||
|
||||
void OnUpdate(const common::UpdateInfo& info)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!robot_model_) robot_model_ = world_->ModelByName(robot_model_name_);
|
||||
if (!car_model_ || !door_floor_1_left_ || !door_floor_1_right_ ||
|
||||
!door_floor_2_left_ || !door_floor_2_right_ || !car_door_left_ || !car_door_right_) return;
|
||||
const double now = info.simTime.Double();
|
||||
if (state_ == two_floor_elevator_sim::SimElevatorState::OPENING)
|
||||
UpdateDoor(now);
|
||||
else if (state_ == two_floor_elevator_sim::SimElevatorState::CLOSING)
|
||||
{
|
||||
if (fault_code_ == "DOOR_BLOCKED" || RobotBlocksDoor()) ReopenBlockedDoor(now);
|
||||
else UpdateDoor(now);
|
||||
}
|
||||
else if (state_ == two_floor_elevator_sim::SimElevatorState::CALLING ||
|
||||
state_ == two_floor_elevator_sim::SimElevatorState::MOVING)
|
||||
UpdateTravel(now);
|
||||
else if (state_ == two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING)
|
||||
{
|
||||
if (RobotPoseInCar() && RobotStopped()) robot_boarded_ = true;
|
||||
if (now - boarding_started_at_ > boarding_timeout_ && !robot_boarded_)
|
||||
{
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::FAULT;
|
||||
fault_code_ = "BOARD_TIMEOUT";
|
||||
}
|
||||
}
|
||||
else if (state_ == two_floor_elevator_sim::SimElevatorState::WAITING_EXIT)
|
||||
{
|
||||
if (!RobotPoseInCar())
|
||||
{
|
||||
robot_boarded_ = false;
|
||||
if (!reserved_ && door_state_ == two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED)
|
||||
state_ = two_floor_elevator_sim::SimElevatorState::IDLE;
|
||||
}
|
||||
}
|
||||
|
||||
if (door_state_ == two_floor_elevator_sim::SimElevatorState::DOOR_BLOCKED &&
|
||||
fault_code_ != "DOOR_BLOCKED" && !RobotBlocksDoor())
|
||||
{
|
||||
door_state_ = two_floor_elevator_sim::SimElevatorState::DOOR_OPEN;
|
||||
state_ = robot_boarded_ ? two_floor_elevator_sim::SimElevatorState::WAITING_EXIT
|
||||
: two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING;
|
||||
door_open_since_ = now;
|
||||
}
|
||||
|
||||
if ((state_ == two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING ||
|
||||
state_ == two_floor_elevator_sim::SimElevatorState::WAITING_EXIT) &&
|
||||
door_state_ == two_floor_elevator_sim::SimElevatorState::DOOR_OPEN &&
|
||||
!reserved_ && door_hold_until_ <= now &&
|
||||
door_open_since_ > 0.0 && now - door_open_since_ >= door_open_timeout_)
|
||||
{
|
||||
BeginClose(now);
|
||||
}
|
||||
|
||||
if (reserved_ && !robot_boarded_ && reserve_expiry_ > 0.0 && now > reserve_expiry_)
|
||||
{
|
||||
reserved_ = false;
|
||||
reserved_by_.clear();
|
||||
reserve_expiry_ = 0.0;
|
||||
}
|
||||
if (door_hold_until_ > 0.0 && now > door_hold_until_) door_hold_until_ = 0.0;
|
||||
|
||||
if (now - last_status_publish_ >= 0.1)
|
||||
{
|
||||
PublishState();
|
||||
last_status_publish_ = now;
|
||||
}
|
||||
}
|
||||
|
||||
void PublishState()
|
||||
{
|
||||
if (!state_pub_) return;
|
||||
two_floor_elevator_sim::SimElevatorState msg;
|
||||
msg.header.stamp = ros::Time::now();
|
||||
msg.header.frame_id = "map";
|
||||
msg.elevator_id = elevator_id_;
|
||||
msg.car_id = car_id_;
|
||||
msg.current_floor = current_floor_;
|
||||
msg.pickup_floor = pickup_floor_;
|
||||
msg.target_floor = target_floor_;
|
||||
msg.request_id = request_id_;
|
||||
msg.reserved_by = reserved_by_;
|
||||
msg.fault_code = fault_code_;
|
||||
msg.state = state_;
|
||||
msg.door_state = door_state_;
|
||||
msg.level_aligned = IsAligned(current_floor_);
|
||||
msg.busy = state_ != two_floor_elevator_sim::SimElevatorState::IDLE;
|
||||
msg.reserved = reserved_;
|
||||
msg.robot_boarded = robot_boarded_ || RobotPoseInCar();
|
||||
state_pub_.publish(msg);
|
||||
}
|
||||
|
||||
physics::WorldPtr world_;
|
||||
physics::ModelPtr car_model_;
|
||||
physics::ModelPtr robot_model_;
|
||||
physics::ModelPtr door_floor_1_left_;
|
||||
physics::ModelPtr door_floor_1_right_;
|
||||
physics::ModelPtr door_floor_2_left_;
|
||||
physics::ModelPtr door_floor_2_right_;
|
||||
physics::ModelPtr car_door_left_;
|
||||
physics::ModelPtr car_door_right_;
|
||||
std::array<physics::ModelPtr, 4> active_door_panels_;
|
||||
event::ConnectionPtr update_connection_;
|
||||
std::unique_ptr<ros::NodeHandle> node_;
|
||||
std::unique_ptr<ros::AsyncSpinner> spinner_;
|
||||
ros::Publisher state_pub_;
|
||||
ros::ServiceServer call_srv_;
|
||||
ros::ServiceServer select_floor_srv_;
|
||||
ros::ServiceServer door_srv_;
|
||||
ros::ServiceServer reserve_srv_;
|
||||
ros::ServiceServer reset_srv_;
|
||||
ros::ServiceServer fault_srv_;
|
||||
ros::ServiceServer emergency_stop_srv_;
|
||||
std::mutex mutex_;
|
||||
|
||||
std::string elevator_id_{"sim_elevator"};
|
||||
std::string car_id_{"sim_car_1"};
|
||||
std::string car_model_name_{"elevator_car"};
|
||||
std::string robot_model_name_{"robot"};
|
||||
std::string door_floor_1_left_name_{"landing_door_floor_1_left"};
|
||||
std::string door_floor_1_right_name_{"landing_door_floor_1_right"};
|
||||
std::string door_floor_2_left_name_{"landing_door_floor_2_left"};
|
||||
std::string door_floor_2_right_name_{"landing_door_floor_2_right"};
|
||||
std::string car_door_left_name_{"elevator_car_door_left"};
|
||||
std::string car_door_right_name_{"elevator_car_door_right"};
|
||||
std::string floor_1_id_{"floor_1"};
|
||||
std::string floor_2_id_{"floor_2"};
|
||||
std::string current_floor_{"floor_1"};
|
||||
std::string pickup_floor_;
|
||||
std::string target_floor_;
|
||||
std::string active_door_floor_{"floor_1"};
|
||||
std::string request_id_;
|
||||
std::string fault_code_;
|
||||
std::string reserved_by_;
|
||||
uint8_t state_{two_floor_elevator_sim::SimElevatorState::IDLE};
|
||||
uint8_t door_state_{two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED};
|
||||
bool reserved_{false};
|
||||
bool robot_boarded_{false};
|
||||
bool move_after_close_{false};
|
||||
double floor_1_z_{0.0};
|
||||
double floor_2_z_{14.0};
|
||||
double car_x_{39.0};
|
||||
double car_y_{0.0};
|
||||
double travel_speed_{1.1};
|
||||
double door_travel_time_{1.0};
|
||||
double door_leaf_open_offset_{1.4};
|
||||
double door_pocket_offset_x_{0.15};
|
||||
double cabin_half_x_{1.4};
|
||||
double cabin_half_y_{1.4};
|
||||
double robot_half_x_{0.60};
|
||||
double robot_half_y_{0.50};
|
||||
double door_half_width_{1.4};
|
||||
double boarding_timeout_{45.0};
|
||||
double travel_timeout_{30.0};
|
||||
double door_open_timeout_{12.0};
|
||||
double state_start_time_{0.0};
|
||||
double boarding_started_at_{0.0};
|
||||
double last_status_publish_{-1.0};
|
||||
double travel_start_z_{0.0};
|
||||
double travel_target_z_{0.0};
|
||||
double reserve_expiry_{0.0};
|
||||
double door_hold_until_{0.0};
|
||||
double door_open_since_{0.0};
|
||||
ignition::math::Quaterniond car_rotation_;
|
||||
ignition::math::Pose3d robot_relative_pose_;
|
||||
std::vector<CarriedModel> carried_cargo_;
|
||||
ignition::math::Pose3d car_door_left_local_pose_;
|
||||
ignition::math::Pose3d car_door_right_local_pose_;
|
||||
std::array<ignition::math::Pose3d, 4> landing_door_closed_poses_;
|
||||
std::array<ignition::math::Pose3d, 4> door_start_poses_;
|
||||
std::array<ignition::math::Pose3d, 4> door_target_poses_;
|
||||
};
|
||||
|
||||
GZ_REGISTER_WORLD_PLUGIN(ElevatorWorldPlugin)
|
||||
} // namespace gazebo
|
||||
271
src/floor_map_switcher.cpp
Normal file
271
src/floor_map_switcher.cpp
Normal file
@@ -0,0 +1,271 @@
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include <nav_msgs/OccupancyGrid.h>
|
||||
#include <ros/ros.h>
|
||||
#include <std_msgs/String.h>
|
||||
|
||||
#include <two_floor_elevator_sim/SimElevatorState.h>
|
||||
#include <two_floor_elevator_sim/SwitchFloorMap.h>
|
||||
|
||||
class FloorMapSwitcher
|
||||
{
|
||||
public:
|
||||
FloorMapSwitcher() : private_nh_("~")
|
||||
{
|
||||
private_nh_.param<std::string>("floor_1_topic", floor_1_topic_, "/floor_1/map");
|
||||
private_nh_.param<std::string>("floor_2_topic", floor_2_topic_, "/floor_2/map");
|
||||
private_nh_.param<std::string>("initial_floor", active_floor_, "floor_1");
|
||||
private_nh_.param<std::string>("map_frame", map_frame_, "map");
|
||||
private_nh_.param("shaft_shift_x", shaft_shift_x_, 35.72);
|
||||
private_nh_.param("shaft_shift_y", shaft_shift_y_, 0.0);
|
||||
private_nh_.param("state_timeout_seconds", state_timeout_seconds_, 1.0);
|
||||
|
||||
map_pub_ = nh_.advertise<nav_msgs::OccupancyGrid>("/map", 1, true);
|
||||
active_floor_pub_ = nh_.advertise<std_msgs::String>("/sim_elevator/active_floor", 1, true);
|
||||
floor_1_sub_ = nh_.subscribe(floor_1_topic_, 1, &FloorMapSwitcher::Floor1Callback, this);
|
||||
floor_2_sub_ = nh_.subscribe(floor_2_topic_, 1, &FloorMapSwitcher::Floor2Callback, this);
|
||||
elevator_state_sub_ = nh_.subscribe("/sim_elevator/state", 1,
|
||||
&FloorMapSwitcher::ElevatorStateCallback, this);
|
||||
switch_srv_ = nh_.advertiseService("/floor_map_switcher/switch", &FloorMapSwitcher::Switch, this);
|
||||
retry_timer_ = nh_.createTimer(ros::Duration(0.25), &FloorMapSwitcher::RetryPublish, this);
|
||||
}
|
||||
|
||||
private:
|
||||
void Floor1Callback(const nav_msgs::OccupancyGrid::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
floor_1_map_ = *msg;
|
||||
has_floor_1_map_ = true;
|
||||
if (active_floor_ == "floor_1") PublishActiveMap(floor_1_map_);
|
||||
}
|
||||
|
||||
void Floor2Callback(const nav_msgs::OccupancyGrid::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
floor_2_map_ = *msg;
|
||||
has_floor_2_map_ = true;
|
||||
if (active_floor_ == "floor_2") PublishActiveMap(floor_2_map_);
|
||||
}
|
||||
|
||||
bool DoorAccessAllowed() const
|
||||
{
|
||||
const bool state_fresh = has_elevator_state_ && !last_state_wall_time_.isZero() &&
|
||||
(ros::WallTime::now() - last_state_wall_time_).toSec() <= state_timeout_seconds_;
|
||||
return state_fresh && elevator_state_.current_floor == active_floor_ &&
|
||||
elevator_state_.level_aligned &&
|
||||
elevator_state_.door_state == two_floor_elevator_sim::SimElevatorState::DOOR_OPEN;
|
||||
}
|
||||
|
||||
void ElevatorStateCallback(const two_floor_elevator_sim::SimElevatorState::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const bool was_access_allowed = DoorAccessAllowed();
|
||||
elevator_state_ = *msg;
|
||||
has_elevator_state_ = true;
|
||||
last_state_wall_time_ = ros::WallTime::now();
|
||||
if (was_access_allowed != DoorAccessAllowed()) PublishCurrentActiveMap();
|
||||
}
|
||||
|
||||
static bool WorldToCell(const nav_msgs::OccupancyGrid& map, const double x, const double y,
|
||||
unsigned int& cell_x, unsigned int& cell_y)
|
||||
{
|
||||
const double resolution = map.info.resolution;
|
||||
if (resolution <= 0.0 || map.info.width == 0 || map.info.height == 0) return false;
|
||||
|
||||
const double yaw = 2.0 * std::atan2(map.info.origin.orientation.z,
|
||||
map.info.origin.orientation.w);
|
||||
const double dx = x - map.info.origin.position.x;
|
||||
const double dy = y - map.info.origin.position.y;
|
||||
const double local_x = std::cos(yaw) * dx + std::sin(yaw) * dy;
|
||||
const double local_y = -std::sin(yaw) * dx + std::cos(yaw) * dy;
|
||||
if (local_x < 0.0 || local_y < 0.0) return false;
|
||||
|
||||
const auto ix = static_cast<unsigned int>(std::floor(local_x / resolution));
|
||||
const auto iy = static_cast<unsigned int>(std::floor(local_y / resolution));
|
||||
if (ix >= map.info.width || iy >= map.info.height) return false;
|
||||
cell_x = ix;
|
||||
cell_y = iy;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void SetWorldCell(nav_msgs::OccupancyGrid& map, const double x, const double y,
|
||||
const std::int8_t value)
|
||||
{
|
||||
unsigned int cell_x = 0;
|
||||
unsigned int cell_y = 0;
|
||||
if (!WorldToCell(map, x, y, cell_x, cell_y)) return;
|
||||
const std::size_t index = static_cast<std::size_t>(cell_y) * map.info.width + cell_x;
|
||||
if (index < map.data.size()) map.data[index] = value;
|
||||
}
|
||||
|
||||
void ApplyElevatorSafetyOverlay(nav_msgs::OccupancyGrid& map) const
|
||||
{
|
||||
if (map.info.resolution <= 0.0 || map.info.width == 0 || map.info.height == 0 ||
|
||||
map.data.size() != static_cast<std::size_t>(map.info.width) * map.info.height)
|
||||
{
|
||||
ROS_ERROR_THROTTLE(5.0, "cannot apply elevator safety overlay to an invalid OccupancyGrid");
|
||||
return;
|
||||
}
|
||||
|
||||
// Block the complete floor aperture until state permits access.
|
||||
// A wall-time freshness gate and timer close access if elevator state stops updating.
|
||||
const unsigned int width = map.info.width;
|
||||
const unsigned int height = map.info.height;
|
||||
const double resolution = map.info.resolution;
|
||||
const double yaw = 2.0 * std::atan2(map.info.origin.orientation.z,
|
||||
map.info.origin.orientation.w);
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
const bool access_allowed = DoorAccessAllowed();
|
||||
|
||||
for (unsigned int iy = 0; iy < height; ++iy)
|
||||
{
|
||||
for (unsigned int ix = 0; ix < width; ++ix)
|
||||
{
|
||||
const double local_x = (static_cast<double>(ix) + 0.5) * resolution;
|
||||
const double local_y = (static_cast<double>(iy) + 0.5) * resolution;
|
||||
// The overlay geometry below is expressed relative to its original location.
|
||||
const double x = map.info.origin.position.x + c * local_x - s * local_y - shaft_shift_x_;
|
||||
const double y = map.info.origin.position.y + s * local_x + c * local_y - shaft_shift_y_;
|
||||
if (x < 1.78 || x > 4.98 || y < -1.78 || y > 1.78) continue;
|
||||
|
||||
// Keep the car and doorway blocked unless the car is aligned here and
|
||||
// its doors report fully open. The doorway corridor is narrower than
|
||||
// the cabin so the robot footprint stays clear of the moving panels.
|
||||
bool safe_cabin = false;
|
||||
if (access_allowed)
|
||||
{
|
||||
const bool doorway = x >= 1.55 && x <= 2.12 && std::abs(y) <= 0.50;
|
||||
const bool cabin = x >= 2.02 && x <= 4.30 && std::abs(y) <= 0.75;
|
||||
safe_cabin = doorway || cabin;
|
||||
}
|
||||
map.data[static_cast<std::size_t>(iy) * width + ix] = safe_cabin ? 0 : 100;
|
||||
}
|
||||
}
|
||||
|
||||
// Reapply fixed cabin walls and safety rails over the cleared cabin area.
|
||||
if (access_allowed)
|
||||
{
|
||||
const auto mark_box = [this, &map](double x0, double x1, double y0, double y1)
|
||||
{
|
||||
const double resolution = map.info.resolution;
|
||||
for (double y = y0; y <= y1; y += resolution)
|
||||
for (double x = x0; x <= x1; x += resolution)
|
||||
SetWorldCell(map, x + shaft_shift_x_, y + shaft_shift_y_, 100);
|
||||
};
|
||||
mark_box(1.78, 2.02, -1.60, -1.44); // left jamb
|
||||
mark_box(1.78, 2.02, 1.44, 1.60); // right jamb
|
||||
mark_box(2.00, 4.80, -1.40, -1.32); // cabin side walls
|
||||
mark_box(2.00, 4.80, 1.32, 1.40);
|
||||
mark_box(4.72, 4.80, -1.40, 1.40); // cabin rear wall
|
||||
mark_box(1.90, 4.90, -1.76, -1.66); // landing guardrails
|
||||
mark_box(1.90, 4.90, 1.66, 1.76);
|
||||
mark_box(4.82, 4.94, -1.76, 1.76); // rear guardrail
|
||||
mark_box(4.80, 4.88, -1.54, -1.46); // guide rails
|
||||
mark_box(4.80, 4.88, 1.46, 1.54);
|
||||
}
|
||||
}
|
||||
|
||||
void PublishActiveMap(nav_msgs::OccupancyGrid map)
|
||||
{
|
||||
ApplyElevatorSafetyOverlay(map);
|
||||
map.header.stamp = ros::Time::now();
|
||||
map.header.frame_id = map_frame_;
|
||||
map_pub_.publish(map);
|
||||
std_msgs::String floor_msg;
|
||||
floor_msg.data = active_floor_;
|
||||
active_floor_pub_.publish(floor_msg);
|
||||
active_published_ = true;
|
||||
last_published_access_allowed_ = DoorAccessAllowed();
|
||||
}
|
||||
|
||||
void PublishCurrentActiveMap()
|
||||
{
|
||||
if (active_floor_ == "floor_1" && has_floor_1_map_) PublishActiveMap(floor_1_map_);
|
||||
else if (active_floor_ == "floor_2" && has_floor_2_map_) PublishActiveMap(floor_2_map_);
|
||||
}
|
||||
|
||||
void RetryPublish(const ros::TimerEvent&)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!active_published_)
|
||||
{
|
||||
PublishCurrentActiveMap();
|
||||
if (active_published_) return;
|
||||
}
|
||||
else if (last_published_access_allowed_ != DoorAccessAllowed())
|
||||
{
|
||||
PublishCurrentActiveMap();
|
||||
return;
|
||||
}
|
||||
if (!active_published_ && active_floor_ != "floor_1" && active_floor_ != "floor_2")
|
||||
ROS_ERROR_THROTTLE(5.0, "initial_floor must be floor_1 or floor_2");
|
||||
}
|
||||
|
||||
bool Switch(two_floor_elevator_sim::SwitchFloorMap::Request& req,
|
||||
two_floor_elevator_sim::SwitchFloorMap::Response& res)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (req.floor_id == "floor_1" && has_floor_1_map_)
|
||||
{
|
||||
active_floor_ = req.floor_id;
|
||||
PublishActiveMap(floor_1_map_);
|
||||
}
|
||||
else if (req.floor_id == "floor_2" && has_floor_2_map_)
|
||||
{
|
||||
active_floor_ = req.floor_id;
|
||||
PublishActiveMap(floor_2_map_);
|
||||
}
|
||||
else
|
||||
{
|
||||
res.message = "unknown floor or its map has not arrived yet";
|
||||
res.active_floor = active_floor_;
|
||||
return true;
|
||||
}
|
||||
res.accepted = true;
|
||||
res.active_floor = active_floor_;
|
||||
res.message = DoorAccessAllowed()
|
||||
? "active map published; aligned open elevator access is cleared"
|
||||
: "active map published with elevator shaft blocked for safety";
|
||||
return true;
|
||||
}
|
||||
|
||||
ros::NodeHandle nh_;
|
||||
ros::NodeHandle private_nh_;
|
||||
ros::Subscriber floor_1_sub_;
|
||||
ros::Subscriber floor_2_sub_;
|
||||
ros::Subscriber elevator_state_sub_;
|
||||
ros::Publisher map_pub_;
|
||||
ros::Publisher active_floor_pub_;
|
||||
ros::ServiceServer switch_srv_;
|
||||
ros::Timer retry_timer_;
|
||||
std::mutex mutex_;
|
||||
nav_msgs::OccupancyGrid floor_1_map_;
|
||||
nav_msgs::OccupancyGrid floor_2_map_;
|
||||
two_floor_elevator_sim::SimElevatorState elevator_state_;
|
||||
bool has_floor_1_map_{false};
|
||||
bool has_floor_2_map_{false};
|
||||
bool has_elevator_state_{false};
|
||||
bool active_published_{false};
|
||||
bool last_published_access_allowed_{false};
|
||||
std::string floor_1_topic_;
|
||||
std::string floor_2_topic_;
|
||||
std::string active_floor_;
|
||||
std::string map_frame_;
|
||||
double shaft_shift_x_{35.72};
|
||||
double shaft_shift_y_{0.0};
|
||||
double state_timeout_seconds_{1.0};
|
||||
ros::WallTime last_state_wall_time_;
|
||||
};
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
ros::init(argc, argv, "floor_map_switcher");
|
||||
FloorMapSwitcher switcher;
|
||||
ros::spin();
|
||||
return 0;
|
||||
}
|
||||
574
src/floor_transition_manager.cpp
Normal file
574
src/floor_transition_manager.cpp
Normal file
@@ -0,0 +1,574 @@
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include <actionlib/server/simple_action_server.h>
|
||||
#include <geometry_msgs/PoseWithCovarianceStamped.h>
|
||||
#include <geometry_msgs/PoseStamped.h>
|
||||
#include <nav_msgs/Odometry.h>
|
||||
#include <ros/ros.h>
|
||||
#include <std_msgs/String.h>
|
||||
#include <tf2/LinearMath/Quaternion.h>
|
||||
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
|
||||
|
||||
#include <two_floor_elevator_sim/CallElevator.h>
|
||||
#include <two_floor_elevator_sim/DoorCommand.h>
|
||||
#include <two_floor_elevator_sim/EmergencyStop.h>
|
||||
#include <two_floor_elevator_sim/ReserveElevator.h>
|
||||
#include <two_floor_elevator_sim/SelectFloor.h>
|
||||
#include <two_floor_elevator_sim/SimElevatorRideAction.h>
|
||||
#include <two_floor_elevator_sim/SimElevatorState.h>
|
||||
#include <two_floor_elevator_sim/SwitchFloorMap.h>
|
||||
|
||||
class FloorTransitionManager
|
||||
{
|
||||
public:
|
||||
using ActionServer = actionlib::SimpleActionServer<two_floor_elevator_sim::SimElevatorRideAction>;
|
||||
|
||||
FloorTransitionManager()
|
||||
: private_nh_("~"), action_server_(nh_, "/sim_elevator/ride",
|
||||
[this](const two_floor_elevator_sim::SimElevatorRideGoalConstPtr& goal) { Execute(goal); }, false)
|
||||
{
|
||||
private_nh_.param<std::string>("elevator/id", elevator_id_, "sim_elevator");
|
||||
private_nh_.param<std::string>("navigation/goal_topic", goal_topic_, "/move_base_simple/goal");
|
||||
private_nh_.param<std::string>("navigation/amcl_pose_topic", amcl_topic_, "/amcl_pose");
|
||||
private_nh_.param<std::string>("navigation/odom_topic", odom_topic_, "/odom");
|
||||
private_nh_.param<std::string>("navigation/map_frame", map_frame_, "map");
|
||||
private_nh_.param("navigation/goal_tolerance", goal_tolerance_, 0.12);
|
||||
private_nh_.param("navigation/stopped_velocity", stopped_velocity_, 0.05);
|
||||
private_nh_.param("navigation/stable_time", stable_time_, 0.75);
|
||||
private_nh_.param("navigation/navigation_timeout", navigation_timeout_, 90.0);
|
||||
private_nh_.param("navigation/localization_timeout", localization_timeout_, 20.0);
|
||||
private_nh_.param("navigation/door_hold_seconds", door_hold_seconds_, 90.0);
|
||||
private_nh_.param("navigation/reservation_seconds", reservation_seconds_, 170.0);
|
||||
|
||||
LoadFloor("floor_1", floor_1_);
|
||||
LoadFloor("floor_2", floor_2_);
|
||||
|
||||
state_sub_ = nh_.subscribe("/sim_elevator/state", 10, &FloorTransitionManager::StateCallback, this);
|
||||
active_floor_sub_ = nh_.subscribe("/sim_elevator/active_floor", 1,
|
||||
&FloorTransitionManager::ActiveFloorCallback, this);
|
||||
amcl_sub_ = nh_.subscribe(amcl_topic_, 10, &FloorTransitionManager::AmclCallback, this);
|
||||
odom_sub_ = nh_.subscribe(odom_topic_, 10, &FloorTransitionManager::OdomCallback, this);
|
||||
goal_pub_ = nh_.advertise<geometry_msgs::PoseStamped>(goal_topic_, 2, false);
|
||||
initial_pose_pub_ = nh_.advertise<geometry_msgs::PoseWithCovarianceStamped>("/initialpose", 1, false);
|
||||
|
||||
call_client_ = nh_.serviceClient<two_floor_elevator_sim::CallElevator>("/sim_elevator/call");
|
||||
select_client_ = nh_.serviceClient<two_floor_elevator_sim::SelectFloor>("/sim_elevator/select_floor");
|
||||
door_client_ = nh_.serviceClient<two_floor_elevator_sim::DoorCommand>("/sim_elevator/door_command");
|
||||
reserve_client_ = nh_.serviceClient<two_floor_elevator_sim::ReserveElevator>("/sim_elevator/reserve");
|
||||
stop_client_ = nh_.serviceClient<two_floor_elevator_sim::EmergencyStop>("/sim_elevator/emergency_stop");
|
||||
map_client_ = nh_.serviceClient<two_floor_elevator_sim::SwitchFloorMap>("/floor_map_switcher/switch");
|
||||
|
||||
action_server_.start();
|
||||
ROS_INFO("Simulated floor transition action ready at /sim_elevator/ride");
|
||||
}
|
||||
|
||||
private:
|
||||
struct FloorPose
|
||||
{
|
||||
std::string id;
|
||||
double cabin_x{0.0};
|
||||
double cabin_y{0.0};
|
||||
double cabin_yaw{0.0};
|
||||
double exit_x{0.0};
|
||||
double exit_y{0.0};
|
||||
double exit_yaw{0.0};
|
||||
};
|
||||
|
||||
void LoadFloor(const std::string& id, FloorPose& floor)
|
||||
{
|
||||
floor.id = id;
|
||||
private_nh_.param("floors/" + id + "/cabin_x", floor.cabin_x, 39.0);
|
||||
private_nh_.param("floors/" + id + "/cabin_y", floor.cabin_y, 0.0);
|
||||
private_nh_.param("floors/" + id + "/cabin_yaw", floor.cabin_yaw, 0.0);
|
||||
private_nh_.param("floors/" + id + "/exit_x", floor.exit_x, 35.5);
|
||||
private_nh_.param("floors/" + id + "/exit_y", floor.exit_y, 0.0);
|
||||
private_nh_.param("floors/" + id + "/exit_yaw", floor.exit_yaw, 3.141592653589793);
|
||||
}
|
||||
|
||||
void StateCallback(const two_floor_elevator_sim::SimElevatorState::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
elevator_state_ = *msg;
|
||||
have_elevator_state_ = true;
|
||||
state_received_wall_ = ros::WallTime::now().toSec();
|
||||
}
|
||||
|
||||
void ActiveFloorCallback(const std_msgs::String::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
active_floor_ = msg->data;
|
||||
}
|
||||
|
||||
void AmclCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
amcl_pose_ = *msg;
|
||||
have_amcl_pose_ = true;
|
||||
amcl_received_wall_ = ros::WallTime::now().toSec();
|
||||
}
|
||||
|
||||
void OdomCallback(const nav_msgs::Odometry::ConstPtr& msg)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
odom_ = *msg;
|
||||
have_odom_ = true;
|
||||
}
|
||||
|
||||
two_floor_elevator_sim::SimElevatorState StateSnapshot() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
return elevator_state_;
|
||||
}
|
||||
|
||||
double Remaining(const ros::WallTime& deadline) const
|
||||
{
|
||||
return std::max(0.0, (deadline - ros::WallTime::now()).toSec());
|
||||
}
|
||||
|
||||
bool WaitUntil(const std::function<bool()>& predicate, const ros::WallTime& deadline,
|
||||
const std::string& phase, std::string& error)
|
||||
{
|
||||
ros::WallTime next_feedback = ros::WallTime::now();
|
||||
while (ros::ok() && Remaining(deadline) > 0.0)
|
||||
{
|
||||
if (action_server_.isPreemptRequested())
|
||||
{
|
||||
error = "action preempt requested during " + phase;
|
||||
return false;
|
||||
}
|
||||
const auto state = StateSnapshot();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
if (have_elevator_state_ && ros::WallTime::now().toSec() - state_received_wall_ > 1.5)
|
||||
{
|
||||
error = "elevator state topic became stale during " + phase;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (state.state == two_floor_elevator_sim::SimElevatorState::EMERGENCY_STOP)
|
||||
{
|
||||
error = "elevator emergency stop: " + state.fault_code;
|
||||
return false;
|
||||
}
|
||||
if (state.state == two_floor_elevator_sim::SimElevatorState::FAULT)
|
||||
{
|
||||
error = "elevator fault during " + phase + ": " + state.fault_code;
|
||||
return false;
|
||||
}
|
||||
if (predicate()) return true;
|
||||
if ((ros::WallTime::now() - next_feedback).toSec() >= 0.5)
|
||||
{
|
||||
PublishFeedback(state);
|
||||
next_feedback = ros::WallTime::now();
|
||||
}
|
||||
ros::WallDuration(0.05).sleep();
|
||||
}
|
||||
error = "timeout during " + phase;
|
||||
return false;
|
||||
}
|
||||
|
||||
void PublishFeedback(const two_floor_elevator_sim::SimElevatorState& state)
|
||||
{
|
||||
two_floor_elevator_sim::SimElevatorRideFeedback feedback;
|
||||
feedback.state = state.state;
|
||||
feedback.state_name = StateName(state.state);
|
||||
feedback.current_floor = state.current_floor;
|
||||
feedback.car_id = state.car_id;
|
||||
feedback.door_state = state.door_state;
|
||||
feedback.robot_boarded = state.robot_boarded;
|
||||
action_server_.publishFeedback(feedback);
|
||||
}
|
||||
|
||||
static std::string StateName(uint8_t state)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case two_floor_elevator_sim::SimElevatorState::IDLE: return "IDLE";
|
||||
case two_floor_elevator_sim::SimElevatorState::CALLING: return "CALLING";
|
||||
case two_floor_elevator_sim::SimElevatorState::OPENING: return "OPENING";
|
||||
case two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING: return "WAITING_BOARDING";
|
||||
case two_floor_elevator_sim::SimElevatorState::CLOSING: return "CLOSING";
|
||||
case two_floor_elevator_sim::SimElevatorState::MOVING: return "MOVING";
|
||||
case two_floor_elevator_sim::SimElevatorState::WAITING_EXIT: return "WAITING_EXIT";
|
||||
case two_floor_elevator_sim::SimElevatorState::FAULT: return "FAULT";
|
||||
case two_floor_elevator_sim::SimElevatorState::EMERGENCY_STOP: return "EMERGENCY_STOP";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
static double YawOf(const geometry_msgs::Quaternion& q)
|
||||
{
|
||||
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
|
||||
}
|
||||
|
||||
bool AtPose(double x, double y, double yaw, bool require_stopped) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
if (!have_amcl_pose_ || (require_stopped && !have_odom_)) return false;
|
||||
const double dx = amcl_pose_.pose.pose.position.x - x;
|
||||
const double dy = amcl_pose_.pose.pose.position.y - y;
|
||||
if (std::hypot(dx, dy) > goal_tolerance_) return false;
|
||||
constexpr double kTwoPi = 6.28318530717958647692;
|
||||
const double yaw_error = std::remainder(YawOf(amcl_pose_.pose.pose.orientation) - yaw, kTwoPi);
|
||||
if (std::abs(yaw_error) > 0.25) return false;
|
||||
return !require_stopped || (std::hypot(odom_.twist.twist.linear.x, odom_.twist.twist.linear.y) < stopped_velocity_ &&
|
||||
std::abs(odom_.twist.twist.angular.z) < stopped_velocity_);
|
||||
}
|
||||
|
||||
bool NavigateTo(double x, double y, double yaw, const ros::WallTime& deadline,
|
||||
const std::string& phase, std::string& error)
|
||||
{
|
||||
geometry_msgs::PoseStamped goal;
|
||||
goal.header.stamp = ros::Time::now();
|
||||
goal.header.frame_id = map_frame_;
|
||||
goal.pose.position.x = x;
|
||||
goal.pose.position.y = y;
|
||||
tf2::Quaternion orientation;
|
||||
orientation.setRPY(0.0, 0.0, yaw);
|
||||
goal.pose.orientation = tf2::toMsg(orientation);
|
||||
goal_pub_.publish(goal);
|
||||
|
||||
const ros::WallTime nav_deadline = std::min(deadline, ros::WallTime::now() + ros::WallDuration(navigation_timeout_));
|
||||
double stable_since = -1.0;
|
||||
return WaitUntil([&]() {
|
||||
if (!AtPose(x, y, yaw, true))
|
||||
{
|
||||
stable_since = -1.0;
|
||||
return false;
|
||||
}
|
||||
if (stable_since < 0.0) stable_since = ros::WallTime::now().toSec();
|
||||
return ros::WallTime::now().toSec() - stable_since >= stable_time_;
|
||||
}, nav_deadline, phase, error);
|
||||
}
|
||||
|
||||
bool CallService(ros::ServiceClient& client, const std::string& name, std::string& error)
|
||||
{
|
||||
if (!client.waitForExistence(ros::Duration(5.0)))
|
||||
{
|
||||
error = "service unavailable: " + name;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SetReservation(bool reserve, const std::string& owner, double lease, std::string& error)
|
||||
{
|
||||
if (!CallService(reserve_client_, "/sim_elevator/reserve", error)) return false;
|
||||
two_floor_elevator_sim::ReserveElevator srv;
|
||||
srv.request.elevator_id = elevator_id_;
|
||||
srv.request.car_id = "sim_car_1";
|
||||
srv.request.owner_id = owner;
|
||||
srv.request.reserve = reserve;
|
||||
srv.request.lease_seconds = lease;
|
||||
srv.request.request_id = owner;
|
||||
if (!reserve_client_.call(srv) || !srv.response.accepted)
|
||||
{
|
||||
error = srv.response.message.empty() ? "reservation service call failed" : srv.response.message;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SetDoor(uint8_t command, double lease, std::string& error)
|
||||
{
|
||||
if (!CallService(door_client_, "/sim_elevator/door_command", error)) return false;
|
||||
two_floor_elevator_sim::DoorCommand srv;
|
||||
srv.request.elevator_id = elevator_id_;
|
||||
srv.request.car_id = "sim_car_1";
|
||||
srv.request.command = command;
|
||||
srv.request.lease_seconds = lease;
|
||||
srv.request.request_id = active_request_id_;
|
||||
if (!door_client_.call(srv) || !srv.response.accepted)
|
||||
{
|
||||
error = srv.response.message.empty() ? "door command failed" : srv.response.message;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WaitForLocalization(double x, double y, double yaw, const ros::WallTime& deadline,
|
||||
std::string& error)
|
||||
{
|
||||
const double sent_at = ros::WallTime::now().toSec();
|
||||
geometry_msgs::PoseWithCovarianceStamped initial;
|
||||
initial.header.stamp = ros::Time::now();
|
||||
initial.header.frame_id = map_frame_;
|
||||
initial.pose.pose.position.x = x;
|
||||
initial.pose.pose.position.y = y;
|
||||
tf2::Quaternion orientation;
|
||||
orientation.setRPY(0.0, 0.0, yaw);
|
||||
initial.pose.pose.orientation = tf2::toMsg(orientation);
|
||||
initial.pose.covariance[0] = 0.04;
|
||||
initial.pose.covariance[7] = 0.04;
|
||||
initial.pose.covariance[35] = 0.08;
|
||||
initial_pose_pub_.publish(initial);
|
||||
|
||||
const ros::WallTime localization_deadline = std::min(deadline,
|
||||
ros::WallTime::now() + ros::WallDuration(localization_timeout_));
|
||||
return WaitUntil([&]() {
|
||||
double received = 0.0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
received = amcl_received_wall_;
|
||||
}
|
||||
return received >= sent_at && AtPose(x, y, yaw, false);
|
||||
}, localization_deadline, "destination localization", error);
|
||||
}
|
||||
|
||||
void Fail(const std::string& error, bool preempted)
|
||||
{
|
||||
const auto state = StateSnapshot();
|
||||
if (state.state == two_floor_elevator_sim::SimElevatorState::MOVING)
|
||||
{
|
||||
two_floor_elevator_sim::EmergencyStop stop;
|
||||
stop.request.reason = preempted ? "ACTION_PREEMPTED" : "RIDE_ABORTED";
|
||||
stop_client_.call(stop);
|
||||
}
|
||||
else if (owns_reservation_ && !state.robot_boarded)
|
||||
{
|
||||
std::string ignored;
|
||||
SetDoor(two_floor_elevator_sim::DoorCommand::Request::RELEASE_HOLD, 0.0, ignored);
|
||||
SetReservation(false, active_request_id_, 0.0, ignored);
|
||||
owns_reservation_ = false;
|
||||
}
|
||||
two_floor_elevator_sim::SimElevatorRideResult result;
|
||||
result.success = false;
|
||||
result.reached_floor = state.current_floor;
|
||||
result.error_code = preempted ? "CANCELLED" :
|
||||
state.fault_code.empty() ? "FAILED" : state.fault_code;
|
||||
result.message = error;
|
||||
if (preempted) action_server_.setPreempted(result, error);
|
||||
else action_server_.setAborted(result, error);
|
||||
ROS_WARN_STREAM("Simulated elevator ride failed: " << error);
|
||||
}
|
||||
|
||||
void Execute(const two_floor_elevator_sim::SimElevatorRideGoalConstPtr& goal)
|
||||
{
|
||||
if (!goal->elevator_id.empty() && goal->elevator_id != elevator_id_)
|
||||
{
|
||||
Fail("unknown elevator_id: " + goal->elevator_id, false);
|
||||
return;
|
||||
}
|
||||
const FloorPose* from = goal->from_floor == floor_1_.id ? &floor_1_ :
|
||||
goal->from_floor == floor_2_.id ? &floor_2_ : nullptr;
|
||||
const FloorPose* to = goal->to_floor == floor_1_.id ? &floor_1_ :
|
||||
goal->to_floor == floor_2_.id ? &floor_2_ : nullptr;
|
||||
if (!from || !to || from == to)
|
||||
{
|
||||
Fail("from_floor/to_floor must be different configured floors", false);
|
||||
return;
|
||||
}
|
||||
std::string active_floor;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(data_mutex_);
|
||||
active_floor = active_floor_;
|
||||
}
|
||||
if (active_floor != from->id)
|
||||
{
|
||||
Fail("active map is " + (active_floor.empty() ? std::string("unknown") : active_floor) +
|
||||
", but ride starts at " + from->id, false);
|
||||
return;
|
||||
}
|
||||
|
||||
active_request_id_ = goal->request_id;
|
||||
if (active_request_id_.empty())
|
||||
{
|
||||
std::ostringstream id;
|
||||
id << "sim-ride-" << ros::WallTime::now().toNSec();
|
||||
active_request_id_ = id.str();
|
||||
}
|
||||
const double requested_timeout = goal->timeout > 0.0 ? goal->timeout : 180.0;
|
||||
const ros::WallTime deadline = ros::WallTime::now() + ros::WallDuration(requested_timeout);
|
||||
std::string error;
|
||||
|
||||
if (!SetReservation(true, active_request_id_, std::min(reservation_seconds_, requested_timeout), error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
owns_reservation_ = true;
|
||||
|
||||
if (!CallService(call_client_, "/sim_elevator/call", error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
two_floor_elevator_sim::CallElevator call;
|
||||
call.request.elevator_id = elevator_id_;
|
||||
call.request.pickup_floor = from->id;
|
||||
call.request.direction = from->id == floor_1_.id ? "UP" : "DOWN";
|
||||
call.request.request_id = active_request_id_;
|
||||
if (!call_client_.call(call) || !call.response.accepted)
|
||||
{
|
||||
Fail(call.response.message.empty() ? "elevator call rejected" : call.response.message, false);
|
||||
return;
|
||||
}
|
||||
|
||||
const bool at_pickup = WaitUntil([&]() {
|
||||
const auto state = StateSnapshot();
|
||||
return state.current_floor == from->id && state.level_aligned &&
|
||||
state.state == two_floor_elevator_sim::SimElevatorState::WAITING_BOARDING &&
|
||||
state.door_state == two_floor_elevator_sim::SimElevatorState::DOOR_OPEN;
|
||||
}, deadline, "elevator arrival at pickup floor", error);
|
||||
if (!at_pickup || !NavigateTo(from->cabin_x, from->cabin_y, from->cabin_yaw,
|
||||
deadline, "robot boarding", error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!SetDoor(two_floor_elevator_sim::DoorCommand::Request::HOLD_OPEN,
|
||||
std::min(door_hold_seconds_, Remaining(deadline)), error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
if (!CallService(select_client_, "/sim_elevator/select_floor", error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
two_floor_elevator_sim::SelectFloor select;
|
||||
select.request.elevator_id = elevator_id_;
|
||||
select.request.car_id = "sim_car_1";
|
||||
select.request.floor_id = to->id;
|
||||
select.request.request_id = active_request_id_;
|
||||
if (!select_client_.call(select) || !select.response.accepted)
|
||||
{
|
||||
Fail(select.response.message.empty() ? "destination floor selection rejected" : select.response.message, false);
|
||||
return;
|
||||
}
|
||||
|
||||
const bool at_destination = WaitUntil([&]() {
|
||||
const auto state = StateSnapshot();
|
||||
return state.current_floor == to->id && state.level_aligned &&
|
||||
state.state == two_floor_elevator_sim::SimElevatorState::WAITING_EXIT &&
|
||||
state.door_state == two_floor_elevator_sim::SimElevatorState::DOOR_OPEN &&
|
||||
state.robot_boarded;
|
||||
}, deadline, "cabin arrival and destination door opening", error);
|
||||
if (!at_destination)
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CallService(map_client_, "/floor_map_switcher/switch", error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
two_floor_elevator_sim::SwitchFloorMap map_switch;
|
||||
map_switch.request.floor_id = to->id;
|
||||
if (!map_client_.call(map_switch) || !map_switch.response.accepted)
|
||||
{
|
||||
Fail(map_switch.response.message.empty() ? "destination map switch failed" : map_switch.response.message, false);
|
||||
return;
|
||||
}
|
||||
if (!WaitForLocalization(to->cabin_x, to->cabin_y, to->cabin_yaw, deadline, error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
if (!NavigateTo(to->exit_x, to->exit_y, to->exit_yaw, deadline, "robot exiting elevator", error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!SetDoor(two_floor_elevator_sim::DoorCommand::Request::RELEASE_HOLD, 0.0, error) ||
|
||||
!SetDoor(two_floor_elevator_sim::DoorCommand::Request::CLOSE, 0.0, error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
if (!SetReservation(false, active_request_id_, 0.0, error))
|
||||
{
|
||||
Fail(error, false);
|
||||
return;
|
||||
}
|
||||
owns_reservation_ = false;
|
||||
if (!WaitUntil([&]() {
|
||||
const auto state = StateSnapshot();
|
||||
return state.state == two_floor_elevator_sim::SimElevatorState::IDLE &&
|
||||
state.door_state == two_floor_elevator_sim::SimElevatorState::DOOR_CLOSED;
|
||||
}, deadline, "elevator ready after robot exit", error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
|
||||
if (goal->navigate_to_destination &&
|
||||
!NavigateTo(goal->destination_x, goal->destination_y, goal->destination_yaw,
|
||||
deadline, "final floor destination", error))
|
||||
{
|
||||
Fail(error, action_server_.isPreemptRequested());
|
||||
return;
|
||||
}
|
||||
|
||||
two_floor_elevator_sim::SimElevatorRideResult result;
|
||||
result.success = true;
|
||||
result.reached_floor = to->id;
|
||||
result.error_code.clear();
|
||||
result.message = "robot transferred, map switched, localized, and exited the simulated elevator";
|
||||
action_server_.setSucceeded(result, result.message);
|
||||
ROS_INFO_STREAM("Simulated elevator ride completed: " << from->id << " -> " << to->id);
|
||||
}
|
||||
|
||||
ros::NodeHandle nh_;
|
||||
ros::NodeHandle private_nh_;
|
||||
ActionServer action_server_;
|
||||
ros::Subscriber state_sub_;
|
||||
ros::Subscriber active_floor_sub_;
|
||||
ros::Subscriber amcl_sub_;
|
||||
ros::Subscriber odom_sub_;
|
||||
ros::Publisher goal_pub_;
|
||||
ros::Publisher initial_pose_pub_;
|
||||
ros::ServiceClient call_client_;
|
||||
ros::ServiceClient select_client_;
|
||||
ros::ServiceClient door_client_;
|
||||
ros::ServiceClient reserve_client_;
|
||||
ros::ServiceClient stop_client_;
|
||||
ros::ServiceClient map_client_;
|
||||
mutable std::mutex data_mutex_;
|
||||
two_floor_elevator_sim::SimElevatorState elevator_state_;
|
||||
geometry_msgs::PoseWithCovarianceStamped amcl_pose_;
|
||||
nav_msgs::Odometry odom_;
|
||||
bool have_elevator_state_{false};
|
||||
bool have_amcl_pose_{false};
|
||||
bool have_odom_{false};
|
||||
double amcl_received_wall_{0.0};
|
||||
double state_received_wall_{0.0};
|
||||
FloorPose floor_1_;
|
||||
FloorPose floor_2_;
|
||||
std::string elevator_id_{"sim_elevator"};
|
||||
std::string goal_topic_{"/move_base_simple/goal"};
|
||||
std::string amcl_topic_{"/amcl_pose"};
|
||||
std::string odom_topic_{"/odom"};
|
||||
std::string map_frame_{"map"};
|
||||
std::string active_request_id_;
|
||||
std::string active_floor_;
|
||||
bool owns_reservation_{false};
|
||||
double goal_tolerance_{0.12};
|
||||
double stopped_velocity_{0.05};
|
||||
double stable_time_{0.75};
|
||||
double navigation_timeout_{90.0};
|
||||
double localization_timeout_{20.0};
|
||||
double door_hold_seconds_{90.0};
|
||||
double reservation_seconds_{170.0};
|
||||
};
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
ros::init(argc, argv, "floor_transition_manager");
|
||||
FloorTransitionManager manager;
|
||||
ros::AsyncSpinner spinner(3);
|
||||
spinner.start();
|
||||
ros::waitForShutdown();
|
||||
return 0;
|
||||
}
|
||||
83
src/walking_actor_collision_plugin.cpp
Normal file
83
src/walking_actor_collision_plugin.cpp
Normal file
@@ -0,0 +1,83 @@
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include <gazebo/common/Plugin.hh>
|
||||
#include <gazebo/gazebo.hh>
|
||||
#include <gazebo/physics/Actor.hh>
|
||||
#include <gazebo/physics/BoxShape.hh>
|
||||
#include <gazebo/physics/Collision.hh>
|
||||
#include <gazebo/physics/Link.hh>
|
||||
#include <ignition/math/Pose3.hh>
|
||||
#include <ignition/math/Vector3.hh>
|
||||
|
||||
namespace gazebo {
|
||||
|
||||
// Gazebo actors animate their skeleton, but their generated links are not
|
||||
// initialized by default. Initializing them exposes the bone collisions to
|
||||
// the physics ray sensor while Gazebo's own actor script drives the motion.
|
||||
class WalkingActorCollisionPlugin final : public ModelPlugin {
|
||||
public:
|
||||
void Load(physics::ModelPtr model, sdf::ElementPtr sdf) override {
|
||||
auto actor = boost::dynamic_pointer_cast<physics::Actor>(model);
|
||||
if (!actor) {
|
||||
gzerr << "WalkingActorCollisionPlugin requires a Gazebo actor\n";
|
||||
return;
|
||||
}
|
||||
|
||||
std::map<std::string, ignition::math::Vector3d> scales;
|
||||
std::map<std::string, ignition::math::Pose3d> offsets;
|
||||
if (sdf->HasElement("collision")) {
|
||||
auto element = sdf->GetElement("collision");
|
||||
while (element) {
|
||||
const std::string name = element->Get<std::string>();
|
||||
if (element->HasAttribute("scale")) {
|
||||
scales[name] = element->Get<ignition::math::Vector3d>("scale");
|
||||
}
|
||||
if (element->HasAttribute("pose")) {
|
||||
offsets[name] = element->Get<ignition::math::Pose3d>("pose");
|
||||
}
|
||||
element = element->GetNextElement("collision");
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int collision_count = 0;
|
||||
unsigned int configured_count = 0;
|
||||
bool left_lower_leg = false;
|
||||
bool right_lower_leg = false;
|
||||
for (const auto& link : actor->GetLinks()) {
|
||||
link->Init();
|
||||
for (const auto& collision : link->GetCollisions()) {
|
||||
++collision_count;
|
||||
const auto& name = collision->GetName();
|
||||
const auto scale = scales.find(name);
|
||||
if (scale != scales.end()) {
|
||||
++configured_count;
|
||||
left_lower_leg |= name == "LeftLeg_LeftFoot_collision";
|
||||
right_lower_leg |= name == "RightLeg_RightFoot_collision";
|
||||
auto box = boost::dynamic_pointer_cast<physics::BoxShape>(collision->GetShape());
|
||||
if (box) {
|
||||
box->SetSize(box->Size() * scale->second);
|
||||
}
|
||||
}
|
||||
const auto offset = offsets.find(name);
|
||||
if (offset != offsets.end()) {
|
||||
collision->SetInitialRelativePose(offset->second + collision->InitialRelativePose());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (collision_count == 0 || !left_lower_leg || !right_lower_leg) {
|
||||
gzwarn << "Actor " << actor->GetName() << " has " << collision_count
|
||||
<< " bone collisions, including " << configured_count
|
||||
<< " configured ones; lower-leg LiDAR collisions are incomplete\n";
|
||||
return;
|
||||
}
|
||||
gzmsg << "Actor " << actor->GetName() << " initialized " << collision_count
|
||||
<< " bone collisions for ray LiDAR (" << configured_count
|
||||
<< " configured; both lower legs present)\n";
|
||||
}
|
||||
};
|
||||
|
||||
GZ_REGISTER_MODEL_PLUGIN(WalkingActorCollisionPlugin)
|
||||
|
||||
} // namespace gazebo
|
||||
Reference in New Issue
Block a user