Python rospy.Service() Examples

The following are 30 code examples of rospy.Service(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rospy , or try the search function .
Example #1
Source File: amazonpolly.py    From tts-ros1 with Apache License 2.0 8 votes vote down vote up
def start(self, node_name='polly_node', service_name='polly'):
        """The entry point of a ROS service node.

        Details of the service API can be found in Polly.srv.

        :param node_name: name of ROS node
        :param service_name:  name of ROS service
        :return: it doesn't return
        """
        rospy.init_node(node_name)

        service = rospy.Service(service_name, Polly, self._node_request_handler)

        rospy.loginfo('polly running: {}'.format(service.uri))

        rospy.spin() 
Example #2
Source File: proxy.py    From Cloudroid with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def run(self):
        self.service_type, self.service_args = wait_service_ready(self.service_name, self.url)
        if not self.service_type:
            rospy.logerr('Type of service %s are not equal in the remote and local sides', self.service_type)
            return
        
        service_type_module, service_type_name = tuple(self.service_type.split('/'))
        try:       
            roslib.load_manifest(service_type_module)
            msg_module = import_module(service_type_module + '.srv')
            self.srvtype = getattr(msg_module, service_type_name)
            
            if self.test:
                self.caller = rospy.Service(self.service_name + '_rb', self.srvtype, self.callback)#, self.queue_size)
            else: 
                self.caller = rospy.Service(self.service_name, self.srvtype, self.callback)#, self.queue_size)
                                      
            self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
            rospy.loginfo('Create connection to Rosbridge server %s for calling service %s successfully', self.url, self.service_name)
            self.ws.run_forever()
        except ResourceNotFound, e:
            rospy.logerr('Proxy for service %s init falied. Reason: Could not find the required resource: %s', self.service_name, str(e)) 
Example #3
Source File: tool_controller.py    From niryo_one_ros with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, ros_command_interface):

        self.ros_command_interface = ros_command_interface

        self.server = actionlib.SimpleActionServer(
            'niryo_one/tool_action', ToolAction, self.tool_on_goal, False)

        self.change_tool_server = rospy.Service(
            'niryo_one/change_tool', SetInt, self.callback_change_tool)

        self.current_tool_id_publisher = rospy.Publisher(
            '/niryo_one/current_tool_id', Int32, queue_size=1)

        rospy.Timer(rospy.Duration(1 / 1.0), self.publish_current_tool_id)

        self.current_tool = None
        self.available_tools = None
        self.command_list = None
        self.create_tools() 
Example #4
Source File: handeye_server.py    From easy_handeye with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.calibrator = HandeyeCalibrator()

        self.get_sample_list_service = rospy.Service(hec.GET_SAMPLE_LIST_TOPIC,
                                                     hec.srv.TakeSample, self.get_sample_lists)
        self.take_sample_service = rospy.Service(hec.TAKE_SAMPLE_TOPIC,
                                                 hec.srv.TakeSample, self.take_sample)
        self.remove_sample_service = rospy.Service(hec.REMOVE_SAMPLE_TOPIC,
                                                   hec.srv.RemoveSample, self.remove_sample)
        self.compute_calibration_service = rospy.Service(hec.COMPUTE_CALIBRATION_TOPIC,
                                                         hec.srv.ComputeCalibration, self.compute_calibration)
        self.save_calibration_service = rospy.Service(hec.SAVE_CALIBRATION_TOPIC,
                                                      std_srvs.srv.Empty, self.save_calibration)

        # Useful for secondary input sources (e.g. programmable buttons on robot)
        self.take_sample_topic = rospy.Subscriber(hec.TAKE_SAMPLE_TOPIC,
                                                  std_msgs.msg.Empty, self.take_sample)
        self.compute_calibration_topic = rospy.Subscriber(hec.REMOVE_SAMPLE_TOPIC,
                                                          std_msgs.msg.Empty, self.remove_last_sample)  # TODO: normalize

        self.last_calibration = None 
