How implement a multi-threaded ROS node with callbacks not being subscribers?
I would like to implement a node which listens to a TCP socket which receives asynchronous data, converts it into messages and publishes the latest of these messages at a fix rate in a topic.
The best solution in my eyes would be to have a dedicated thread (spinner) that always reads the latest TCP data and saves it to a variable; it stalls when there is no message. The main spinner would read this variable, convert it into a message, publish it and sleep to for predefined loop rate time.
At the moment I can only find ways to add subscribers to a callback queue but not generic functions such as the envisioned TCP listener.
Therefore my questions:
1) How can i assign a function (the TCP listener) to a callback queue if it is no subscriber?
2) How can I avoid concurrent modification of the data communicated between the two threads? I.e. how do I guarantee that the TCP thread is not concurrently writing to the same memory as the publisher thread is reading from?
3) Would you see a more elegant solution to my problem? I want to make sure that the data on the TCP socket is read asap to not interrupt the program that is sending the data to the socket AND I want to make sure that the topic is only publishing the latest data but with a fixed interval (i.e. data is dropped if it arrives faster than the publishing rate).
Why can't you loop on your TCP listening and publish at the condition that there is new data or that enough time has elapsed ? You just need a publisher that will be invoked potentially as fast as the TCP listener or at a lower rate depending on the condition set.
This is my fallback plan because it does not guarantee that the publishing rate is constant. If the TCP socket is still busy when the next topic message is due, it will be delayed. In the case of a separate thread this can be avoided by only publishing the latest full data block the node received.