ROS2 Dynamic messages template - c++

I have a question regarding ROS2 messages or possibly just standard C++, maybe one of you have tried something similar before, or can tell me that what I am trying to accomplish won't work.
What I'm trying to create is a library that I can use to quickly create a ROS2 Node, dynamically add publishers and/or subscribers, depending on the situation, before starting the node.
The problem I'm facing is that ROS2 uses message types like std_msgs::msg::String. Example source can be found on github.
The source uses the following code to create a subscriber:
subscription_ = this->create_subscription<std_msgs::msg::String>("topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
I would like to create a function that can create a subscriber using a given message type i.e.:
void createListener(std::string topicName, 'messagetype')
{
auto subscription_ = this->create_subscription<'messagetype'>(topicname, 10, [this]{}, this, _1));
//adding the created subscriber to a list is already done
}
This would allow me to use the same function while still being able to use different messages like:
nav_msgs::msg::Path
geometry_msgs::msg::Point
without having to create a new function for every message type.
I can't seem to find the template type that is used in the create_subscribtion<>() function, all I can find is that each message creates its own type.
std_msgs::msg::String would return the std_msgs::msg::String_<std::allocator<void>> type.
Is there a way that i can make this work?

You could use templates here right, by doing the following:
template <typename MsgType>
void createListener(std::string topicName)
{
auto subscription_ = this->create_subscription<MsgType>(topicname, 10, [this]{}, this, _1));
//adding the created subscriber to a list is already done
}
This function can then be called, for example by:
createListener<nav_msgs::msg::Path>("topicName")

Related

Adding non-cObject data (custom class) into a packet in Omnet++

I am trying to create a packet and attach a custom object. I read through the manual and tried following their suggestions but I am stuck.
According to the manual: Non-cObject data can be attached to messages by wrapping them into cObject, for example into cMsgPar which has been designed expressly for this purpose.
cMsgPar has the function: setObjectValue(), so I attempted to add the class via this code:
// b is a pointer to a custom object
auto packet = createPacket("Msg");
packet->addPar("data");
packet->par("data").setObjectValue(b);
but I get a 'no matching function for call' error for the setObject value function. I checked the function declaration, which is:
cMsgPar & setObjectValue (cOwnedObject *obj)
which brings me back to square one. Trying to convert my custom class into something acceptable by Omnet to send to other nodes in my network.
Any help would be appreciated.
The recommended way of carrying own classes (objects) via message in OMNeT++ is to add this to definition of a message. For example:
cplusplus {{
#include "MyClass.h" // assuming that MyClass is declared here
typedef MyClass *MyClassPtr;
}};
class noncobject MyClassPtr;
packet MyPacket {
int x;
MyClassPtr ptr;
}
Reference: OMNeT++ Simulation Manual - 6.6 Using C++ Types
this is how i do it as an easy solution. Omnet++ already gave alot of ways to do it.
msg->addPar("preamble");
msg->par("preamble").setLongValue(0b01010101010101);
send(msg,"phyout");
i hope it will helpout

ROS subscribe callback - using boost::bind with member functions