Example #5
Source File: niryo_one_ros_setup.py    From niryo_one_ros with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.process_list = []
        self.process_config = rospy.get_param("~processes")
        self.create_processes()

        rospy.on_shutdown(self.clean_ros_processes)

        self.process_state_publish_rate = rospy.get_param("~process_state_publish_rate")

        self.process_state_publisher = rospy.Publisher(
            '/niryo_one/rpi/process_state', ProcessState, queue_size=1)

        rospy.Timer(rospy.Duration(1.0 / self.process_state_publish_rate), self.publish_process_state)

        self.manage_process_server = rospy.Service(
            '/niryo_one/rpi/manage_process', ManageProcess, self.callback_manage_process)

        self.start_init_processes()
        # self.start_all_processes() 
Example #6
Source File: nao_alife.py    From nao_robot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__( self ):

        #Initialisation
        NaoqiNode.__init__( self, self.NODE_NAME )
        if self.get_version() < distutils.version.LooseVersion('2.0'):
            rospy.logwarn("{} is only available on NaoQi version 2.0 or higher, your version is {}".format(self.NODE_NAME, self.get_version()))
            exit(1)

        #Proxy to interface with LEDs
        self.proxy = self.get_proxy( "ALAutonomousLife" )

        # Register ROS services
        self.disabled_srv = rospy.Service("~disabled", Empty, self.disabled )
        self.solitary_srv = rospy.Service("~solitary", Empty, self.solitary )
        self.interactive_srv = rospy.Service("~interactive", Empty, self.interactive )
        self.safeguard_srv = rospy.Service("~safeguard", Empty, self.safeguard ) 
Example #7
Source File: digital_io_panel.py    From niryo_one_ros with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        lock = Lock()

        self.publish_io_state_frequency = rospy.get_param("~publish_io_state_frequency")
        self.digitalIOs = [DigitalPin(lock, GPIO_1_A, GPIO_1_A_NAME), DigitalPin(lock, GPIO_1_B, GPIO_1_B_NAME),
                           DigitalPin(lock, GPIO_1_C, GPIO_1_C_NAME),
                           DigitalPin(lock, GPIO_2_A, GPIO_2_A_NAME), DigitalPin(lock, GPIO_2_B, GPIO_2_B_NAME),
                           DigitalPin(lock, GPIO_2_C, GPIO_2_C_NAME),
                           DigitalPin(lock, SW_1, SW_1_NAME, mode=GPIO.OUT),
                           DigitalPin(lock, SW_2, SW_2_NAME, mode=GPIO.OUT)]

        self.digital_io_publisher = rospy.Publisher('niryo_one/rpi/digital_io_state', DigitalIOState, queue_size=1)
        rospy.Timer(rospy.Duration(1.0 / self.publish_io_state_frequency), self.publish_io_state)

        self.get_io_server = rospy.Service('niryo_one/rpi/get_digital_io', GetDigitalIO, self.callback_get_io)
        self.set_io_mode_server = rospy.Service('niryo_one/rpi/set_digital_io_mode', SetDigitalIO,
                                                self.callback_set_io_mode)
        self.set_io_state_server = rospy.Service('niryo_one/rpi/set_digital_io_state', SetDigitalIO,
                                                 self.callback_set_io_state) 
Example #8
Source File: led_manager.py    From niryo_one_ros with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        # Set warning false, and don't cleanup LED GPIO after exit
        # So the LED will be red only after the Rpi is shutdown
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        GPIO.setup(LED_GPIO_R, GPIO.OUT)
        GPIO.setup(LED_GPIO_G, GPIO.OUT)
        GPIO.setup(LED_GPIO_B, GPIO.OUT)

        rospy.sleep(0.1)
        self.state = LedState.OK
        self.set_led_from_state(dxl_leds=True)

        self.set_led_state_server = rospy.Service('/niryo_one/rpi/set_led_state',
                                                  SetInt, self.callback_set_led_state)

        # Subscribe to hotspot and hardware status. Those values will override standard states
        self.hotspot_state_subscriber = rospy.Subscriber('/niryo_one/wifi/hotspot',
                                                         Bool, self.callback_hotspot_state)

        self.hardware_status_subscriber = rospy.Subscriber('/niryo_one/hardware_status',
                                                           HardwareStatus, self.callback_hardware_status)

        rospy.loginfo('LED manager has been started.') 
