lambdaprime / jros2client

Java module to interact with ROS2 (Robot Operating System)
5 stars 3 forks source link

Simple publisher/subscriber example doesn't work #2

Closed dbortoluzzi closed 1 year ago

dbortoluzzi commented 1 year ago

Hi, I've tried to improve class PolygonApp, adding also the subscriber. Here below the code:

public class PolygonApp {

    public static void main(String[] args) throws Exception {
        var cli = new CommandLineInterface();
        String topic = "/PolygonExample";
        try (var client = new JRos2ClientFactory().createClient()) {
            var publisher = new TopicSubmissionPublisher<>(PolygonStampedMessage.class, topic);
            client.publish(publisher);
            cli.print("Press any key to stop publishing...");
            while (!cli.wasEnterKeyPressed()) {
                PolygonStampedMessage polygon = new PolygonStampedMessage()
                        .withHeader(new HeaderMessage()
                                .withFrameId("/map")
                                .withStamp(Time.now()))
                        .withPolygon(new PolygonMessage()
                                .withPoints(new Point32Message[]{
                                        new Point32Message(2F, 2F, 0F),
                                        new Point32Message(1F, 2F, 3F),
                                        new Point32Message(0F, 0F, 0F)}));
                publisher.submit(polygon);
                cli.print("Published");
                Thread.sleep(1000);
            }

            // register a new subscriber
            client.subscribe(new TopicSubscriber<>(PolygonStampedMessage.class, topic) {
                @Override
                public void onNext(PolygonStampedMessage item) {
                    cli.print("message received");
                    cli.print(item.polygon.points.length);
                    // request next message
                    getSubscription().get().request(1);
                }
            });
        }
    }

But it doesn't work! Why? I'm unable to make the communication work... I've tried also to customize the RtpsTalkConfiguration, but without success.

Please help me, otherwise I have to switch to ros2_java.

Best regards, Daniele

dbortoluzzi commented 1 year ago

Publisher and subscriber can't live in the same thread.

lambdaprime commented 1 year ago

Hi @dbortoluzzi,

By default subscriber always runs on its own thread.

The problem is that you run while loop BEFORE you actually register your subscriber. If you put subscribe call before while loop it should be ok.

Please note - we do not recommend using same object of JRosClient for pub/sub to same topic. It is preferrable to use two separate objects. See PublisherSubscriberApp example.

dbortoluzzi commented 1 year ago

Thanks!