I'm trying to subscribe to different topics in ROS (one for every vehicle that pops up) using the same callback for all of them. The idea is that boost::bind will pass the topic name as an additional argument so I know which vehicle I should access in the callback.
The problem is that, even though I've gone through multiple questions on the topic, none of the solutions seem to work.
Basically, I have the following class VOBase containing a std::map<std::string, VOAgent*> agents_ with a member function as follows:
void VOBase::callback_agentState(const custom_msgs::VState::ConstPtr& vStateMsg,
std::string topic) {
// [...] regex to find agent name from topic string
std::string agent_name = match.str();
// [...] Check if agent name exists, else throw exception
// Process message
agents_[agent_name]->pos_ = vStateMsg->pose.position; // etc.
}
Which I'm calling through this subscription:
void VOBase::callback_agentList(const custom_msgs::VehicleList& vehListMsg) {
// [...] New agent/vehicle found: process vehListMsg and get agent_name string
// Subscribe to VState
topic_name = agent_name + "/state_estimate";
subscribers_[topic_name] = nodeHandlePtr->subscribe<custom_msgs::VState>(topic_name, 1,
std::bind(&VOBase::callback_agentState, this, _1, topic_name));
}
However, I'm getting a template argument deduction/substitution failed with all the candidates and this error:
mismatched types ‘std::reference_wrapper<_Tp>’ and ‘VO::VOBase*’
typename add_cv<_Functor>::type&>::type>()(
I've tested a number of the solutions out there, e.g. using std::ref(this) to get a std::reference_wrapper<_Tp> instead of a VO::VOBase* (the reference doesn't survive though: use of deleted function), using boost::bind instead of std::bind (but it should be all the same since C++11), with and without the ...::ConstPtr for the ROS message in the callback function arguments (and in the subscribe<acl_msgs::ViconState::ConstPtr>, etc. So I'm just juggling with partial solutions and their permutations here...
Any clues?
I haven't looked into the specifics of the code you show (it's hard to figure out the information not shown and deduce what's required).
However, last time I helped someone with ROS subscriptions and the type-deduction, it was apparent that the handler should take a shared_ptr to the message. This might help you get started seeing a solution:
Error using boost::bind for subscribe callback

Submitting concurrent task via QFuture from GUI thread

In order to avoid computations in GUI thread on button click I'm trying to run it in separate thread.
As soon as I want to have ability to monitor progress my code is based on this source.
So, my code is:
futureWatcher.setFuture(QtConcurrent::mapped(library_pool.cbegin(), library_pool.cend(), util->loadFilesInLibrary(library_pool)));
futureWatcher.waitForFinished();
table = QFuture::result();
Which is quite similar to the given sorce from qt docs, but it gives corresponding errors:
C2893: Failed to specialize function template 'QFuture<QtPrivate::MapResultType<void,MapFunctor>::ResultType> QtConcurrent::mapped(Iterator,Iterator,MapFunctor)'
C2780: 'QFuture<QtPrivate::MapResultType<void,MapFunctor>::ResultType> QtConcurrent::mapped(const Sequence &,MapFunctor)': expects 2 arguments - 3 provided
C2955: 'QFuture': use of class template requires template argument list
'QFuture<T>::result': illegal call of non-static member function
So, how do I properly populate worker thread(s) with function from non-gui class in button_clicked slot without making GUI hand?
UPD
Well, I've succeeded with compiling code for now and this is how it works:
futureWatcher.setFuture(QtConcurrent::run(&this->util, &Utils::loadFilesInLibrary, library_pool.at(0)));
futureWatcher.waitForFinished();
library_pool = future.result();
But button click still results to error in runtime:
My function which I'm trying to run generates no widgets, so the reason of this message is unclear.
I've read couple questions (like this) where all the code stated to work but it resides only in main() which is far from my needs. So, again, how do I start it from GUI thread?
You can use non-static members with QtConcurrent methods with the help of a wrapper. There is more discussion about it at Qt's Forums. Here's another similar question asking about how to use the wrapper.
struct AddWrapper {
Utils *utils = nullptr;
typedef MyType result_type;
AddWrapper(Util *u): instance(u) {};
MyType operator()(const MyType &t) const {
return instance->longMethod(t);
}
}
Utils *foo = new Utils();
AddWrapper wrapper(foo);
QFuture<MyType> results = QtConcurrent::mapped(myList, wrapper);

Using preprocess hook on specific node type in Drupal 8

I've had success using preprocess page hooks such as:
function mytheme_preprocess_page__node_front(&$variables) {
...
}
and
function mytheme_preprocess_page__node_12(&$variables) {
...
}
which correlate with custom templates named page--front.html.twig and page--12.html.twig, respectively.
I'm trying to implement the same hook and template pairing for a content type called Video. I understand that there is a difference in that my examples have been custom templates for specific pages while my goal is a custom template for an entire content type, but I got a custom template called node--video.html.twig that works as a template for all video pages. However when I try to write a hook based on this template name:
function mytheme_preprocess_node__video(&$variables) {
...
}
this does not work. I think that I either can't define a hook like this, or I'm just naming it incorrectly. I found a couple threads somewhat relating to this such as this that seem to imply that I need to define a hook for all nodes and then write an if statement that handles each type separately.
So.......
Final Question: Can I define a hook for an entire content type, and if so what am I doing wrong?
Use condition within the preprocessor to get the node type and then either do your logic within, or invoke another function.
function mytheme_preprocess_node(&$variables) {
switch ($variables['node']->getType()) {
case "video":
// ...
break;
case "something_else":
// ...
break;
}
}
You could in theory emulate what you are trying to achieve by trying to invoke a function named mytheme_preprocess_node__" . $variables['node']->getType() if it exists, but is too much fuss without a clear benefit.
In drupal 7 from zen template I used to use this generic solution. I think it is still a viable solution on drupal 8:
function mytheme_preprocess_node(&$variables) {
...
// Add global modification that works for all node type
$function = __FUNCTION__ . '__' . $variables['node']->getType();
// Each node type can have its own specific function
if (function_exists($function)) {
$function($variables, $hook);
}
...
}
You can then now add preprocess function that will only works for you node type.
function mytheme_preprocess_node__video(&$variables) {
...
}
Instead of having one big function, each node type's preprocess logic has its own function. It's better for maintainability.

How to make a C++ boost::signal be caught from an object which encapsulates the object which emits it?

I have a TcpDevice class which encapsulates a TCP connection, which has an onRemoteDisconnect method which gets called whenever the remote end hangs up. Then, there's a SessionManager object which creates TcpSession objects which take a TcpDevice as a communication channel and inserts them in an internal pointer container for the application to use. In case any of the managed TcpSessions should end, I would like the SessionManager instance to be notified about it and then remove the corresponding session from the container, freeing up the resources associated with it.
I found my problem to be very similar to this question:
Object delete itself from container
but since he has a thread for checking the connections state, it gets a little different from mine and the way I intended to solve it using boost::signals, so I decided to go for a new question geared towards it - I apologize if it's the wrong way to do it... I'm still getting the feel on how to properly use S.O. :)
Since I'm kind of familiar with QT signals/slots, I found boost::signals offers a similar mechanism (I'm already using boost::asio and have no QT in this project), so I decided to implement a remoteDeviceDisconnected signal to be emitted by TcpDevice's onRemoteDisconnect, and for which I would have a slot in SessionManager, which would then delete the disconnected session and device from the container.
To initially try it out I declared the signal as a public member of TcpDevice in tcpdevice.hpp:
class TcpDevice
{
(...)
public:
boost::signal <void ()> remoteDeviceDisconnected;
(...)
}
Then I emitted it from TcpDevice's onRemoteDisconnect method like this:
remoteDeviceDisconnected();
Now, is there any way to connect this signal to my SessionManager slot from inside session manager? I tried this:
unsigned int SessionManager::createSession(TcpDevice* device)
{
unsigned int session_id = session_counter++;
boost::mutex::scoped_lock lock(sessions_mutex);
sessions.push_back(new TcpSession(device, session_id));
device->remoteDeviceDisconnected.connect(boost::bind(&SessionManager::removeDeadSessionSlot, this));
return session_id;
}
It compiles fine but at link time it complains of multiple definitions of remoteDeviceDisconnected in several object code files:
tcpsession.cpp.o:(.bss+0x0): multiple definition of `remoteDeviceDisconnected'
tcpdevice.cpp.o: (.bss+0x0): first defined here
sessionmanager.cpp.o:(.bss+0x0): multiple definition of `remoteDeviceDisconnected'
tcpdevice.cpp.o: (.bss+0x0): first defined here
I found this strange, since I didn't redefine the signal anywhere, but just used it at the createSession method above.
Any tips would be greatly appreciated! Thank you!
My bad! Like we all should expect, the linker was right... there was indeed a second definition, I just couldn't spot it right away because it wasn't defined by any of my classes, but just "floating" around one of my .cpp files, like those found on boost::signals examples.
Just for the record, the initial idea worked like a charm: when a given TcpDevice gets disconnected from the remote end, it emits the remoteDeviceDisconnected signal, which is then caught by the SessionManager object which holds the TcpSession instance that points to that TcpDevice. Once notified, SessionManager's method removeDeadSessionSlot gets executed, iterating through the sessions ptr_list container and removing the one which was disconnected:
void SessionManager::removeDeadSessionSlot()
{
boost::mutex::scoped_lock lock(sessions_mutex);
TcpSession_ptr_list_it it = sessions.begin();
while (it != sessions.end()) {
if (!(*it).device->isConnected())
it = sessions.erase(it);
else
++it;
}
}
Hope that may serve as a reference to somebody!