Example #9
Source File: qsrlib_ros_server.py    From strands_qsr_lib with MIT License 6 votes vote down vote up
def __init__(self, node_name="qsr_lib"):
        """Constructor.

        :param node_name: The QSRlib ROS server node name.
        :type node_name: str
        """
        self.qsrlib = QSRlib()
        """:class:`QSRlib <qsrlib.qsrlib.QSRlib>`: QSRlib main object."""

        self.node_name = node_name
        """str: QSRlib ROS server node name."""

        rospy.init_node(self.node_name)

        self.service_topic_names = {"request": self.node_name+"/request"}
        """dict: Holds the service topic names."""

        self.srv_qsrs_request = rospy.Service(self.service_topic_names["request"], RequestQSRs, self.handle_request_qsrs)
        """rospy.impl.tcpros_service.Service: QSRlib ROS service."""

        rospy.loginfo("QSRlib_ROS_Server up and running, listening to: %s" % self.service_topic_names["request"]) 
Example #10
Source File: joint_controller.py    From ROS-Robotics-Projects-SecondEdition with MIT License 6 votes vote down vote up
def __init__(self, dxl_io, controller_namespace, port_namespace):
        self.running = False
        self.dxl_io = dxl_io
        self.controller_namespace = controller_namespace
        self.port_namespace = port_namespace
        self.joint_name = rospy.get_param(self.controller_namespace + '/joint_name')
        self.joint_speed = rospy.get_param(self.controller_namespace + '/joint_speed', 1.0)
        self.compliance_slope = rospy.get_param(self.controller_namespace + '/joint_compliance_slope', None)
        self.compliance_margin = rospy.get_param(self.controller_namespace + '/joint_compliance_margin', None)
        self.compliance_punch = rospy.get_param(self.controller_namespace + '/joint_compliance_punch', None)
        self.torque_limit = rospy.get_param(self.controller_namespace + '/joint_torque_limit', None)
        
        self.__ensure_limits()
        
        self.speed_service = rospy.Service(self.controller_namespace + '/set_speed', SetSpeed, self.process_set_speed)
        self.torque_service = rospy.Service(self.controller_namespace + '/torque_enable', TorqueEnable, self.process_torque_enable)
        self.compliance_slope_service = rospy.Service(self.controller_namespace + '/set_compliance_slope', SetComplianceSlope, self.process_set_compliance_slope)
        self.compliance_marigin_service = rospy.Service(self.controller_namespace + '/set_compliance_margin', SetComplianceMargin, self.process_set_compliance_margin)
        self.compliance_punch_service = rospy.Service(self.controller_namespace + '/set_compliance_punch', SetCompliancePunch, self.process_set_compliance_punch)
        self.torque_limit_service = rospy.Service(self.controller_namespace + '/set_torque_limit', SetTorqueLimit, self.process_set_torque_limit) 
Example #11
Source File: ggcnn_service.py    From mvp_grasp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        # Get the camera parameters
        cam_info_topic = rospy.get_param('~camera/info_topic')
        camera_info_msg = rospy.wait_for_message(cam_info_topic, CameraInfo)
        self.cam_K = np.array(camera_info_msg.K).reshape((3, 3))

        self.img_pub = rospy.Publisher('~visualisation', Image, queue_size=1)
        rospy.Service('~predict', GraspPrediction, self.compute_service_handler)

        self.base_frame = rospy.get_param('~camera/robot_base_frame')
        self.camera_frame = rospy.get_param('~camera/camera_frame')
        self.img_crop_size = rospy.get_param('~camera/crop_size')
        self.img_crop_y_offset = rospy.get_param('~camera/crop_y_offset')
        self.cam_fov = rospy.get_param('~camera/fov')

        self.counter = 0
        self.curr_depth_img = None
        self.curr_img_time = 0
        self.last_image_pose = None
        rospy.Subscriber(rospy.get_param('~camera/depth_topic'), Image, self._depth_img_callback, queue_size=1)

        self.waiting = False
        self.received = False 
