Nav2 Navigation Stack - kilted  kilted
ROS 2 Navigation Stack
utils.py
1 #! /usr/bin/env python3
2 # Copyright 2024 Open Navigation LLC
3 # Copyright 2024 Stevedan Ogochukwu Omodolor Omodia
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 """General utility functions."""
18 
19 import math
20 import os
21 import signal
22 import subprocess
23 
24 from geometry_msgs.msg import Quaternion
25 
26 
27 def find_os_processes(name: str) -> list[tuple[str, str]]:
28  """Find all the processes that are running gz sim."""
29  ps_output = subprocess.check_output(['ps', 'aux'], text=True)
30  ps_lines = ps_output.split('\n')
31  gz_sim_processes = []
32  for line in ps_lines:
33  if name in line:
34  columns = line.split()
35  pid = columns[1]
36  command = ' '.join(columns[10:])
37  if command.startswith(name):
38  gz_sim_processes.append((pid, command))
39  return gz_sim_processes
40 
41 
42 def kill_process(pid: str) -> None:
43  """Kill a process with a given PID."""
44  try:
45  os.kill(int(pid), signal.SIGKILL)
46  print(f'Successfully killed process with PID: {pid}')
47  except Exception as e:
48  print(f'Failed to kill process with PID: {pid}. Error: {e}')
49 
50 
51 def kill_os_processes(name: str) -> None:
52  """Kill all processes that are running with name."""
53  processes = find_os_processes(name)
54  if processes:
55  for pid, _ in processes:
56  kill_process(pid)
57  else:
58  print(f'No processes found starting with {name}')
59 
60 
61 def euler_to_quaternion(
62  roll: float = 0.0, pitch: float = 0.0,
63  yaw: float = 0.0) -> Quaternion:
64  """Convert euler angles to quaternion."""
65  cy = math.cos(yaw * 0.5)
66  sy = math.sin(yaw * 0.5)
67  cp = math.cos(pitch * 0.5)
68  sp = math.sin(pitch * 0.5)
69  cr = math.cos(roll * 0.5)
70  sr = math.sin(roll * 0.5)
71 
72  q = Quaternion()
73  q.w = cr * cp * cy + sr * sp * sy
74  q.x = sr * cp * cy - cr * sp * sy
75  q.y = cr * sp * cy + sr * cp * sy
76  q.z = cr * cp * sy - sr * sp * cy
77 
78  return q