information allocation from multiple subscribers using one callback function - c++

I have a C++ ROS question.
I have an assignment which requires me to get information from a number of topics generated by another program. basically. this other program makes a bunch a topics that publishes some basic data, called Pose, from the turtle simulator ros tutorials. the problem is, that I'm not sure how to get all the information I need from all the different topic sources. I know I need to subscribe to a topic to get its info, and i already know how to get all the topic names and open the subscriptions to them. what I am unclear about is whether or not i have to pass in a unique callback function into each new topic I subscribe to. or if there is a way to make one generic callback function that can be passed into all of the subscriptions.
this is my code for this so far
void getTTurtles(char tType, vector < TurtlePose > Tarray) {
int i;
string tname;
stringstream topicName;
//TurtlePose TPose;
ros::master::V_TopicInfo alltopics;
//get all topic names
ros::master::getTopics(alltopics);
for (int i = 0; i < alltopics.size(); i++) {
topicName.clear();
topicName.str("");
tname = getTurtlename(alltopics[i]);
if (tname[0] == 'T') {
Tarray[i].topicname = alltopics[i].name;
Tarray[i].name = tname;
topicName << "/" << TPose[i].name << "/pose";
ros::Subscriber sub_tur = n.subscribe < turtlesim::Pose > (tname, 1, poseCallback);
}
}
return false;
};
as you can see, i have a function that get all the topic names for me. this allows me to grab only the ones whose names start with T (the purpose of the program is to get my own turtle to collect all of his created T-Turtles while avoiding his created Xturtles, so this function it meant to give me a list of the Tturtles and their locations.). I grab name of the topic names of the turtles and from that can grab the actual turtles name as well. but there is a third element i need to extract. the turtlesim::pose information that is being transmitted by all the Tturtle topics. so i use the topic name(T1,T2,T3, etc) to make a subscription to that topic and pass it a callback function, but i'm not sure how to properly write the callback function to appropriately allocate the pose information into the proper location. for example. how to make sure that when the callback function is called as a result of /T1/pose publishing, to make sure that the information it has transmitted end up in Tarray[0].pose instead of Tarray[1] to [2], while also having /T3/pose go into Tarray[2].pose. so on and so forth.
the solution must be scalable, since the number of T-turtle topics being made can be and probably will be changed.
is their a way to write the subscription or the callback function so that you pass in a specific container at the time of creation to be used whenever that specific subscription get information from its subscribed topic?
thanks in advance for the help?

If Your Input Data Is The Same U Can Use AnyNumber Of Subscribers With One CallBack and When Declaring Subscriber U can Pass Any Number Arguments To It So U can Separate Data That's Incoming To Your Node Inside Your Callback (by pushing it out To separate global vectors etc.)

Related

Intercepting all orders with full data in MT4

I'm trying to write a trade copier for MT4. I have already written one for MT5, but the issue I'm having with translation is in intercepting active orders. In MT5, this is relatively simple:
void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request,
const MqlTradeResult &result) {
// Code goes here
}
As shown in the MQL5 documentation, this event intercepts all orders sent from the client and accepted by a trade server.
Looking at the MQL4 documentation, however, I don't see any easy way of doing this. The closest I could get would be to iterate over all the orders by doing this:
for (int i = 0; i < OrdersTotal(); i++) {
if (!OrderSelect(i, SELECT_BY_POS)) {
// Error handling here
}
// Do stuff with this order
}
My understanding is that this code also gets all open orders. However, the issue I'm having is that there are key pieces of information that I cannot determine on these orders:
Slippage
Position-by (for close-by orders)
Action type (close, close-by, delete, modify, send). Although this could be inferred from the fields populated on the order.
In my mind, I could then go and intercept the orders when they're generated (i.e. wrap OrderClose, OrderCloseBy, OrderDelete, OrderModify and OrderSend) and pull the relevant information off of the orders that way. But that still doesn't cover the case where the user enters an order manually.
Is there a way I can intercept all orders data without losing information?

Need information regarding publishing a double variable on to a ROS topic

I am using ROS to publish double variables on to a ROS topic. This topic will be advertising the topic so that any subscribers can access the data.
The following is the code which I have used to publish the data:
ros::NodeHandle n;
ros::Publisher Auc_pub = n.advertise<std_msgs::Float64>("/auc", 1000);
std_msgs::Float64 areaValue;
areaValue.data.push_back(Area)
Auc_pub.publish(areaValue);
Here Area is the double variable which I need to publish it over the topic /auc. I am not able to build this file as don't know how to enter the Area variable into the areaValue.
If you look at the documentation for std_msgs::Float64, it shows that it contains a single data field, which is called data and will be of type double in C++.
So, in your code, you just do:
areaValue.data = Area
assuming that Area is a double.
I suggest that you take a look at the basic Writing a simple Publisher and Subscriber tutorial on the ROS wiki.
EDIT
If what is in the original post is the entirety of your code, then it's probably not going to do exactly what you think it does. If you use the default constructor for a publisher, messages published on them are emitted once immediately. Any nodes subscribed to that topic at the moment of publishing will get the message, and then the topic will be clear. If you want any node that subscribes to the topic to receive the last message published on it, do the following:
ros::Publisher Auc_pub = n.advertise<std_msgs::Float64>("/auc", 1000, true);
That last bool true tells the publisher that it should latch messages that are published.
But you have yet another problem, presuming this is all your code: You never spin, so your node starts up, advertises its topic, publishes one message on it, and then shuts down, taking the topic with it (assuming nothing was subscribed to the topic). You need to add the following before the end of your main:
ros::spin();
This will keep the node active (and thus the topic alive) until ros::ok() returns false, I.E. until the node is killed.
Of course, your message is still only going to be published once, but the topic will at least stay alive. If you want the message to be broadcast periodically, use a ros::Timer and put the pulish call inside the timer's callback.
But seriously, please read the tutorials, they'll walk you through all of this stuff.
I finally found the solution for the problem. I had multiple ros:spinOnce() in the code. And also in the snippet
ros::NodeHandle n;
ros::Publisher Auc_pub = n.advertise<std_msgs::Float64>("/auc", 1000);
std_msgs::Float64 areaValue;
areaValue.data;
Auc_pub.publish(areaValue);
The publisher Auc_pub was created and destroyed ( As I had included the publisher in a function... my bad). Instead, i included the publisher in the main function where the publisher is created only once and stays alive until the execution completes. And, thanks to #aruisdante your suggestion helped.