Example #12
Source File: carla_ros_scenario_runner.py    From ros-bridge with MIT License 6 votes vote down vote up
def __init__(self, role_name, host, port, scenario_runner_path, wait_for_ego):
        """
        Constructor
        """
        self._status_publisher = rospy.Publisher(
            "/scenario_runner/status", CarlaScenarioRunnerStatus, queue_size=1, latch=True)
        self.scenario_runner_status_updated(ApplicationStatus.STOPPED)
        self._scenario_runner = ScenarioRunnerRunner(
            scenario_runner_path,
            host,
            port,
            wait_for_ego,
            self.scenario_runner_status_updated,
            self.scenario_runner_log)
        self._request_queue = queue.Queue()
        self._execute_scenario_service = rospy.Service(
            '/scenario_runner/execute_scenario', ExecuteScenario, self.execute_scenario) 
Example #13
Source File: service_server.py    From ros_book_programs with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def service_server():
    rospy.init_node('service_server')
    s = rospy.Service('call_me', Empty, handle_service)
    print "Ready to serve."
    rospy.spin() 
Example #14
Source File: qsr_prob_rep_ros_server.py    From strands_qsr_lib with MIT License 6 votes vote down vote up
def __init__(self, name):
        """
        :param name: The name of the node
        """
        rospy.logdebug( "[" + rospy.get_name() + "]: " + "Starting " )
        self._lib = ProbRepLib()
        self.services = {}
        for namespace, services in ServiceManager.available_services.items():
            # Automatically creating a service for all the entries in 'qsrrep_lib.rep_io.available_services'
            # Passing the key of the dict entry to the service to identify the right function to call
            for i, service in enumerate(services):
                # The outer lambda function creates a new scope for the inner lambda function
                # This is necessary to preserve the value of k, otherwise it will have the same value for all services
                # x will be substituded by the service request
                rospy.logdebug( "[" + rospy.get_name() + "]: " + "Creating service: ["+namespace+"]["+service+"]" )
                self.services[service] = rospy.Service("~"+namespace+"/"+service, QSRProbRep, (lambda a,b: lambda x: self.callback(x, a, b))(namespace,service))
                rospy.logdebug( "[" + rospy.get_name() + "]: " + "Created" )
        rospy.logdebug( "[" + rospy.get_name() + "]: " + "Done" ) 
Example #15
Source File: flipper.py    From uav_trajectory_optimizer_gurobi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        
        #self.sub_state = rospy.Subscriber('vicon', ViconState, self.state_cb)


        self.srv_flip = rospy.Service('window', Trigger, self.window_cb)
        self.srv_flip = rospy.Service('line', Trigger, self.line_cb)
        self.srv_flip = rospy.Service('flip_pitch', Trigger, self.flip_pitch_cb)
        self.srv_flip = rospy.Service('flip', Trigger, self.flip_cb)
        self.srv_flip = rospy.Service('flip_trans', Trigger, self.flip_trans_cb)

        #self.srv_takeoff = rospy.Service('takeoff', Trigger, self.takeoff_cb)

        # outer loop setpoints
        #self.pub_goal = rospy.Publisher('goal', QuadGoal, queue_size=1)

        self.pub_drone_markers=rospy.Publisher('snapshots', MarkerArray, queue_size=10)
        self.pub_window=rospy.Publisher('window', Marker, queue_size=10)

        # initialize members
        #self.state_msg = ViconState()

        # desired control rate
        self.dc = 0.01

        # motor spinup time, seconds
        self.spinup_secs = 0 
