def talker():
pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
# rate = rospy.Rate(10)
# hello_str = "hello world"
# rospy.loginfo(hello_str)
# pub.publish(hello_str)
# rospy.spin()
# exit(0)
python类init_node()的实例源码
def run_driver():
# init moveit commander
moveit_commander.roscpp_initialize(sys.argv)
# specify move group
group = moveit_commander.MoveGroupCommander("arm")
# init ros node
rospy.init_node('real_servo_driver', anonymous=True)
print "============ Waiting for RVIZ..."
rospy.sleep(2)
# move grasper to init position
init_position(group)
# set ros publisher rate, 10hz = 10 seconds for a circle
rate = rospy.Rate(50)
while True:
group.set_random_target()
plan_msg = group.plan()
group.execute(plan_msg=plan_msg, wait=False)
rospy.sleep(5)
if is_exit:
break
# shutdown moveit commander
moveit_commander.roscpp_shutdown()
def main():
rospy.init_node("whatsapp_service")
cred = credentials.WHATSAPP
stackBuilder = YowStackBuilder()
stack = (stackBuilder
.pushDefaultLayers(True)
.push(AideRosLayer)
.build())
loginfo("Stack built...")
stack.setCredentials(cred)
stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) # sending the connect signal
loginfo("Connected...")
atexit.register(lambda: stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_DISCONNECT)))
th = threading.Thread(target=stack.loop)
th.daemon = True
th.start()
loginfo("Running in background.")
loginfo("All done. spinning.")
while not rospy.is_shutdown():
rospy.spin()
def main():
rospy.init_node("actions")
loginfo("Creating action handler...")
action_handler = ActionHandler()
loginfo("Registering services...")
get_service_handler(CallFunction).register_service(
lambda func_name, kwargs: action_handler.call_func(func_name, **json.loads(kwargs))
)
rospy.Subscriber("/aide/update_apis", String, lambda x: action_handler.reload_api_references(x.data))
get_service_handler(GetActionProvider).register_service(lambda name: action_handler.get_action_provider(name) or ())
get_service_handler(GetAllActionProviders).register_service(action_handler.get_all_action_providers)
get_service_handler(AddActionProvider).register_service(action_handler.add_action_provider)
get_service_handler(DeleteActionProvider).register_service(action_handler.remove_action_provider)
loginfo("Registered services. Spinning.")
rospy.spin()
def main():
rospy.init_node("api_handler")
loginfo("Creating api handler...")
notify_publisher = rospy.Publisher("/aide/update_apis", String, queue_size=50)
api = ApiHandler(lambda x: notify_publisher.publish(x))
loginfo("Registering services...")
get_service_handler(GetApi).register_service(lambda **args: api.get_api(**args) or ())
get_service_handler(GetAllApis).register_service(api.get_all_apis)
get_service_handler(AddApi).register_service(api.add_api)
get_service_handler(DeleteApi).register_service(api.remove_api)
loginfo("Registered services. Spinning.")
rospy.spin()
def init(self):
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((250, 250))
rospy.init_node('highway_teleop')
self.rate = rospy.Rate(rospy.get_param('~hz', 10))
self.acc = rospy.get_param('~acc', 5)
self.yaw = rospy.get_param('~yaw', 0)
self.robot_pub = rospy.Publisher('robot_0/cmd_vel', Twist, queue_size=1)
print "Usage: \n \
up arrow: accelerate \n \
down arrow: decelerate \n \
left arrow: turn left \n \
right arrow: turn right"
def init(self):
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((250, 250))
rospy.init_node('teleop')
self.rate = rospy.Rate(rospy.get_param('~hz', 20))
self.acc = rospy.get_param('~acc', 1)
self.yaw = rospy.get_param('~yaw', 0.25)
self.robot_pub = rospy.Publisher('control_command', controlCommand, queue_size=1)
self.path_record_pub = rospy.Publisher('record_state', \
RecordState, queue_size=1)
self.highway_game_start_pub = rospy.Publisher('highway_game_start', RecordState, queue_size=1)
print "Usage: \n \
up arrow: accelerate \n \
down arrow: decelerate \n \
left arrow: turn left \n \
right arrow: turn right"
def main():
rospy.init_node("listener")
sub = rospy.Subscriber("/chatter_topic", String, callback)
rospy.spin()
publish_calib_file.py 文件源码
项目:camera_calibration_frontend
作者: groundmelon
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def main(args):
rospy.init_node("publish_calib_file", args)
files = glob.glob("left-*.png");
files.sort()
print("All {} files".format(len(files)))
image_pub = rospy.Publisher("image",Image, queue_size=10)
bridge = CvBridge();
for f in files:
if rospy.is_shutdown():
break
raw_input("Publish {}?".format(f))
img = cv2.imread(f, 0)
image_pub.publish(bridge.cv2_to_imgmsg(img, "mono8"))
def main():
from optparse import OptionParser
rospy.init_node('cameracheck')
parser = OptionParser()
parser.add_option("-s", "--size", default="8x6", help="specify chessboard size as nxm [default: %default]")
parser.add_option("-q", "--square", default=".108", help="specify chessboard square size in meters [default: %default]")
options, args = parser.parse_args()
size = tuple([int(c) for c in options.size.split('x')])
dim = float(options.square)
CameraCheckerNode(size, dim)
rospy.spin()
def main():
rospy.init_node('easy_handeye')
while rospy.get_time() == 0.0:
pass
print('Handeye Calibration Commander')
print('connecting to: {}'.format((rospy.get_namespace().strip('/'))))
cmder = HandeyeCalibrationCommander()
if cmder.client.eye_on_hand:
print('eye-on-hand calibration')
print('robot effector frame: {}'.format(cmder.client.robot_effector_frame))
else:
print('eye-on-base calibration')
print('robot base frame: {}'.format(cmder.client.robot_base_frame))
print('tracking base frame: {}'.format(cmder.client.tracking_base_frame))
print('tracking target frame: {}'.format(cmder.client.tracking_marker_frame))
cmder.spin_interactive()
def main():
rospy.init_node('easy_handeye')
while rospy.get_time() == 0.0:
pass
cw = HandeyeServer()
rospy.spin()
def main():
rgb_object_detection = RGBObjectDetection()
rospy.init_node('rgb_object_detection', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
def main():
store_data = StoreData()
rospy.init_node('store_data', anonymous=True)
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
def main():
"""SDK Navigator Example
Demonstrates Navigator by echoing input values from wheels and
buttons.
Uses the intera_interface.Navigator class to demonstrate an
example of using the register_callback feature.
Shows Navigator input of the arm for 10 seconds.
"""
arg_fmt = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(formatter_class=arg_fmt)
parser.add_argument(
"-n", "--navigator", dest="nav_name", default="right",
choices=["right", "head"],
help='Navigator on which to run example'
)
args = parser.parse_args(rospy.myargv()[1:])
rospy.init_node('sdk_navigator', anonymous=True)
echo_input(args.nav_name)
return 0
def main():
"""Intera RSDK Joint Velocity Example: Wobbler
Commands joint velocities of randomly parameterized cosine waves
to each joint. Demonstrates Joint Velocity Control Mode.
"""
arg_fmt = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(formatter_class=arg_fmt,
description=main.__doc__)
parser.parse_args(rospy.myargv()[1:])
print("Initializing node... ")
rospy.init_node("rsdk_joint_velocity_wobbler")
wobbler = Wobbler()
rospy.on_shutdown(wobbler.clean_shutdown)
wobbler.wobble()
print("Done.")
def main():
"""RSDK Inverse Kinematics Example
A simple example of using the Rethink Inverse Kinematics
Service which returns the joint angles and validity for
a requested Cartesian Pose.
Run this example, the example will use the default limb
and call the Service with a sample Cartesian
Pose, pre-defined in the example code, printing the
response of whether a valid joint solution was found,
and if so, the corresponding joint angles.
"""
rospy.init_node("rsdk_ik_service_client")
if ik_service_client():
rospy.loginfo("Simple IK call passed!")
else:
rospy.logerr("Simple IK call FAILED")
if ik_service_client(use_advanced_options=True):
rospy.loginfo("Advanced IK call passed!")
else:
rospy.logerr("Advanced IK call FAILED")
def main():
"""RSDK Forward Kinematics Example
A simple example of using the Rethink Forward Kinematics
Service which returns the Cartesian Pose based on the input joint angles.
Run this example, the example will use the default limb
and call the Service with a sample Joint Position,
pre-defined in the example code, printing the
response of whether a valid Cartesian solution was found,
and if so, the corresponding Cartesian pose.
"""
rospy.init_node("rsdk_fk_service_client")
if fk_service_client():
rospy.loginfo("Simple FK call passed!")
else:
rospy.logerr("Simple FK call FAILED")
def main():
"""RSDK Head Example: Wobbler
Nods the head and pans side-to-side towards random angles.
Demonstrates the use of the intera_interface.Head class.
"""
arg_fmt = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(formatter_class=arg_fmt,
description=main.__doc__)
parser.parse_args(rospy.myargv()[1:])
print("Initializing node... ")
rospy.init_node("rsdk_head_wobbler")
wobbler = Wobbler()
rospy.on_shutdown(wobbler.clean_shutdown)
print("Wobbling... ")
wobbler.wobble()
print("Done.")
joint_trajectory_action_server.py 文件源码
项目:intera_sdk
作者: RethinkRobotics
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def start_server(limb, rate, mode, valid_limbs):
rospy.loginfo("Initializing node... ")
rospy.init_node("sdk_{0}_joint_trajectory_action_server{1}".format(
mode, "" if limb == 'all_limbs' else "_" + limb,))
rospy.loginfo("Initializing joint trajectory action server...")
robot_name = intera_interface.RobotParams().get_robot_name().lower().capitalize()
config_module = "intera_interface.cfg"
if mode == 'velocity':
config_name = ''.join([robot_name,"VelocityJointTrajectoryActionServerConfig"])
elif mode == 'position':
config_name = ''.join([robot_name,"PositionJointTrajectoryActionServerConfig"])
else:
config_name = ''.join([robot_name,"PositionFFJointTrajectoryActionServerConfig"])
cfg = importlib.import_module('.'.join([config_module,config_name]))
dyn_cfg_srv = Server(cfg, lambda config, level: config)
jtas = []
if limb == 'all_limbs':
for current_limb in valid_limbs:
jtas.append(JointTrajectoryActionServer(current_limb, dyn_cfg_srv,
rate, mode))
else:
jtas.append(JointTrajectoryActionServer(limb, dyn_cfg_srv, rate, mode))
def cleanup():
for j in jtas:
j.clean_shutdown()
rospy.on_shutdown(cleanup)
rospy.loginfo("Joint Trajectory Action Server Running. Ctrl-c to quit")
rospy.spin()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--timeout", type=lambda t:abs(float(t)),
default=60.0, help="[in seconds] Time to wait for joints to home")
parser.add_argument("-m", "--mode", type=str.upper, default="AUTO",
choices=['AUTO', 'MANUAL'], help="Mode to home the robot's joints")
enable_parser = parser.add_mutually_exclusive_group(required=False)
enable_parser.add_argument("-e", "--enable", action='store_true', dest='enable',
help="Try to enable the robot before homing.")
enable_parser.add_argument("-n", "--no-enable", action='store_false', dest='enable',
help="Avoid trying to enable the robot before homing.")
enable_parser.set_defaults(enable=True)
args = parser.parse_args(rospy.myargv()[1:])
rospy.init_node('home_joints_node')
if args.enable:
rs = intera_interface.RobotEnable(CHECK_VERSION)
rs.enable()
cmd_mode = HomingCommand.MANUAL if args.mode == 'MANUAL' else HomingCommand.AUTO
rospy.loginfo("Homing joints in '{0}' mode".format(args.mode.capitalize()))
home_jnts = HomeJoints()
state = home_jnts.home_robot(mode=cmd_mode, timeout=args.timeout)
rospy.loginfo("{0} in homing the robot's joints".format("Succeeded" if state else "Failed"))
def start():
global left_motor_pub,right_motor_pub
# publishing to "turtle1/cmd_vel" to control turtle1
global pub
pub = rospy.Publisher('turtle1/cmd_vel', Twist)
left_motor_pub = rospy.Publisher('/left_motor', std_msgs.msg.Int32, queue_size=10)
right_motor_pub = rospy.Publisher('/right_motor', std_msgs.msg.Int32, queue_size=10)
# subscribed to joystick inputs on topic "joy"
rospy.Subscriber("joy", Joy, callback)
# starts the node
rospy.init_node('Joy2Turtle')
rospy.spin()
def start():
global left_motor_pub,right_motor_pub
# publishing to "turtle1/cmd_vel" to control turtle1
global pub
pub = rospy.Publisher('turtle1/cmd_vel', Twist)
left_motor_pub = rospy.Publisher('/left_motor', std_msgs.msg.Int32, queue_size=10)
right_motor_pub = rospy.Publisher('/right_motor', std_msgs.msg.Int32, queue_size=10)
# subscribed to joystick inputs on topic "joy"
rospy.Subscriber("joy", Joy, callback)
# starts the node
rospy.init_node('Joy2Turtle')
rospy.spin()
def start():
global left_motor_pub,right_motor_pub
# publishing to "turtle1/cmd_vel" to control turtle1
global pub
pub = rospy.Publisher('turtle1/cmd_vel', Twist)
left_motor_pub = rospy.Publisher('/left_motor', std_msgs.msg.Int32, queue_size=10)
right_motor_pub = rospy.Publisher('/right_motor', std_msgs.msg.Int32, queue_size=10)
# subscribed to joystick inputs on topic "joy"
rospy.Subscriber("joy", Joy, callback)
# starts the node
rospy.init_node('Joy2Turtle')
rospy.spin()
def start():
global left_motor_pub,right_motor_pub
# publishing to "turtle1/cmd_vel" to control turtle1
global pub
pub = rospy.Publisher('turtle1/cmd_vel', Twist)
left_motor_pub = rospy.Publisher('/left_motor', std_msgs.msg.Int32, queue_size=10)
right_motor_pub = rospy.Publisher('/right_motor', std_msgs.msg.Int32, queue_size=10)
# subscribed to joystick inputs on topic "joy"
rospy.Subscriber("joy", Joy, callback)
# starts the node
rospy.init_node('Joy2Turtle')
rospy.spin()
avoid_runaway_suppressor.py 文件源码
项目:micros_mars_task_alloc
作者: liminglong
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def avoid_runaway_suppressor():
rospy.init_node('avoid_runaway_suppressor')
rospy.Subscriber("/avoid/suppressor/heading", Heading, avoid_headingCB)
rospy.Subscriber("/runaway/suppressor/heading", Heading, runaway_headingCB)
rospy.spin()
def start_detect(self):
FunctionUnit.init_node(self)
#print 'hello 1'
#print self._receive_topic
receive_1 = FunctionUnit.create_receive(self, self._receive_topic, Image, self.receive_1_cb)
#print 'hello 2'
FunctionUnit.spin(self)
def run(self):
rospy.init_node('hello2')
print 'hello2'
rospy.spin()
def __init__(self):
rospy.init_node('gaze', anonymous=False)
self.lock = threading.RLock()
with self.lock:
self.current_state = GazeState.IDLE
self.last_state = self.current_state
# Initialize Variables
self.glance_timeout = 0
self.glance_timecount = 0
self.glance_played = False
self.idle_timeout = 0
self.idle_timecount = 0
self.idle_played = False
rospy.loginfo('\033[92m[%s]\033[0m waiting for bringup social_mind...'%rospy.get_name())
rospy.wait_for_service('environmental_memory/read_data')
rospy.wait_for_service('social_events_memory/read_data')
self.rd_memory = {}
self.rd_memory['environmental_memory'] = rospy.ServiceProxy('environmental_memory/read_data', ReadData)
self.rd_memory['social_events_memory'] = rospy.ServiceProxy('social_events_memory/read_data', ReadData)
rospy.Subscriber('raising_events', RaisingEvents, self.handle_raising_events)
rospy.Subscriber('gaze_focusing', String, self.handle_gaze_focusing)
self.pub_gaze_cmd = rospy.Publisher('gaze_command', GazeCommand, queue_size=10)
self.pub_viz_gaze_cmd = rospy.Publisher('visualization_gaze_cmd', PointStamped, queue_size=10)
rospy.Timer(rospy.Duration(GAZE_CONTROLLER_PERIOD), self.handle_gaze_controller)
rospy.loginfo('\033[92m[%s]\033[0m initialized...'%rospy.get_name())
rospy.spin()
def __init__(self):
rospy.init_node('fake_renderer', anonymous=True)
try:
topic_name = rospy.get_param('~action_name')
except KeyError as e:
print('[ERROR] Needed parameter for (topic_name)...')
quit()
if 'render_gesture' in rospy.get_name():
self.GetInstalledGesturesService = rospy.Service(
"get_installed_gestures",
GetInstalledGestures,
self.handle_get_installed_gestures
)
self.motion_list = {
'neutral': ['neutral_motion1'],
'encourge': ['encourge_motion1'],
'attention': ['attention_motion1'],
'consolation': ['consolation_motion1'],
'greeting': ['greeting_motion1'],
'waiting': ['waiting_motion1'],
'advice': ['advice_motion1'],
'praise': ['praise_motion1'],
'command': ['command_motion1'],
}
self.server = actionlib.SimpleActionServer(
topic_name, RenderItemAction, self.execute_callback, False)
self.server.start()
rospy.loginfo('[%s] initialized...' % rospy.get_name())
rospy.spin()