Python源码示例:rospy.Service()

示例1
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() 
示例2
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)) 
示例3
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() 
示例4
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() 
示例5
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) 
示例6
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.') 
示例7
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 
示例8
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" ) 
示例9
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"]) 
示例10
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 ) 
示例11
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 
示例12
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) 
示例13
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) 
示例14
def startRosService():
	rospy.Subscriber("waterCurrentTime", Int64, defineTime)
	preprocessDataset2()
        s = rospy.Service('waterCurrent', GetSpeed, handleWaterCurrent2)
        print "\nReady to answer water current.\n" 
示例15
def startRosService():
        s = rospy.Service('windCurrent', GetSpeed, handleWindCurrent)
        print "Ready to answer wind current. Wait full load before changing time" 
示例16
def startRosService():
        s = rospy.Service('windCurrent', GetSpeed, handleWindCurrent)
        print "Ready to answer wind current." 
示例17
def start(self, node_name='synthesizer_node', service_name='synthesizer'):
        """The entry point of a ROS service node.

        :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, Synthesizer, self._node_request_handler)

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

        rospy.spin() 
示例18
def __init__(self):
        self._dc = DialogflowClient()
        self._service = rospy.Service('/dialogflow_client/intent_service', DialogflowService, self._service_cb) 
示例19
def __init__(self, port="/dev/ttyUSB0", baudrate=9600):
		'''
		Initializes the receiver class. 
		port: The serial port to listen to.
		baudrate: Baud rate for the serial communication
		'''

		self._Counter = 0

		rospy.init_node('arduino')

		port = rospy.get_param("~port", "/dev/ttyUSB0")
		baudRate = int(rospy.get_param("~baudRate", 9600))

		rospy.loginfo("Starting with serial port: " + port + ", baud rate: " + str(baudRate))

		# subscriptions
		rospy.Subscriber("cmd_vel", Twist, self._HandleVelocityCommand)
		self._SerialPublisher = rospy.Publisher('serial', String)

		self._OdometryTransformBroadcaster = tf.TransformBroadcaster()
		self._OdometryPublisher = rospy.Publisher("odom", Odometry)

#		self._VoltageLowlimit = rospy.get_param("~batteryStateParams/voltageLowlimit", "12.0")
#		self._VoltageLowLowlimit = rospy.get_param("~batteryStateParams/voltageLowLowlimit", "11.7")

#		self._BatteryStatePublisher = rospy.Publisher("battery", BatteryState)
		
		self._SetDriveGainsService = rospy.Service('setDriveControlGains', SetDriveControlGains, self._HandleSetDriveGains)

		self._State = Arduino.CONTROLLER_RESET_REQUIRED

		self._SerialDataGateway = SerialDataGateway(port, baudRate,  self._HandleReceivedLine) 
示例20
def __init__(self, port="/dev/ttyUSB0", baudrate=9600):
		'''
		Initializes the receiver class. 
		port: The serial port to listen to.
		baudrate: Baud rate for the serial communication
		'''

		self._Counter = 0

		rospy.init_node('arduino')

		port = rospy.get_param("~port", "/dev/ttyUSB0")
		baudRate = int(rospy.get_param("~baudRate", 9600))

		rospy.loginfo("Starting with serial port: " + port + ", baud rate: " + str(baudRate))

		# subscriptions
		rospy.Subscriber("cmd_vel", Twist, self._HandleVelocityCommand)
		self._SerialPublisher = rospy.Publisher('serial', String)

		self._OdometryTransformBroadcaster = tf.TransformBroadcaster()
		self._OdometryPublisher = rospy.Publisher("odom", Odometry)

#		self._VoltageLowlimit = rospy.get_param("~batteryStateParams/voltageLowlimit", "12.0")
#		self._VoltageLowLowlimit = rospy.get_param("~batteryStateParams/voltageLowLowlimit", "11.7")

#		self._BatteryStatePublisher = rospy.Publisher("battery", BatteryState)
		
		self._SetDriveGainsService = rospy.Service('setDriveControlGains', SetDriveControlGains, self._HandleSetDriveGains)

		self._State = Arduino.CONTROLLER_RESET_REQUIRED

		self._SerialDataGateway = SerialDataGateway(port, baudRate,  self._HandleReceivedLine) 
示例21
def __init__(self, port="/dev/ttyUSB0", baudrate=9600):
		'''
		Initializes the receiver class. 
		port: The serial port to listen to.
		baudrate: Baud rate for the serial communication
		'''

		self._Counter = 0

		rospy.init_node('arduino')

		port = rospy.get_param("~port", "/dev/ttyUSB0")
		baudRate = int(rospy.get_param("~baudRate", 9600))

		rospy.loginfo("Starting with serial port: " + port + ", baud rate: " + str(baudRate))

		# subscriptions
		rospy.Subscriber("cmd_vel", Twist, self._HandleVelocityCommand)
		self._SerialPublisher = rospy.Publisher('serial', String)

		self._OdometryTransformBroadcaster = tf.TransformBroadcaster()
		self._OdometryPublisher = rospy.Publisher("odom", Odometry)

#		self._VoltageLowlimit = rospy.get_param("~batteryStateParams/voltageLowlimit", "12.0")
#		self._VoltageLowLowlimit = rospy.get_param("~batteryStateParams/voltageLowLowlimit", "11.7")

#		self._BatteryStatePublisher = rospy.Publisher("battery", BatteryState)
		
		self._SetDriveGainsService = rospy.Service('setDriveControlGains', SetDriveControlGains, self._HandleSetDriveGains)

		self._State = Arduino.CONTROLLER_RESET_REQUIRED

		self._SerialDataGateway = SerialDataGateway(port, baudRate,  self._HandleReceivedLine) 
示例22
def __init__(self, position_dir):
        self.fh = PositionFileHandler(position_dir)
        self.manage_position_server = rospy.Service('/niryo_one/position/manage_position', ManagePosition,
                                                    self.callback_manage_position)
        rospy.loginfo("service manage position created")

        self.get_position_list_server = rospy.Service(
            '/niryo_one/position/get_position_list', GetPositionList, self.callback_get_position_list)
        rospy.loginfo("get list position created")

        self.validation = rospy.get_param("/niryo_one/robot_command_validation")
        self.parameters_validation = ParametersValidation(self.validation) 
示例23
def __init__(self, trajectory_dir):
        self.fh = TrajectoryFileHandler(trajectory_dir)
        self.manage_position_server = rospy.Service(
            '/niryo_one/trajectory/manage_trajectory', ManageTrajectory, self.callback_manage_trajectory)
        rospy.loginfo("/niryo_one/trajectory/manage_trajectory service has been created ")
        self.get_trajectory_list_server = rospy.Service(
            '/niryo_one/trajectory/get_trajectory_list', GetTrajectoryList, self.callback_get_trajectory_list)
        rospy.loginfo("/niryo_one/trajectory/get_trajectory_list")
        self.validation = rospy.get_param("/niryo_one/robot_command_validation")
        self.parameters_validation = ParametersValidation(self.validation) 
示例24
def __init__(self, jevois_manager):
        self.jevois_manager = jevois_manager

        self.change_module_server = rospy.Service(
            '/niryo_one/jevois/set_module', SetString,
            self.ros_callback_set_module)

        self.data_publisher = rospy.Publisher(
            '/niryo_one/jevois/data', String, queue_size=10)

        self.jevois_manager.set_data_callback(self.callback_data) 
示例25
def __init__(self, sequences_dir):
        self.fh = SequenceFileHandler(sequences_dir)
        self.blockly_generator = BlocklyCodeGenerator()

        self.get_sequence_list_server = rospy.Service(
            '/niryo_one/sequences/get_sequence_list', GetSequenceList, self.callback_get_sequence_list)

        self.manage_command_server = rospy.Service(
            '/niryo_one/sequences/manage_sequence', ManageSequence, self.callback_manage_sequence) 
示例26
def __init__(self):
        self.sequence_autorun_status_file = rospy.get_param("~sequence_autorun_status_file")
        self.sequence_autorun_status_file = os.path.expanduser(self.sequence_autorun_status_file)
        self.lock = Lock()
        self.enabled, self.mode, self.sequence_ids = self.read_sequence_autorun_status()
        self.activated = False
        self.sequence_execution_index = -1
        self.flag_send_robot_to_home_position = False
        self.cancel_sequence = False
        self.is_sequence_running = False

        self.calibration_needed = None
        self.calibration_in_progress = None
        self.hardware_status_subscriber = rospy.Subscriber(
            '/niryo_one/hardware_status', HardwareStatus, self.sub_hardware_status)

        self.learning_mode_on = None
        self.learning_mode_subscriber = rospy.Subscriber(
            '/niryo_one/learning_mode', Bool, self.sub_learning_mode)

        # Wait for sequence action server to finish setup
        self.sequence_action_client = actionlib.SimpleActionClient('niryo_one/sequences/execute', SequenceAction)
        self.sequence_action_client.wait_for_server()

        self.sequence_autorun_status_publisher = rospy.Publisher(
            '/niryo_one/sequences/sequence_autorun_status', SequenceAutorunStatus, queue_size=10)
        self.timer = rospy.Timer(rospy.Duration(3.0), self.publish_sequence_autorun_status)

        self.set_sequence_autorun_server = rospy.Service(
            '/niryo_one/sequences/set_sequence_autorun', SetSequenceAutorun, self.callback_set_sequence_autorun)

        self.trigger_sequence_autorun = rospy.Service(
            '/niryo_one/sequences/trigger_sequence_autorun', SetInt, self.callback_trigger_sequence_autorun)

        self.sequence_autorun_thread = Thread(name="worker", target=self.execute_sequence_autorun_thread)
        self.sequence_autorun_thread.setDaemon(True)
        self.sequence_autorun_thread.start()

        rospy.loginfo('Init Sequence autorun OK') 
示例27
def __init__(self):
        ws_dir = rospy.get_param("~workspace_dir", "~/niryo_one_workspaces/")
        grip_dir = rospy.get_param("~grip_dir", "~/catkin_ws/src/niryo_one_pose_converter/grips/")

        tool_config_list = rospy.get_param("niryo_one_tools/tool_list")
        self.tool_id_gripname_dict = {tool["id"]: "default_" + tool["name"].replace(" ", "_")
                                      for tool in tool_config_list}
        self.tool_id_gripname_dict[0] = "default_Calibration_Tip"

        self.ws_manager = WorkspaceManager(ws_dir)
        self.grip_manager = GripManager(grip_dir, self.tool_id_gripname_dict.values())
        self.transform_handler = TransformHandler()
        self.edit_grip_server = rospy.Service(
            'niryo_one/pose_converter/edit_grip', EditGrip, self.__callback_edit_grip)
        self.edit_ws_server = rospy.Service(
            'niryo_one/pose_converter/edit_workspace', EditWorkspace,
            self.__callback_edit_workspace)
        self.get_ws_ratio_server = rospy.Service(
            'niryo_one/pose_converter/get_workspace_ratio', GetWorkspaceRatio,
            self.__callback_workspace_ratio)
        self.get_ws_list_server = rospy.Service(
            'niryo_one/pose_converter/get_workspace_list', GetWorkspaceList,
            self.__callback_workspace_list)
        self.get_target_pose_server = rospy.Service(
            'niryo_one/pose_converter/get_workspace_poses', GetWorkspaceRobotPoses,
            self.__callback_workspace_poses)
        self.get_target_pose_server = rospy.Service(
            'niryo_one/pose_converter/get_target_pose', GetTargetPose,
            self.__callback_target_pose)

    # ROS CALLBACKS 
示例28
def __init__(self):
        self.shutdown_rpi_sever = rospy.Service('/niryo_one/rpi/shutdown_rpi',
                                                SetInt, self.callback_shutdown_rpi)
        rospy.loginfo("Shutdown Manager OK") 
示例29
def __init__(self):
        self.pin = BUTTON_GPIO
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        rospy.loginfo("GPIO setup : " + str(self.pin) + " as input")
        rospy.sleep(0.1)

        self.last_state = self.read_value()
        self.consecutive_pressed = 0
        self.activated = True

        self.timer_frequency = 20.0
        self.shutdown_action = False
        self.hotspot_action = False

        self.button_mode = ButtonMode.TRIGGER_SEQUENCE_AUTORUN
        self.change_button_mode_server = rospy.Service(
            "/niryo_one/rpi/change_button_mode", SetInt, self.callback_change_button_mode)
        self.monitor_button_mode_timer = rospy.Timer(rospy.Duration(3.0), self.monitor_button_mode)
        self.last_time_button_mode_changed = rospy.Time.now()

        # Publisher used to send info to Niryo One Studio, so the user can add a move block
        # by pressing the button
        self.save_point_publisher = rospy.Publisher(
            "/niryo_one/blockly/save_current_point", Int32, queue_size=10)

        self.button_state_publisher = rospy.Publisher(
            "/niryo_one/rpi/is_button_pressed", Bool, queue_size=10)

        self.button_timer = rospy.Timer(rospy.Duration(1.0 / self.timer_frequency), self.check_button)
        rospy.on_shutdown(self.shutdown)
        rospy.loginfo("Niryo One Button started") 
示例30
def __init__(self):
        self.hw_version = rospy.get_param("/niryo_one/hardware_version")
        self.change_motor_config_server = rospy.Service('/niryo_one/debug_change_motor_config',
                                                        ChangeMotorConfig, self.callback_change_motor_config)
        rospy.loginfo("Init motor debug OK")