How does one identify the type (whatToShow) of HistoricalData received from iBrokers API

The IB API reqHistoricalData() method offers a whatToShow argument which can take values to denote you seek data on TRADES, MIDPOINT, BID, ASK etc...
However, the API's historicalData callback, provided to asynchronously receive the requested historical data, doesn't return the relevant whatToShow making it impossible to ascertain what one is looking at. Is it the line for the TRADES, the BIDS or the ASKS I requested???
I get around this the obvious way, namely by requesting TRADES first, waiting for the entirety of the messages to come back and then requesting BIDS then wait again and request ASKS.
Does anyone have a better solution?
Please use the tickerId field properly which is the first parameter in reqHistoricalData() method. When you get the historical data with callbacks, you will be receiving this id back as the first parameter with historicalData().
You just need to keep track which tickerId is associated with which kind of data (bid, ask or trade) to identify that on the callback.
Example:
While requesting:
reqHistoricalData(1, ..whatToShow = Bid,...);
reqHistoricalData(2, ..whatToShow = Ask,...);
Callback handling:
historicalData(int reqId,....)
if(reqId == 1)
//This is the data built of bids as per request1
else if(reqId == 2)
//This is the data built of asks as per request2

data structure for a circuit switching?

I would like to create something like this :
I have a module that does something like 'circuit switching' for a stream of messages. That is, it has a single inport and multiple outports. Once a message arrives at the inport, an outport is selected based on some logic (logic is not important in the context of the question). It is checked whether, there is any ongoing message transfer on the outport (for the first message, there won't be any). If there is no transfer, message is sent to that outport, otherwise, it is kept in queue for that particular outport. I need to decide data structure for this communication. Please advice
My idea is to have a map of outports and corresponding queues.
queue<message> m_incoming_queue;
typedef map<outport*,m_incoming_queue> transaction_map
if this is a good solution, i want to know how do I create a queue at the runtime? as in, I dont know in advance how many outports will there be, I create outports based on requirement.
Maybe something like:
// At beginning
typedef queue<message> MessageQueue
typedef map<outport*, MessageQueue> transaction_map
transaction_map tm() // Create the transaction map
// On receipt of each message
// (Some logic that determines outport* op and message m)
if(tm.count(*op) == 0)
{
// There are no queues yet, create one and insert it
tm.insert(transaction_map::value_type(*op, MessageQueue()))
}
// There is already a queue created, so add to it
tm[*op].push(m)

Asynchronous network calls

I made a class that has an asynchronous OpenWebPage() function. Once you call OpenWebPage(someUrl), a handler gets called - OnPageLoad(reply). I have been using a global variable called lastAction to take care of stuff once a page is loaded - handler checks what is the lastAction and calls an appropriate function. For example:
this->lastAction == "homepage";
this->OpenWebPage("http://www.hardwarebase.net");
void OnPageLoad(reply)
{
if(this->lastAction == "homepage")
{
this->lastAction = "login";
this->Login(); // POSTs a form and OnPageLoad gets called again
}
else if(this->lastAction == "login")
{
this->PostLogin(); // Checks did we log in properly, sets lastAction as new topic and goes to new topic URL
}
else if(this->lastAction == "new topic")
{
this->WriteTopic(); // Does some more stuff ... you get the point
}
}
Now, this is rather hard to write and keep track of when we have a large number of "actions". When I was doing stuff in Python (synchronously) it was much easier, like:
OpenWebPage("http://hardwarebase.net") // Stores the loaded page HTML in self.page
OpenWebpage("http://hardwarebase.net/login", {"user": username, "pw": password}) // POSTs a form
if(self.page == ...): // now do some more checks etc.
// do something more
Imagine now that I have a queue class which holds the actions: homepage, login, new topic. How am I supposed to execute all those actions (in proper order, one after one!) via the asynchronous callback? The first example is totally hard-coded obviously.
I hope you understand my question, because frankly I fear this is the worst question ever written :x
P.S. All this is done in Qt.
You are inviting all manner of bugs if you try and use a single member variable to maintain state for an arbitrary number of asynchronous operations, which is what you describe above. There is no way for you to determine the order that the OpenWebPage calls complete, so there's also no way to associate the value of lastAction at any given time with any specific operation.
There are a number of ways to solve this, e.g.:
Encapsulate web page loading in an immutable class that processes one page per instance
Return an object from OpenWebPage which tracks progress and stores the operation's state
Fire a signal when an operation completes and attach the operation's context to the signal
You need to add "return" statement in the end of every "if" branch: in your code, all "if" branches are executed in the first OnPageLoad call.
Generally, asynchronous state mamangment is always more complicated that synchronous. Consider replacing lastAction type with enumeration. Also, if OnPageLoad thread context is arbitrary, you need to synchronize access to global variables.