### Run ROS Talker Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Starts the ROS talker node. This is a prerequisite for the listener example. ```default python ros-hello-world-talker.py ``` -------------------------------- ### Install roslibpy with pip Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/readme.md Install the roslibpy library using pip for standard Python environments. ```bash pip install roslibpy ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/contributing.md Installs the necessary development dependencies for the project. Ensure you have a virtual environment set up before running this command. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install roslibpy with pip for IronPython Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/readme.md Install the roslibpy library using pip for IronPython environments, specifying user installation. ```bash ipy -X:Frames -m pip install --user roslibpy ``` -------------------------------- ### Full ROS Connection Example Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md A complete Python script to establish a ROS connection, print its status, and then terminate. ```python import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() print('Is ROS connected?', client.is_connected) client.terminate() ``` -------------------------------- ### Publishing Messages to a Topic Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md This example demonstrates how to create a publisher for a ROS topic and continuously send 'Hello World!' messages. ```python import time import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() talker = roslibpy.Topic(client, '/chatter', 'std_msgs/String') while client.is_connected: talker.publish(roslibpy.Message({'data': 'Hello World!'})) print('Sending message...') time.sleep(1) talker.unadvertise() client.terminate() ``` -------------------------------- ### Install ROS Bridge Server Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Installs the necessary ROS bridge server packages for ROS Kinetic. ```bash sudo apt-get install -y ros-kinetic-rosbridge-server sudo apt-get install -y ros-kinetic-tf2-web-republisher ``` -------------------------------- ### Subscribing to a Topic Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md This example shows how to create a subscriber for a ROS topic and print any received messages. It runs indefinitely until interrupted. ```python from __future__ import print_function import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() listener = roslibpy.Topic(client, '/chatter', 'std_msgs/String') listener.subscribe(lambda message: print('Heard talking: ' + message['data'])) try: while True: pass except KeyboardInterrupt: client.terminate() ``` -------------------------------- ### roslibpy.Ros.run Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Starts a non-blocking event loop with an optional timeout for connection readiness. ```APIDOC ## run(timeout=10) ### Description Kick-starts a non-blocking event loop. ### Parameters * **timeout** – Timeout to wait until connection is ready. ``` -------------------------------- ### Import roslibpy Source: https://github.com/robotwebtools/roslibpy/blob/main/ISSUE_TEMPLATE.md This snippet shows the basic import statement for the roslibpy library in Python. Ensure this library is installed before running. ```python import roslibpy ``` -------------------------------- ### Run ROS Listener Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Starts the ROS listener node to receive messages from the talker. Ensure the talker is running first. ```default python ros-hello-world-listener.py ``` -------------------------------- ### Example console output for latency check Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/02_check_latency.md This shows the expected output when running the Python script, indicating connection status and the calculated message age in milliseconds. ```text $ python 02_check_latency.py 2020-04-09 07:45:49,909 INFO: Connection to ROS ready. 2020-04-09 07:45:50,431 INFO: Age of message: 2ms 2020-04-09 07:45:50,932 INFO: Age of message: 2ms 2020-04-09 07:45:51,431 INFO: Age of message: 1ms 2020-04-09 07:45:51,932 INFO: Age of message: 2ms 2020-04-09 07:45:52,434 INFO: Age of message: 3ms 2020-04-09 07:45:52,934 INFO: Age of message: 2ms 2020-04-09 07:45:53,435 INFO: Age of message: 3ms 2020-04-09 07:45:53,934 INFO: Age of message: 1ms 2020-04-09 07:45:54,436 INFO: Age of message: 2ms ``` -------------------------------- ### Python Example: Throttling Messages for a Slow Consumer Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/03_slow_consumer.md This Python script demonstrates how to throttle messages in a ROS environment using roslibpy. It configures a publisher to send messages rapidly and a subscriber with a specific queue length and throttle rate to manage message consumption by a slow process. Use this when a publisher generates messages faster than a subscriber can process them. ```python import time import logging from roslibpy import Header from roslibpy import Ros from roslibpy import Time from roslibpy import Topic from roslibpy.core import LOGGER # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = Ros(host='127.0.0.1', port=9090) def receive_message(msg): header = Header(msg['seq'], msg['stamp'], msg['frame_id']) age = time.time() - header['stamp'].to_sec() fmt = 'Age of message (sequence #%d): %6.3f seconds' log.info(fmt, msg['seq'], age) # Simulate a very slow consumer time.sleep(.5) publisher = Topic(client, '/slow_consumer', 'std_msgs/Header') publisher.advertise() # Queue length needs to be used in combination with throttle rate (in ms) # This value must be tuned to the expected duration of the slow consumer # and ideally bigger than the max of it, # otherwise message will be older than expected (up to a limit) subscriber = Topic(client, '/slow_consumer', 'std_msgs/Header', queue_length=1, throttle_rate=600) subscriber.subscribe(receive_message) seq = 0 def publish_message(): global seq seq += 1 header = Header(frame_id='', seq=seq, stamp=Time.now()) publisher.publish(header) client.call_later(.001, publish_message) client.on_ready(publish_message) client.run_forever() ``` -------------------------------- ### Create ROS Action Server for Fibonacci Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Defines and starts a ROS action server for the Fibonacci sequence. It handles goals, sends feedback with the sequence, and sets the final result upon completion or preemption. ```python import roslibpy import roslibpy.actionlib client = roslibpy.Ros(host='localhost', port=9090) server = roslibpy.actionlib.SimpleActionServer(client, '/fibonacci', 'actionlib_tutorials/FibonacciAction') def execute(goal): print('Received new fibonacci goal: {}'.format(goal['order'])) seq = [0, 1] for i in range(1, goal['order']): if server.is_preempt_requested(): server.set_preempted() return seq.append(seq[i] + seq[i - 1]) server.send_feedback({'sequence': seq}) server.set_succeeded({'sequence': seq}) server.start(execute) client.run_forever() ``` -------------------------------- ### Run ROS Action Server Script Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Executes the Python script to start the Fibonacci ROS action server. The server remains active until the program is terminated, allowing action clients to connect and request computations. ```default $ python ros-action-server.py ``` -------------------------------- ### roslibpy.Ros.run_forever Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Starts a blocking event loop to wait for events. This may be required depending on the client application and implementation. ```APIDOC ## run_forever() ### Description Kick-starts a blocking loop to wait for events. Depending on the implementations, and the client applications, running this might be required or not. ``` -------------------------------- ### Run ROS Service Caller Script Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Executes a Python script to call the '/set_ludicrous_speed' ROS service. This verifies that the service created in the previous example is working correctly. ```default $ python ros-service-call-set-bool.py ``` -------------------------------- ### Run Integration Test Docker Container Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/contributing.md Starts a Docker container for running integration tests. This container exposes port 9090 and runs the integration tests bridge. ```bash docker run -d -p 9090:9090 --name roslibpy_integration_tests gramaziokohler/integration-tests-bridge /bin/bash -c "roslaunch /integration-tests.launch" ``` -------------------------------- ### Call ROS Service to Get Loggers Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Connects to a ROS instance and calls the '/rosout/get_loggers' service to retrieve logger information. Requires a running ROS instance with the 'roscpp' package. ```python import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.run() service = roslibpy.Service(client, '/rosout/get_loggers', 'roscpp/GetLoggers') request = roslibpy.ServiceRequest() print('Calling service...') result = service.call(request) print('Service response: {}'.format(result['loggers'])) client.terminate() ``` -------------------------------- ### Python script to check roundtrip message latency Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/02_check_latency.md This script connects to a ROS instance, advertises a topic, subscribes to it, and continuously publishes messages with timestamps to measure latency. It requires roslibpy to be installed. ```python import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) def receive_message(msg): age = int(time.time() * 1000) - msg['data'] log.info('Age of message: %6dms', age) publisher = roslibpy.Topic(client, '/check_latency', 'std_msgs/UInt64') publisher.advertise() subscriber = roslibpy.Topic(client, '/check_latency', 'std_msgs/UInt64') subscriber.subscribe(receive_message) def publish_message(): publisher.publish(dict(data=int(time.time() * 1000))) client.call_later(.5, publish_message) client.on_ready(publish_message) client.run_forever() ``` -------------------------------- ### Initialize ROS Connection Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Initialize a connection to the ROS environment. Ensure ROS and rosbridge are running. ```python >>> ros = roslibpy.Ros(host='localhost', port=9090) >>> ros.run() ``` -------------------------------- ### Connect to ROS Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Establishes the connection to the ROS server. ```python client.connect() ``` -------------------------------- ### id_counter Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Generates an auto-incremental ID starting from 1. This is a property, not a method call. ```APIDOC ## id_counter ### Description Generate an auto-incremental ID starting from 1. ### Returns An auto-incremented ID. ``` -------------------------------- ### Generate Documentation Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/contributing.md Generates the project's documentation using Sphinx. This command should be run after making documentation changes. ```bash invoke docs ``` -------------------------------- ### Enable Debug Logging with Python Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/01_debug_logging.md Configure Python's logging to DEBUG level and initialize a roslibpy client. This is useful for detailed troubleshooting. ```python import logging import roslibpy # Configure logging to high verbosity (DEBUG) fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.DEBUG) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) client.on_ready(lambda: log.info('On ready has been triggered')) client.run_forever() ``` -------------------------------- ### connect Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Establishes a connection to ROS. ```APIDOC ## connect() ### Description Connect to ROS. ``` -------------------------------- ### roslibpy.Ros.on_ready Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Adds a callback to be executed when the connection to ROS is established. If a connection is already available, the callback is executed immediately. ```APIDOC ## on_ready(callback, run_in_thread=True) ### Description Add a callback to be executed when the connection is established. If a connection to ROS is already available, the callback is executed immediately. ### Parameters * **callback** – Callable function to be invoked when ROS connection is ready. * **run_in_thread** (`bool`) – True to run the callback in a separate thread, False otherwise. ``` -------------------------------- ### roslibpy.ros1.actionlib.SimpleActionServer Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Implementation of a simple action server. It handles incoming goals, cancellations, and allows sending feedback, preemptions, and results. ```APIDOC ## Class: roslibpy.ros1.actionlib.SimpleActionServer ### Description Implementation of the simple action server. It emits events for new goals and cancellations. ### Parameters * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **server_name** (`str`) – Action server name, e.g. `/fibonacci`. * **action_name** (`str`) – Action message name, e.g. `actionlib_tutorials/FibonacciAction`. ### Methods #### is_preempt_requested() Indicate whether the client has requested preemption of the current goal. #### send_feedback(feedback) Send feedback. * **Parameters:** **feedback** (`dict`) – Dictionary of key/values of the feedback message. #### set_preempted() Set the current action to preempted (cancelled). #### set_succeeded(result) Set the current action state to succeeded. * **Parameters:** **result** (`dict`) – Dictionary of key/values to set as the result of the action. #### start(action_callback) Start the action server. * **Parameters:** * **action_callback** – Callable function to be invoked when a new goal is received. It takes one parameter containing the goal message. ``` -------------------------------- ### Invoke Available Tasks Source: https://github.com/robotwebtools/roslibpy/blob/main/CONTRIBUTING.rst Displays a list of all available tasks that can be run with invoke. ```bash invoke ``` -------------------------------- ### Launch ROS Bridge Services Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Launches the ROS bridge websocket server and the TF2 web republisher service. ```bash roslaunch rosbridge_server rosbridge_websocket.launch rosrun tf2_web_republisher tf2_web_republisher ``` -------------------------------- ### Initialize Ros Connection Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Initializes a connection manager to a ROS server. Use this to establish and manage your connection to ROS. ```python import roslibpy client = roslibpy.Ros(host='127.0.0.1', port=9090) ``` -------------------------------- ### ROS Connection with run_forever and on_ready Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Connect to ROS and handle the event loop explicitly using run_forever. The on_ready callback is executed once the connection is established. ```python from __future__ import print_function import roslibpy client = roslibpy.Ros(host='localhost', port=9090) client.on_ready(lambda: print('Is ROS connected?', client.is_connected)) client.run_forever() ``` -------------------------------- ### Basic ROS Action Client Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md A simple action client that sends a goal and waits for the result. It prints intermediate feedback and the final sequence. Uses Goal.wait() for simplicity. ```python from __future__ import print_function import roslibpy import roslibpy.actionlib client = roslibpy.Ros(host='localhost', port=9090) client.run() action_client = roslibpy.actionlib.ActionClient(client, '/fibonacci', 'actionlib_tutorials/FibonacciAction') goal = roslibpy.actionlib.Goal(action_client, roslibpy.Message({'order': 8})) goal.on('feedback', lambda f: print(f['sequence'])) goal.send() result = goal.wait(10) action_client.dispose() print('Result: {}'.format(result['sequence'])) ``` -------------------------------- ### Prepare and release a new version Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/readme.md Prepare and release a new version of roslibpy using invoke tasks, following semantic versioning. ```bash git checkout -b release-x.y.z invoke release [patch|minor|major] ``` -------------------------------- ### roslibpy.Ros.send_on_ready Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends a message to ROS once the connection is established. If a connection is already available, the message is sent immediately. ```APIDOC ## send_on_ready(message) ### Description Send message to ROS once the connection is established. If a connection to ROS is already available, the message is sent immediately. ### Parameters * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message to send. ``` -------------------------------- ### roslibpy.Topic.advertise Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Registers the topic as a publisher. ```APIDOC ## advertise() ### Description Register as a publisher for the topic. ``` -------------------------------- ### Push release branch and tags Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/readme.md Push the release branch and git tags to the origin repository after a release. ```bash git push origin release-x.y.z git push origin --tags ``` -------------------------------- ### Publish Compressed Image Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/04_publish_image.md Publishes a local JPEG image file as a compressed image message to the '/camera/image/compressed' topic. Requires a 'robots.jpg' file in the same directory. ```python import base64 import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) publisher = roslibpy.Topic(client, '/camera/image/compressed', 'sensor_msgs/CompressedImage') publisher.advertise() def publish_image(): with open('robots.jpg', 'rb') as image_file: image_bytes = image_file.read() encoded = base64.b64encode(image_bytes).decode('ascii') publisher.publish(dict(format='jpeg', data=encoded)) client.on_ready(publish_image) client.run_forever() ``` -------------------------------- ### call_async_action Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends an action request to ROS once the connection is established. If a connection is available, it's sent immediately. ```APIDOC ## call_async_action(message, resultback, feedback, errback) ### Description Send a action request to ROS once the connection is established. If a connection to ROS is already available, the request is sent immediately. ### Parameters * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message containing the request. * **resultback** – Callback invoked on successful execution. * **feedback** – Callback invoked on receiving action feedback. * **errback** – Callback invoked on error. ``` -------------------------------- ### Run ROS Service Creation Script Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Executes the Python script to create and advertise the '/set_ludicrous_speed' ROS service. The service remains active until the program is terminated. ```default $ python ros-service.py ``` -------------------------------- ### ROS 2 Action Client with Callbacks Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md An action client for ROS 2 that uses callbacks for handling results, feedback, and failures. It demonstrates sending a goal, waiting for completion, and canceling a goal. ```python from __future__ import print_function import roslibpy import time global result def result_callback(msg): global result result = msg print("Action result:", msg) def feedback_callback(msg): print(f"Action feedback: {msg['sequence']}") def fail_callback(msg): print(f"Action failed: {msg}") def test_action_success(action_client): """ This test function sends a action goal to an Action server. """ global result result = None goal = roslibpy.Goal({"order": 8}) action_client.send_goal(goal, result_callback, feedback_callback, fail_callback) while result == None: time.sleep(1) print("-----------------------------------------------") print("Action status:", result["status"]) print("Action result: {}".format(result["values"]["sequence"])) def test_action_cancel(action_client): """ This test function sends a cancel request to an Action server. NOTE: Make sure to start the "rosbridge_server" node with the parameter "send_action_goals_in_new_thread" set to "true". """ global result result = None goal = roslibpy.Goal({"order": 8}) goal_id = action_client.send_goal(goal, result_callback, feedback_callback, fail_callback) time.sleep(3) print("Sending action goal cancel request...") action_client.cancel_goal(goal_id) while result == None: time.sleep(1) print("-----------------------------------------------") print("Action status:", result["status"]) print("Action result: {}".format(result["values"]["sequence"])) if __name__ == "__main__": client = roslibpy.Ros(host="localhost", port=9090) client.run() action_client = roslibpy.ActionClient(client, "/fibonacci", "example_interfaces/action/Fibonacci") print("\n** Starting action client test **") test_action_success(action_client) print("\n** Starting action goal cancelation test **") test_action_cancel(action_client) ``` -------------------------------- ### Run code and documentation style checks Source: https://github.com/robotwebtools/roslibpy/blob/main/README.rst Execute the invoke check task to perform various code and documentation style checks. ```bash invoke check ``` -------------------------------- ### roslibpy.ros1.actionlib.ActionClient Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Client for interacting with ROS action servers. It manages goals, allows cancellation, and handles disconnection. ```APIDOC ## Class: roslibpy.ros1.actionlib.ActionClient ### Description Client to use ROS actions. It manages goals and connection lifecycle. ### Parameters * **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. * **server_name** (`str`) – Action server name, e.g. `/fibonacci`. * **action_name** (`str`) – Action message name, e.g. `actionlib_tutorials/FibonacciAction`. * **timeout** (`int`) – Deprecated. Connection timeout, expressed in seconds. ### Methods #### add_goal(goal) Add a goal to this action client. * **Parameters:** **goal** ([`Goal`](#roslibpy.ros1.actionlib.Goal)) – Goal to add. #### cancel() Cancel all goals associated with this action client. #### dispose() Unsubscribe and unadvertise all topics associated with this action client. ``` -------------------------------- ### Run All Tests Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/contributing.md Executes all tests and checks for the project using the invoke task runner. This command should be run after making code changes to ensure everything still passes. ```bash invoke test ``` -------------------------------- ### Pyinvoke Tasks for Development Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/contributing.md Provides a list of common pyinvoke tasks for development operations. These tasks help automate recurring operations like cleaning, checking, and testing. ```bash invoke clean ``` ```bash invoke check ``` ```bash invoke docs ``` ```bash invoke test ``` ```bash invoke ``` -------------------------------- ### roslibpy.tf.TFClient Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md A TF Client that listens to TFs from tf2_web_republisher. ```APIDOC ## Class: roslibpy.tf.TFClient ### Description A TF Client that listens to TFs from tf2_web_republisher. ### Parameters - **ros** ([`Ros`](#roslibpy.Ros)) – Instance of the ROS connection. - **fixed_frame** (`str`) – Fixed frame, e.g. `/base_link`. - **angular_threshold** (`float`) – Angular threshold for the TF republisher. - **translation_threshold** (`float`) – Translation threshold for the TF republisher. - **rate** (`float`) – Rate for the TF republisher. - **update_delay** (`int`) – Time expressed in milliseconds to wait after a new subscription before update TFs. - **topic_timeout** (`int`) – Timeout parameter for the TF republisher expressed in milliseconds. - **repub_service_name** (`str`) – Name of the republish tfs service, e.g. `/republish_tfs`. ### Methods #### dispose() Unsubscribe and unadvertise all topics associated with this instance. #### subscribe(frame_id, callback) Subscribe to the given TF frame. ### Parameters - **frame_id** (`str`) – TF frame identifier to subscribe to. - **callback** (`callable`) – A callable functions receiving one parameter with transform data. #### unsubscribe(frame_id, callback) Unsubscribe from the given TF frame. ### Parameters - **frame_id** (`str`) – TF frame identifier to unsubscribe from. - **callback** (`callable`) – The callback function to remove. #### update_goal() Send a new service request to the tf2_web_republisher based on the current list of TFs. ``` -------------------------------- ### authenticate Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends an authorization request to the server. This is typically done on connection. ```APIDOC ## authenticate(mac, client, dest, rand, t, level, end) ### Description Sends an authorization request to the server. #### NOTE Sends authentication on connection. ### Parameters * **mac** (`str`) – MAC (hash) string given by the trusted source. * **client** (`str`) – IP of the client. * **dest** (`str`) – IP of the destination. * **rand** (`str`) – Random string given by the trusted source. * **t** (`float`) – Time of the authorization request. * **level** (`str`) – User level as a string given by the client. * **end** (`float`) – End time of the client’s session. ``` -------------------------------- ### Subscribe to Compressed Images Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples/05_subscribe_to_images.md Subscribes to the '/camera/image/compressed' topic, decodes base64 encoded image data, and saves each received image to a file. Requires a running ROS instance with a compatible image publisher. ```python import base64 import logging import time import roslibpy # Configure logging fmt = '%(asctime)s %(levelname)8s: %(message)s' logging.basicConfig(format=fmt, level=logging.INFO) log = logging.getLogger(__name__) client = roslibpy.Ros(host='127.0.0.1', port=9090) def receive_image(msg): log.info('Received image seq=%d', msg['header']['seq']) base64_bytes = msg['data'].encode('ascii') image_bytes = base64.b64decode(base64_bytes) with open('received-image-{}.{}'.format(msg['header']['seq'], msg['format']) , 'wb') as image_file: image_file.write(image_bytes) subscriber = roslibpy.Topic(client, '/camera/image/compressed', 'sensor_msgs/CompressedImage') subscriber.subscribe(receive_image) client.run_forever() ``` -------------------------------- ### get_topics Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of all topics available in the ROS system. Supports asynchronous and synchronous calls. ```APIDOC ## get_topics ### Description Retrieve list of topics in ROS. ### Method GET (implied) ### Parameters #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of topics if blocking, otherwise `None`. ``` -------------------------------- ### Create ROS Service to Set Boolean Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Advertises a ROS service '/set_ludicrous_speed' that accepts a boolean request and returns a success status. This service can be called by other nodes. ```python import roslibpy def handler(request, response): print('Setting speed to {}'.format(request['data'])) response['success'] = True return True client = roslibpy.Ros(host='localhost', port=9090) service = roslibpy.Service(client, '/set_ludicrous_speed', 'std_srvs/SetBool') service.advertise(handler) print('Service advertised.') client.run_forever() client.terminate() ``` -------------------------------- ### roslibpy.Service Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Client/server of ROS services. This class can be used both to consume other ROS services as a client, or to provide ROS services as a server. ```APIDOC ## roslibpy.Service(ros, name, service_type, reconnect_on_close=True) ### Description Client/server of ROS services. This class can be used both to consume other ROS services as a client, or to provide ROS services as a server. ### Parameters * **ros** (`roslibpy.Ros`) – Instance of the ROS connection. * **name** (`str`) – Service name, e.g. `/add_two_ints`. * **service_type** (`str`) – Service type, e.g. `rospy_tutorials/AddTwoInts`. #### advertise(callback) ### Description Start advertising the service. This turns the instance from a client into a server. The callback will be invoked with every request that is made to the service. If the service is already advertised, this call does nothing. ### Parameters * **callback** – Callback invoked on every service call. It should accept two parameters: service_request and service_response. It should return True if executed correctly, otherwise False. #### call(request, callback=None, errback=None, timeout=None) ### Description Start a service call. The service can be used either as blocking or non-blocking. If the `callback` parameter is `None`, then the call will block until receiving a response. Otherwise, the service response will be returned in the callback. ### Parameters * **request** (`roslibpy.ServiceRequest`) – Service request. * **callback** – Callback invoked on successful execution. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. ### Returns *object* – Service response if used as a blocking call, otherwise `None`. #### is_advertised ### Description Service servers are registered as advertised on ROS. This class can be used to be a service client or a server. ### Returns *bool* – True if this is a server, False otherwise. #### unadvertise() ### Description Unregister as a service server. ``` -------------------------------- ### emit Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Triggers a named event with provided arguments. ```APIDOC ## emit(event_name, *args) ### Description Trigger a named event. ### Parameters * **event_name** (`str`) – The name of the event to trigger. * **args** – Positional arguments to pass with the event. ``` -------------------------------- ### call_async_service Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends a service request to ROS once the connection is established. If a connection is available, it's sent immediately. ```APIDOC ## call_async_service(message, callback, errback) ### Description Send a service request to ROS once the connection is established. If a connection to ROS is already available, the request is sent immediately. ### Parameters * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message containing the request. * **callback** – Callback invoked on successful execution. * **errback** – Callback invoked on error. ``` -------------------------------- ### get_services Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of all active service names in the ROS system. Supports asynchronous and synchronous calls. ```APIDOC ## get_services ### Description Retrieve list of active service names in ROS. ### Method GET (implied) ### Parameters #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of services if blocking, otherwise `None`. ``` -------------------------------- ### on Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Adds a callback function to an arbitrary named event. The callback will be executed when the event is triggered. ```APIDOC ## on ### Description Add a callback to an arbitrary named event. ### Method POST (implied) ### Parameters #### Request Body - **event_name** (string) - Required - Name of the event to which to subscribe. - **callback** (callable) - Required - Callable function to be executed when the event is triggered. ``` -------------------------------- ### get_params Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of all parameter names available on the ROS Parameter Server. Supports asynchronous and synchronous operations. ```APIDOC ## get_params ### Description Retrieve list of param names from the ROS Parameter Server. ### Method GET (implied) ### Parameters #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of parameters if blocking, otherwise `None`. ``` -------------------------------- ### Call Action Asynchronously Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends an action request to ROS and provides callbacks for results, feedback, and errors. The request is sent immediately if a connection is already available. ```python client.call_async_action(message, resultback, feedback, errback) ``` -------------------------------- ### roslibpy.Ros Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Manages the connection to a ROS server. It handles connection establishment, automatic reconnections, and provides methods for interacting with ROS functionalities. ```APIDOC ## class roslibpy.Ros(host, port=None, is_secure=False, headers=None) ### Description Connection manager to ROS server. Other classes that need an active connection with ROS receive this instance as an argument to their constructors. ### Parameters * **host** (`str`) – Name or IP address of the ROS bridge host, e.g. `127.0.0.1`. * **port** (`int`) – ROS bridge port, e.g. `9090`. * **is_secure** (`bool`) – `True` to use a secure web sockets connection, otherwise `False`. * **headers** (`dict`) – Additional headers to include in the WebSocket connection. ``` -------------------------------- ### roslibpy.ros1.actionlib.Goal Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Represents a goal for an action server. It allows sending goals, canceling them, and tracking their progress through status, feedback, and result events. ```APIDOC ## Class: roslibpy.ros1.actionlib.Goal ### Description Represents a goal for an action server. It emits events for status, feedback, and result. ### Parameters * **action_client** ([`ActionClient`](#roslibpy.ros1.actionlib.ActionClient)) – Instance of the action client associated with the goal. * **goal_message** ([`Message`](#roslibpy.Message)) – Goal for the action server. ### Methods #### cancel() Cancel the current goal. #### send(result_callback=None, timeout=None) Send goal to the action server. * **Parameters:** * **timeout** (`int`) – Timeout for the goal’s result expressed in seconds. * **callback** (`callable`) – Function to be called when a result is received. It is a shorthand for hooking on the `result` event. #### wait(timeout=None) Block until the result is available. * **Parameters:** **timeout** (`int`) – Timeout to wait for the result expressed in seconds. * **Returns:** Result of the goal. ### Properties #### is_finished Indicate if the goal is finished or not. * **Returns:** *bool* – True if finished, False otherwise. ``` -------------------------------- ### get_action_servers Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of action servers available in the ROS system. This method can be used asynchronously with a callback or synchronously by passing None for the callback. ```APIDOC ## get_action_servers ### Description Retrieve list of action servers in ROS. ### Method GET (implied) ### Parameters #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of action servers. ``` -------------------------------- ### roslibpy.Topic.publish Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Publishes a message to the topic. ```APIDOC ## publish(message) ### Description Publish a message to the topic. ### Parameters * **message** ([`Message`](#roslibpy.Message)) – ROS Bridge Message to publish. ``` -------------------------------- ### get_param Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves the value of a specific parameter from the ROS Parameter Server. Supports asynchronous and synchronous calls. ```APIDOC ## get_param ### Description Get the value of a parameter from the ROS Parameter Server. ### Method GET (implied) ### Parameters #### Path Parameters - **name** (string) - Required - The name of the parameter to retrieve. #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns Parameter value if blocking, otherwise `None`. ``` -------------------------------- ### get_services_for_type Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of services in ROS that match a specified service type. Supports asynchronous and synchronous operations. ```APIDOC ## get_services_for_type ### Description Retrieve list of services in ROS matching the specified type. ### Method GET (implied) ### Parameters #### Path Parameters - **service_type** (string) - Required - The type of the service to search for. #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of services matching the specified type if blocking, otherwise `None`. ``` -------------------------------- ### roslibpy.Topic.unadvertise Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Unregisters the topic as a publisher. ```APIDOC ## unadvertise() ### Description Unregister as a publisher for the topic. ``` -------------------------------- ### roslibpy.Param Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md A ROS parameter. ROS provides a parameter server to share data among different nodes. This service can be accessed via the Param class. ```APIDOC ## roslibpy.Param(ros, name) ### Description A ROS parameter. ROS provides a parameter server to share data among different nodes. This service can be accessed via the [`Param`](#roslibpy.Param) class. ### Parameters * **ros** (`roslibpy.Ros`) – Instance of the ROS connection. * **name** (`str`) – Parameter name, e.g. `max_vel_x`. #### delete(callback=None, errback=None, timeout=None) ### Description Delete the parameter. This method can be used either as blocking or non-blocking. If the `callback` parameter is `None`, the call will block until completion. ### Parameters * **callback** – Callable function to be invoked when the operation is completed. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. #### get(callback=None, errback=None, timeout=None) ### Description Fetch the current value of the parameter. This method can be used either as blocking or non-blocking. If the `callback` parameter is `None`, the call will block until completion. ### Parameters * **callback** – Callable function to be invoked when the operation is completed. * **errback** – Callback invoked on error. * **timeout** – Timeout for the operation, in seconds. Only used if blocking. ``` -------------------------------- ### is_connected Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Indicates whether the ROS connection is currently open or not. This is a property, not a method call. ```APIDOC ## is_connected ### Description Indicate if the ROS connection is open or not. ### Returns True if connected to ROS, False otherwise. ``` -------------------------------- ### roslibpy.Time Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Represents ROS time with two integers: seconds since epoch and nanoseconds since seconds. ```APIDOC ## Class: roslibpy.Time ### Description Represents ROS time with two integers: seconds since epoch and nanoseconds since seconds. ### Methods #### static from_sec(float_secs) Create new Time instance from a float seconds representation (e.g. `time.time()`). #### is_zero() Return `True` if zero (secs and nsecs) otherwise `False`. #### static now() Create new Time instance from the current system time (not ROS time). #### to_nsec() Return time as nanoseconds from epoch. #### to_sec() Return time as float seconds representation (same as `time.time()`). ### Properties #### nsecs Nanoseconds since seconds. #### secs Seconds since epoch. ``` -------------------------------- ### roslibpy.Topic.is_advertised Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Indicates if the topic is currently advertised as a publisher. ```APIDOC ## is_advertised ### Description Indicate if the topic is currently advertised or not. ### Returns *bool* – True if advertised as publisher of this topic, False otherwise. ``` -------------------------------- ### get_service_request_callback Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Obtains a callback function that, when invoked, sends a service request with the provided message. This is a synchronous operation. ```APIDOC ## get_service_request_callback ### Description Get the callback which, when called, sends the service request. ### Method POST (implied) ### Parameters #### Request Body - **message** (Message) - Required - ROS Bridge Message containing the request. ### Returns A callable which makes the service request. ``` -------------------------------- ### Call Service Asynchronously Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends a service request to ROS and invokes callbacks upon completion or error. The request is sent immediately if a connection is already available. ```python client.call_async_service(message, callback, errback) ``` -------------------------------- ### Check ROS Connection Status Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/examples.md Verify if the connection to ROS is established and active. ```python >>> ros.is_connected ``` -------------------------------- ### roslibpy.Topic.subscribe Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Registers a subscription to the topic. The provided callback is invoked for each message received. ```APIDOC ## subscribe(callback) ### Description Register a subscription to the topic. Every time a message is published for the given topic, the callback will be called with the message object. ### Parameters * **callback** – Function to be called when messages of this topic are published. ``` -------------------------------- ### Authenticate ROS Connection Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends an authorization request to the server, typically done on connection. Requires specific parameters like MAC, client IP, destination IP, random string, time, user level, and session end time. ```python client.authenticate(mac, client, dest, rand, t, level, end) ``` -------------------------------- ### Call Function Later Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Schedules a callback function to be invoked after a specified delay, once the ROS connection is ready. ```python client.call_later(delay, callback) ``` -------------------------------- ### Emit Event Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Triggers a named event with provided arguments. ```python client.emit(event_name, *args) ``` -------------------------------- ### roslibpy.ActionClient Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Action Client of ROS 2 actions. An Action client for ROS 2 Actions can be used by managing goal/feedback/result messages via ActionClient. ```APIDOC ## roslibpy.ActionClient(ros, name, action_type, reconnect_on_close=True) ### Description Action Client of ROS 2 actions. An Action client for ROS 2 Actions can be used by managing goal/feedback/result messages via [`ActionClient`](#roslibpy.ActionClient). ### Parameters * **ros** (`roslibpy.Ros`) – Instance of the ROS connection. * **name** (`str`) – Service name, e.g. `/fibonacci`. * **action_type** (`str`) – Action type, e.g. `example_interfaces/action/Fibonacci`. #### cancel_goal(goal_id) ### Description Cancel an ongoing action. NOTE: Async cancelation is not yet supported on rosbridge (rosbridge_suite issue #909) ### Parameters * **goal_id** – Goal ID returned from `send_goal()` #### send_goal(goal, resultback, feedback, errback) ### Description Start a call to an action. Note: The action client is non-blocking. ### Parameters * **goal** (`roslibpy.Goal`) – Action goal. * **resultback** – Callback invoked on receiving action result. * **feedback** – Callback invoked on receiving action feedback. * **errback** – Callback invoked on error. ### Returns *object* – goal ID if successfull, otherwise `None`. #### wait_goal(goal_id, timeout=None) ### Description Block until the result is available. If `timeout` is `None`, it will wait indefinitely. ### Parameters * **goal_id** – Goal ID returned from `send_goal()` * **timeout** (`int`) – Timeout to wait for the result expressed in seconds. ``` -------------------------------- ### Clean generated artifacts Source: https://github.com/robotwebtools/roslibpy/blob/main/README.rst Use the invoke clean task to remove all generated artifacts from the project. ```bash invoke clean ``` -------------------------------- ### Call Service Synchronously Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Sends a blocking service request to ROS and waits for the result. The request is sent immediately if a connection is already available. ```python client.call_sync_service(message, timeout) ``` -------------------------------- ### get_time Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves the current time from the ROS system. Supports asynchronous and synchronous calls. ```APIDOC ## get_time ### Description Retrieve the current ROS time. ### Method GET (implied) ### Parameters #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns An instance of ROS Time if blocking, otherwise `None`. ``` -------------------------------- ### get_topics_for_type Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves a list of topics in ROS that match a specified topic type. Supports asynchronous and synchronous operations. ```APIDOC ## get_topics_for_type ### Description Retrieve list of topics in ROS matching the specified type. ### Method GET (implied) ### Parameters #### Path Parameters - **topic_type** (string) - Required - The type of the topic to search for. #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns List of topics matching the specified type if blocking, otherwise `None`. ``` -------------------------------- ### Update local repository to main branch Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/readme.md Update your local git repository to use the 'main' branch instead of 'master'. ```bash git branch -m master main git fetch origin git branch -u origin/main main ``` -------------------------------- ### get_service_response_details Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves detailed information about a ROS Service Response type. Supports asynchronous and synchronous calls. ```APIDOC ## get_service_response_details ### Description Retrieve details of a ROS Service Response. ### Method GET (implied) ### Parameters #### Path Parameters - **type** (string) - Required - The type of the service response. #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns Service Response details if blocking, otherwise `None`. ``` -------------------------------- ### get_service_request_details Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Retrieves detailed information about a ROS Service Request type. Supports asynchronous and synchronous calls. ```APIDOC ## get_service_request_details ### Description Retrieve details of a ROS Service Request. ### Method GET (implied) ### Parameters #### Path Parameters - **type** (string) - Required - The type of the service request. #### Query Parameters - **callback** (callable) - Optional - The callback function to handle the response. - **errback** (callable) - Optional - The error callback function. ### Returns Service Request details if blocking, otherwise `None`. ``` -------------------------------- ### call_later Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Schedules a function to be called after a specified delay, once the ROS connection is ready. ```APIDOC ## call_later(delay, callback) ### Description Call the given function after a certain period of time has passed. ### Parameters * **delay** (`int`) – Number of seconds to wait before invoking the callback. * **callback** (`callable`) – Callable function to be invoked when ROS connection is ready. ``` -------------------------------- ### close Source: https://github.com/robotwebtools/roslibpy/blob/main/docs/reference/index.md Disconnects from ROS with an optional timeout for the disconnection process. ```APIDOC ## close(timeout=10) ### Description Disconnect from ROS. ```