Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
is_battery_charging_condition.cpp
1 // Copyright (c) 2023 Alberto J. Tudela Roldán
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <string>
16 
17 #include "nav2_behavior_tree/plugins/condition/is_battery_charging_condition.hpp"
18 
19 namespace nav2_behavior_tree
20 {
21 
22 IsBatteryChargingCondition::IsBatteryChargingCondition(
23  const std::string & condition_name,
24  const BT::NodeConfiguration & conf)
25 : BT::ConditionNode(condition_name, conf),
26  battery_topic_("/battery_status"),
27  is_battery_charging_(false)
28 {
29  getInput("battery_topic", battery_topic_);
30  auto node = config().blackboard->get<rclcpp::Node::SharedPtr>("node");
31  callback_group_ = node->create_callback_group(
32  rclcpp::CallbackGroupType::MutuallyExclusive,
33  false);
34  callback_group_executor_.add_callback_group(callback_group_, node->get_node_base_interface());
35 
36  rclcpp::SubscriptionOptions sub_option;
37  sub_option.callback_group = callback_group_;
38  battery_sub_ = node->create_subscription<sensor_msgs::msg::BatteryState>(
39  battery_topic_,
40  rclcpp::SystemDefaultsQoS(),
41  std::bind(&IsBatteryChargingCondition::batteryCallback, this, std::placeholders::_1),
42  sub_option);
43 
44  // Spin multiple times due to rclcpp regression in Jazzy requiring a 'warm up' spin
45  callback_group_executor_.spin_some(std::chrono::nanoseconds(1));
46 }
47 
49 {
50  callback_group_executor_.spin_some();
51  if (is_battery_charging_) {
52  return BT::NodeStatus::SUCCESS;
53  }
54  return BT::NodeStatus::FAILURE;
55 }
56 
57 void IsBatteryChargingCondition::batteryCallback(sensor_msgs::msg::BatteryState::SharedPtr msg)
58 {
59  is_battery_charging_ =
60  (msg->power_supply_status == sensor_msgs::msg::BatteryState::POWER_SUPPLY_STATUS_CHARGING);
61 }
62 
63 } // namespace nav2_behavior_tree
64 
65 #include "behaviortree_cpp/bt_factory.h"
66 BT_REGISTER_NODES(factory)
67 {
68  factory.registerNodeType<nav2_behavior_tree::IsBatteryChargingCondition>("IsBatteryCharging");
69 }
A BT::ConditionNode that listens to a battery topic and returns SUCCESS when battery is charging and ...
BT::NodeStatus tick() override
The main override required by a BT action.