|
| 1 | +import math |
| 2 | + |
| 3 | +from boat_interfaces.msg import BoatHeading |
| 4 | +import rclpy |
| 5 | +from geometry_msgs.msg import PoseWithCovarianceStamped |
| 6 | +from geometry_msgs.msg import Quaternion |
| 7 | +from rclpy.node import Node |
| 8 | +from sensor_msgs.msg import NavSatFix |
| 9 | + |
| 10 | + |
| 11 | +def heading_to_quaternion(heading_deg): |
| 12 | + # Convert compass heading from degrees to radians |
| 13 | + heading_rad = math.radians(heading_deg) |
| 14 | + |
| 15 | + # Calculate quaternion components |
| 16 | + qx = 0.0 |
| 17 | + qy = 0.0 |
| 18 | + qz = math.sin(heading_rad / 2) |
| 19 | + qw = math.cos(heading_rad / 2) |
| 20 | + |
| 21 | + # Return quaternion |
| 22 | + return Quaternion(x=qx, y=qy, z=qz, w=qw) |
| 23 | + |
| 24 | + |
| 25 | +class SensorFusionNode(Node): |
| 26 | + |
| 27 | + def __init__(self): |
| 28 | + super().__init__('sensor_fusion_node') |
| 29 | + self.gps_sub = self.create_subscription(NavSatFix, '/fix', self.gps_callback, 10) |
| 30 | + self.compass_sub = self.create_subscription(BoatHeading, '/compass', self.compass_callback, 10) |
| 31 | + self.pose_pub = self.create_publisher(PoseWithCovarianceStamped, '/amcl_pose', 10) |
| 32 | + self.current_lat = None |
| 33 | + self.current_lon = None |
| 34 | + self.current_heading = None # Heading from your custom compass |
| 35 | + |
| 36 | + def gps_callback(self, msg): |
| 37 | + self.current_lat = msg.latitude |
| 38 | + self.current_lon = msg.longitude |
| 39 | + self.publish_pose() |
| 40 | + |
| 41 | + def compass_callback(self, heading): |
| 42 | + self.current_heading = heading |
| 43 | + self.publish_pose() |
| 44 | + |
| 45 | + def publish_pose(self): |
| 46 | + if self.current_lat is not None and self.current_lon is not None and self.current_heading is not None: |
| 47 | + pose_msg = PoseWithCovarianceStamped() |
| 48 | + pose_msg.header.stamp = self.get_clock().now().to_msg() |
| 49 | + pose_msg.header.frame_id = 'odom' |
| 50 | + |
| 51 | + # Convert GPS to XY coordinates (this will need to be done with a transform library) |
| 52 | + # Simplified; typically requires a transform |
| 53 | + pose_msg.pose.pose.position.x = self.current_lon |
| 54 | + pose_msg.pose.pose.position.y = self.current_lat |
| 55 | + |
| 56 | + # Convert compass heading to quaternion for orientation |
| 57 | + pose_msg.pose.pose.orientation = heading_to_quaternion(self.current_heading.heading) |
| 58 | + |
| 59 | + self.pose_pub.publish(pose_msg) |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + rclpy.init() |
| 64 | + node = SensorFusionNode() |
| 65 | + rclpy.spin(node) |
| 66 | + node.destroy_node() |
| 67 | + rclpy.shutdown() |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + main() |
0 commit comments