6.3 A hello world example!

Communicating between threads in URScript should not generally be done using ROS2, as the overhead makes it incredibly inefficient. It does however make a good example for how to use ROS2 in URScript.

Hello World

global iter = 0
 
# A thread responsible for sending messages
thread publish():
  # Prepare a handle for a topic, that can be used to send messages. The name is test, and the type is std_msgs/String
  pub_handle = ros_publisher_factory(topic="test", msg_type="std_msgs/String", history="keep_last", depth=100, durability="transient_local")
  while(True):
    msg = str_cat("Hello world ",iter)
    pub_handle.write(struct(data=msg))
    iter = iter + 1
    textmsg(str_cat("Published ", msg))
    sleep(0.5)
  end
end
myPublisher = run publish()
 
thread readOneItem():
 sub_handle = ros_subscriber_factory(topic="test", msg_type="std_msgs/String")
  sleep(3)
  while (True):
    value = sub_handle.read() # This read will block until something is available
    textmsg(str_cat("Read 1 item: ",value))
  end
end
myReadOneItem = run readOneItem()
 
# Insert any other threads you want to use here above the join
 
join myReadOneItem # Avoid the main thread exiting

To experiment with accessing the ROS2 history, the following two threads can added to the above program. Make sure to add it before the join line.

Observe that the subscriber handles operate independently. A read from one handle will not affect the history of the others.

More Subscribers

# This thread will repeatedly try to read 10 items from the topics history.
thread subscribe_history():
  sub_handle = ros_subscriber_factory(topic="test", msg_type="std_msgs/String", history="keep_last", depth=100, durability="transient_local")
  sleep(3)
  while (True):
    value = sub_handle.read_history(10) # Read 0-10 items from the history, depending on how many are available
    textmsg(str_cat("Read 10 history items: ",value))
    waittime = (iter % 10)/2.0 # Wait for a pseudo random amount of time, to see how the read reacts to different history sized
    sleep(waittime)
  end
end
mySubscriber = run subscribe_history()
 
thread subscribe2():
 # This subhandle only has a history depth of 1, and thus at most one message will ever be returned by read_history
 sub_handle = ros_subscriber_factory(topic="test", msg_type="std_msgs/String", history="keep_last", depth=1, durability="transient_local")
  sleep(3)
  while (True):
    value = sub_handle.read_history(1) # Read one message from
    if length(value)>0: # We are not guaranteed any items will be read
      textmsg(str_cat("Read 1 history items: ",value[0]))
    end
    waittime = (iter % 10)/2.0
    sleep(waittime)
  end
end
mySubscriber2 = run subscribe2()

Try playing around with history depth, waits and other parameters to gain a better understanding of the ROS2 functionality.