PX4 simulation stack
offboard_sample.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import rospy
4 
5 from geometry_msgs.msg import PoseStamped
6 from mavros_msgs.msg import State
7 from mavros_msgs.srv import CommandBool, CommandBoolRequest
8 from mavros_msgs.srv import SetMode, SetModeRequest
9 
10 current_state = State()
11 def state_cb(msg):
12  global current_state
13  current_state = msg
14 
16 
17  rospy.init_node("offb_node")
18  r = rospy.Rate(20)
19 
20  rospy.Subscriber("mavros/state", State, state_cb)
21  local_pos_pub = rospy.Publisher("mavros/setpoint_position/local",
22  PoseStamped,
23  queue_size=1000)
24  arming_client = rospy.ServiceProxy("mavros/cmd/arming", CommandBool)
25  set_mode_client = rospy.ServiceProxy("mavros/set_mode", SetMode)
26 
27  while not rospy.is_shutdown() and not current_state.connected:
28  r.sleep()
29 
30  pose = PoseStamped()
31  pose.pose.position.x = 0
32  pose.pose.position.y = 0
33  pose.pose.position.z = 2
34 
35  for i in range(100):
36  local_pos_pub.publish(pose)
37  r.sleep()
38 
39  if rospy.is_shutdown():
40  break
41 
42  offb_set_mode = SetModeRequest()
43  offb_set_mode.custom_mode = "OFFBOARD"
44 
45  arm_cmd = CommandBoolRequest()
46  arm_cmd.value = True
47 
48  last_request = rospy.Time.now()
49 
50  while not rospy.is_shutdown():
51  if current_state.mode != "OFFBOARD" \
52  and (rospy.Time.now() - last_request > rospy.Duration(5)):
53 
54  try:
55  offb_set_mode_resp = set_mode_client(offb_set_mode)
56  if offb_set_mode_resp.mode_sent:
57  rospy.loginfo("Offboard enabled")
58  except rospy.ServiceException as e:
59  rospy.logwarn(e)
60 
61  last_request = rospy.Time.now()
62 
63  else:
64  if not current_state.armed \
65  and (rospy.Time.now() - last_request > rospy.Duration(5)):
66 
67  try:
68  arm_cmd_resp = arming_client(arm_cmd)
69  if arm_cmd_resp.success:
70  rospy.loginfo("Vehicle armed")
71  except rospy.ServiceException as e:
72  rospy.logwarn(e)
73 
74  last_request = rospy.Time.now()
75 
76  local_pos_pub.publish(pose)
77  r.sleep()
78 
79 if __name__ == "__main__":
80  try:
82  except rospy.ROSInterruptException:
83  pass