Example #16
Source File: nao_behaviors.py    From nao_robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__( self ):

        #Initialisation
        NaoqiNode.__init__( self, self.NODE_NAME )

        #We need this variable to be able to call stop behavior when preempted
        self.behavior = None
        self.lock = threading.RLock()

        #Proxy for listingBehaviors and stopping them
        self.behaviorProxy = self.get_proxy( "ALBehaviorManager" )

        # Register ROS services
        self.getInstalledBehaviorsService = rospy.Service(
            "get_installed_behaviors",
            GetInstalledBehaviors,
            self.getInstalledBehaviors
            )

        #Prepare and start actionlib server
        self.actionlibServer = actionlib.SimpleActionServer(
            "run_behavior",
            RunBehaviorAction,
            self.runBehavior,
            False
            )

        self.actionlibServer.register_preempt_callback( self.stopBehavior )

        self.actionlibServer.start() 
Example #17
Source File: mln_server.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, node_name="rosmln", service_name="mln_interface"):
        rospy.init_node(node_name)
        rospy.Service(service_name, MLNInterface, self.__handle_mln_query)
        rospy.loginfo("MLN is ready to be queried!")
        rospy.spin() 
Example #18
Source File: mln_server.py    From pracmln with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def mln_interface_server():
    rospy.init_node('rosmln')
    s = rospy.Service('mln_interface', MLNInterface, handle_mln_query)
    print "MLN is ready to be queried."
    rospy.spin() 
Example #19
Source File: kinematics.py    From pyrobot with MIT License 5 votes vote down vote up
def __init__(self):
        self.init_done = False
        rospy.init_node("pyrobot_kinematics")

        self.ik_srv = rospy.Service("pyrobot/ik", IkCommand, self.ik_server)
        self.fk_srv = rospy.Service("pyrobot/fk", FkCommand, self.fk_server)
        rospy.spin() 
Example #20
Source File: qsrlib_ros_server.py    From strands_qsr_lib with MIT License 5 votes vote down vote up
def handle_request_qsrs(self, req):
        """Service handler.

        :param req: QSRlib ROS request.
        :type req: qsr_lib.srv.RequestQSRsRequest
        :return: SRlib ROS response message.
        :rtype: qsr_lib.srv.RequestQSRsResponse
        """
        rospy.logdebug("Handling QSRs request made at %i.%i" % (req.header.stamp.secs, req.header.stamp.nsecs))
        req_msg = pickle.loads(req.data)
        qsrlib_res_msg = self.qsrlib.request_qsrs(req_msg)
        ros_res_msg = RequestQSRsResponse()
        ros_res_msg.header.stamp = rospy.get_rostime()
        ros_res_msg.data = pickle.dumps(qsrlib_res_msg)
        return ros_res_msg 
Example #21
Source File: manual.py    From image_recognition with MIT License 5 votes vote down vote up
def trigger_configuration(self):
        """
        Callback when the configuration button is clicked
        """

        srv_name, ok = QInputDialog.getText(self._widget, "Select service name", "Service name")
        if ok:
            self._create_service_server(srv_name) 
Example #22
Source File: manual.py    From image_recognition with MIT License 5 votes vote down vote up
def _create_service_server(self, srv_name):
        """
        Method that creates a service server for a Recognize.srv
        :param srv_name:
        """
        if self._srv:
            self._srv.shutdown()

        if srv_name:
            rospy.loginfo("Creating service '%s'" % srv_name)
            self._srv_name = srv_name
            self._srv = rospy.Service(srv_name, Recognize, self.recognize_srv_callback) 
Example #23
Source File: nao_footsteps.py    From nao_robot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        NaoqiNode.__init__(self, 'nao_footsteps')

        self.connectNaoQi()

        # initial stiffness (defaults to 0 so it doesn't strain the robot when
        # no teleoperation is running)
        # set to 1.0 if you want to control the robot immediately
        initStiffness = rospy.get_param('~init_stiffness', 0.0)

        # TODO: parameterize
        if initStiffness > 0.0 and initStiffness <= 1.0:
            self.motionProxy.stiffnessInterpolation('Body', initStiffness, 0.5)

        # last: ROS subscriptions (after all vars are initialized)
        rospy.Subscriber("footstep", StepTarget, self.handleStep, queue_size=50)

        # ROS services (blocking functions)
        self.stepToSrv = rospy.Service("footstep_srv", StepTargetService,
                                       self.handleStepSrv)
        self.clipSrv = rospy.Service("clip_footstep_srv", ClipFootstep,
                                     self.handleClipSrv)

    	# Initialize action server
        self.actionServer = actionlib.SimpleActionServer(
            "footsteps_execution",
            ExecFootstepsAction,
            execute_cb=self.footstepsExecutionCallback,
            auto_start=False)
        self.actionServer.start()

        rospy.loginfo("nao_footsteps initialized") 
Example #24
Source File: windOpenFoam.py    From usv_sim_lsa with Apache License 2.0 5 votes vote down vote up
def startRosService():
        s = rospy.Service('windCurrent', GetSpeed, handleWindCurrent)
        print "Ready to answer wind current. Wait full load before changing time" 
Example #25
Source File: manager.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def pause(self):
        if self.pause_srv is None:
            raise RuntimeError('Service Proxy not created! Is sim running?')
        self.pause_srv() 
Example #26
Source File: manager.py    From costar_plan with Apache License 2.0 5 votes vote down vote up
def resume(self):
        if self.unpause_srv is None:
            raise RuntimeError('Service Proxy not created! Is sim running?')
        self.publish_scene_srv()
        self.unpause_srv() 
Example #27
Source File: naoqi_background_movement.py    From naoqi_bridge with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        NaoqiNode.__init__(self, 'naoqi_background_movement')
        self.connectNaoQi()
        
        self.SetEnabledSrv = rospy.Service("background_movement/set_enabled", SetBool, self.handleSetEnabledSrv)
        self.IsEnabledSrv = rospy.Service("background_movement/is_enabled", Trigger, self.handleIsEnabledSrv)
        rospy.loginfo("naoqi_background_movement initialized") 
Example #28
Source File: naoqi_listening_movement.py    From naoqi_bridge with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        NaoqiNode.__init__(self, 'naoqi_listening_movement')
        self.connectNaoQi()
        
        self.SetEnabledSrv = rospy.Service("listening_movement/set_enabled", SetBool, self.handleSetEnabledSrv)
        self.IsEnabledSrv = rospy.Service("listening_movement/is_enabled", Trigger, self.handleIsEnabledSrv)
        rospy.loginfo("naoqi_listening_movement initialized") 
Example #29
Source File: naoqi_gaze_analysis.py    From naoqi_bridge with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        NaoqiNode.__init__(self, 'naoqi_gaze_analysis')
        self.connectNaoQi()
        self.setToleranceSrv = rospy.Service("set_gaze_analysis_tolerance", SetFloat, self.handleSetGazeAnalysisTolerance)
        self.getToleranceSrv = rospy.Service("get_gaze_analysis_tolerance", GetFloat, self.handleGetGazeAnalysisTolerance)
        rospy.loginfo("naoqi_gaze_analysis is initialized") 
Example #30
Source File: test_proxies.py    From flexbe_behavior_engine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_service_caller(self):
        t1 = '/service_1'
        rospy.Service(t1, Trigger, lambda r: (True, 'ok'))

        srv = ProxyServiceCaller({t1: Trigger})

        result = srv.call(t1, TriggerRequest())
        self.assertIsNotNone(result)
        self.assertTrue(result.success)
        self.assertEqual(result.message, 'ok')

        self.assertFalse(srv.is_available('/not_there'))
        srv = ProxyServiceCaller({'/invalid': Trigger}, wait_duration=.1)
        self.assertFalse(srv.is_available('/invalid'))