How do I open the serial port to a Zaber device? - c++

I have a Zaber linear stage for which I'm developing a C++ backend, to integrate it in my framework.
I have installed the Zaber API by following the instructions from the Zaber webpage. The installer actually generates the dll, lib, and headers necessary for my backend, and I'm confident that my CMake configuration is correct, because I can instantiate objects from the Zaber API.
So now, I am trying in my framework to go through their first code example:
// I commented out the following block:
// - enableDeviceDbStore() is supposed to allow the library to cache
// information from the online database
// - I don't need the online db
// - when I call it, it throws a "string too long" exception.
// try
// {
// zaber::motion::Library::enableDeviceDbStore(".");
// }
// catch (std::exception& e)
// {
// LogError << e.what();
// }
try
{
_connection = zaber::motion::ascii::Connection::openSerialPort("COM6");
// this also throws a "string too long" exception
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
std::vector<zaber::motion::ascii::Device> deviceList;
try
{
deviceList = _connection.detectDevices(false);
// this throws a "Connection has been closed" exception
}
catch (std::exception& e)
{
std::count << e.what() << std::endl;
}
std::count << "Found " << deviceList.size() << " devices." << std::endl;
The problem is, when I use the Zaber Launcher (their UI that allows to control a connected stage), the port is "COM6", and I have made sure to close the connection on the Zaber Launcher before trying to connect with my framework.
I have also tried to launch their pre-configured C++ code example (VS17 solution), with the same problems arising (except their example doesn't catch exceptions, so it just crashes).
None of my exception matches their troubleshooting section.
I don't know how to proceed from here, or how to interpret the "string too long" error message, considering that I'm sure of my connection port.

Related

Google protocol buffer always throw bad allocation exception

I'm newbie in google protocol buffer. And now I have a issue as below:
I have created a simple message in testMessage.proto file:
option optimize_for = SPEED;
message TestMessage
{
optional string foo = 1;
optional string bar = 2;
}
Then I generated this message to testMessage.pb.h and testMessage.pb.cc files and included these files, also added libprotobuf libs to my test project.
Then I wrote a simple code to use this class:
TestMessage testMsg;
testMsg.set_foo("1234"); // set ok
testMsg.set_bar("abcd"); // set ok
string output;
try {
std::cout << testMsg.foo() << std::endl; // output foo ok
testMsg.PrintDebugString(); // throw bad allocation exception here
// testMsg.SerializeToString(&output); // also throw bad allocation exception here
} catch (std::exception ex) {
std::cout << ex.what() << std::endl;
}
This code is very simple, but I cannot understand why it cannot run correctly.
I googled for my issue but there is nowhere mention about it.
Everyone please help me with this issue.

QuickFix error: 58=Conditionally Required Field Missing (268)

This is the server config file
[DEFAULT]
ConnectionType=acceptor
SocketAcceptPort=5001
SocketReuseAddress=Y
StartTime=00:00:00
EndTime=00:00:00
FileLogPath=log
FileStorePath=store
[SESSION]
BeginString=FIX.4.4
SenderCompID=EXECUTOR
TargetCompID=CLIENT1
DataDictionary=/home/idf/Documents/quickfixspec/spec/FIX44.xml
I have a FIXServer and FIXClient quickfix application. The client on connection immediately shows:
IN: 8=FIX.4.4|9=197|35=X|34=34|49=EXECUTOR|52=20141114-19:12:07.219|56=CLIENT1|55=bond3|110=0|268=1|269=0|270=100.272681729868|271=0|278=1862140492|279=0|6350=0|6351=0|6360=0.0528078713919967|6361=0.00698885442689061|10=158
OUT: 8=FIX.4.4|9=123|35=j|34=45|49=CLIENT1|52=20141114-19:12:07.220|56=EXECUTOR|45=34|58=Conditionally Required Field Missing(268)|372=X|380=5|10=139
The server shows:
IN: 8=FIX.4.4|9=123|35=j|34=46|49=CLIENT1|52=20141114-19:12:12.220|56=EXECUTOR|45=35|58=Conditionally Required Field Missing (268)|372=X|380=5|10=137
OUT: 8=FIX.4.4|9=193|35=X|34=36|49=EXECUTOR|52=20141114-19:12:17.221|56=CLIENT1|268=1|279=0|269=0|278=500257692|55=bond|5270=99.54393400065|6271=0|110=0|6350=0|6351=0|6360=0.0107738308608532|6361=0.047250702092424|10=154
I looked this up on http://www.fixtradingcommunity.org/FIXimate/FIXimate3.0/ and it is "Number of entries in Market Data message."
It looks like the server is sending Marketdata and not specifying the number of NoMDEntries? It is a bit strange, because for the Java version anyway, it appears this field gets set automatically, e.g., http://www.quickfixj.org/quickfixj/usermanual/1.5.3/usage/repeating_groups.html
This is the line that causes the problem in the client as it is getting MarketData from the server. I added the try catch block so I could see the exception myself, but it gives less information than if I let QF handle the exception and sending it back to the server through [OUT:]
void MyApplication::fromApp( const FIX::Message& message, const FIX::SessionID& sessionID )
throw( FIX::FieldNotFound, FIX::IncorrectDataFormat, FIX::IncorrectTagValue, FIX::UnsupportedMessageType )
{
std::cout << std::endl << "IN: " << message << std::endl;
try
{
crack( message, sessionID );
}
catch(std::exception& ex)
{
//I suppose I could comment out FIX::FieldNotFound above in the throw clause and ignore this exception
/// here since it seems that the thing is plain wrong since the field IS there!!??
std::cout << "crack exception: " << ex.what() << "\n";
}
}

Poco stops after SMTPClientSession.login

I just started with the Poco library and tried to create an email program (Which I knew virtually nothing about). The following is my code (There may be other problems with it besides the one I've encountered so far, but I just started working on it)
int main(int argc, char** argv)
{
Poco::Net::SocketAddress add("smtp.gmail.com:465");
Poco::Net::StreamSocket sock(add);
Poco::Net::SMTPClientSession sess(sock);
std::cout << "-";
sess.login(
"gmail.com",
Poco::Net::SMTPClientSession::AUTH_LOGIN,
"----",
"----"
);
Poco::Net::MailMessage msg;
Poco::Net::MailRecipient resp(Poco::Net::MailRecipient::PRIMARY_RECIPIENT,"michaelrgoldfine#gmail.com");
msg.addRecipient(resp);
std::string content("HELP SOS");
msg.encodeWord(content);
std::cout << msg.getContent() << "-";
}
When I go into the debugger, it runs fine until it gets to sess.login then suddenly the little bar that represents were I am in the code disappears but the program keeps running (I'm not experienced enough to know what that means). None of the cout stuff I put in actually prints, the debugger just goes past that line but nothing shows up. After a little while this comes up:
terminate called throwing an exception
So what's going on?
You are attempting to use SMTP over TLS (the port 465 passed to the SocketAddress). In one shot you have to learn (1) TLS and certificate handling in POCO, before focusing on (2) your goal: sending an email message.
I suggest to start learning POCO with simpler examples. You can find sample code in the various samples directories in the POCO source code.
I think that your code is just hanging on the TLS handshake, because it doesn't know what to do.
These are the fixes you should do before looking at the solution:
Place your code inside a try/catch block. POCO uses exceptions.
Replace StreamSocket with SecureStreamSocket.
The simplest way to properly initialize SecureStreamSocket is via the Application class. See the Applications slides and Util/samples/SampleApp/src/SampleApp.cpp.
See the documentation for the SSLManager for how to properly tell the Application which certificates to use.
Don't specify an hostname to the login() method. The hostname is optional and should be the client hostname, not the server (See the SMTP RFC).
Remember to actually send the message! Your code is not sending it :-)
OK, and now for the running code. I left steps 4 and 6 as an exercise, but this code will at least run the TLS handshake, will tell you that it cannot verify the server's certificate and, if you answer Yes on the terminal to the questions on the certificates, it will fail the SMTP authentication.
class MiniApp : public Poco::Util::Application {
int main(const vector <string>& args) {
try {
Poco::Net::SocketAddress add("smtp.gmail.com:465");
Poco::Net::SecureStreamSocket sock(add);
Poco::Net::SMTPClientSession session(sock);
session.login(Poco::Net::SMTPClientSession::AUTH_LOGIN, "user", "pw");
Poco::Net::MailMessage msg;
Poco::Net::MailRecipient recipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT,
"michaelrgoldfine#gmail.com");
msg.addRecipient(recipient);
string content("HELP SOS");
msg.encodeWord(content);
} catch (Poco::Exception& e) {
cout << "Error: " << e.displayText() << endl;
return -1;
}
return 0;
}
};
POCO_APP_MAIN(MiniApp)
Yes, so I struggled with login(), trying to use smtp.gmail.com. This is the excerpt of the communication with the SSL session that made it work.
string host("smtp.gmail.com")
Poco::UInt16 port = 587;
SecureSMTPClientSession session(host, port);
session.open();
Poco::Net::initializeSSL();
SharedPtr<InvalidCertificateHandler> ptrHandler = new AcceptCertificateHandler(false);
Context::Ptr ptrContext = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_RELAXED, 9, true, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
SSLManager::instance().initializeClient(0, ptrHandler, ptrContext);
try
{
// SSL
session.login();
if (session.startTLS(ptrContext))
{
session.login(SMTPClientSession::AUTH_LOGIN, "user#gmail.com", "yourpassword");
session.sendMessage(message);
}
session.close();
Poco::Net::uninitializeSSL();
}
catch (SMTPException &e)
{
cout << e.message() << endl;
session.close();
Poco::Net::uninitializeSSL();
return 0;
}
Original source:
http://www.axistasoft.sg/tutorials/cpp/poco/item/sending-email-messages-using-smtp-protocol

c++ exceptions and program execution logic

I have been thru a few questions but did not find an answer.
I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress?
For example, I want to process exceptions at four stages of the program and know that exception happened at that specific stage:
1. Initialization
2. Script processing
3. Computation
4. Wrap-up.
At this point, I tried this:
int main (...)
{
...
// start logging system
try {
...
}
catch (exception &e)
{
cerr << "Error: " << e.what() << endl;
cerr << "Could not start the logging system. Application terminated!\n";
return -1;
}
catch(...)
{
cerr << "Unknown error occured.\n";
cerr << "Could not start the logging system. Application terminated!\n";
return -2;
}
// open script file and acquire data
try {
...
}
catch (exception &e)
{
cerr << "Error: " << e.what() << endl;
cerr << "Could not acquire input parameters. Application terminated!\n";
return -1;
}
catch(...)
{
cerr << "Unknown error occured.\n";
cerr << "Could not acquire input parameters. Application terminated!\n";
return -2;
}
// computation
try {
...
}
...
This is definitely not centralized and seems stupid.
Or maybe it is not a good concept at all?
You could keep a global variable containing the state of the program, and print it out in the catch block. Then you would only need two catch blocks, one for std::exception and one for everything else.
It seems to me that you're trying to use exceptions as (more or less) a replacement for logging. I think in this case, you'd be a lot better off using the two together -- in particular, I'd probably have a small exception handler that put output in the log, so your code would look something like this:
try {
// start logging system
}
catch (exception const &e) { std::cerr << e.what << "error starting logging"; }
catch (...) { std::cerr << "Unknown error starting logging"; }
try {
{ scoped_log("script processing");
start_script();
}
{ scoped_log("computation");
do_computation();
}
{ scoped_log("wrap up");
wrap_up();
}
}
catch(std::exception const &e) { log << "error: " << e.what() << "\n"; }
catch(...) { log << "Unknown exception\n"; }
where "scoped_log" is a simple class something like:
class scoped_log {
std::string caption;
public:
scoped_log(std::string const &c) : caption(c) {
log << "Starting: " << caption << "\n";
}
~scoped_log() { log << "Finished: " << caption << "\n"; }
};
This allows you to centralize most of the exception handling. The only exception (no pun intended) is for starting up the logging system itself -- you obviously can't use logging to report problems with starting up the logging system.
Once the logging system is up, however, things are a lot simpler -- you use the combination of logging and exception handling to track down when the problem occurred. Keep one minor detail in mind: since the scoped_log is an object that's destroyed when the scope is exited (for any reason), the log will have a structure that might (at least initially) seem a bit misleading -- the error message will follow the "finshed xxx" message in the log. For example, if a script file couldn't be opened, your log might look something like this:
starting script processing
finished script processing
error: could not open file: 'script.input'
At least IMO, that's unlikely to cause a problem if you're aware of the situation.
In my opinion, exceptions should be (generally) caught in 5 conditions:
You can legitimately handle the exception and continue normally (e.g. you caught a boost::bad_lexical_cast from user input, but can recover by reporting the error to the user).
You need to translate the exception from one source to another (e.g. your library uses another library as a pure implementation detail and wants to translate a 'socket_exception' into a 'service_exception' or something of the sort). In .Net, I'd do this by throwing a new exception instance w/ an inner exception. In C++, it can be useful to provide a consistent interface to your users, especially if you're, for instance, only throwing exceptions derived from std::exception, but a dependent library throws exceptions from a non-standard type (string, int, const char*, custom type, etc).
You're writing a cross language wrapper. C++/C, C++/Fortran, etc. C++ exceptions don't tend to cross these barriers well, and you're best off translating them into the target runtime's error handling facilities, if possible.
You're in main, and wish to capture some slight information from the exception & log before you crash. If you do so, there's two primary camps on what to do next: exit(1) or throw; and generate a core (on *nix). I've mixed feelings...
much like in main, around a thread entry. Can be helpful to log why a thread terminated, and then treat thread termination in a appropriate manner.
A simple way of having exception processing centralized is creating a simple function to process the exceptions and then using a generic catch that calls the function:
void processExceptions( std::string const & stage )
{
std::cout << "Exception caught at stage " << stage << std::endl;
try {
throw; // rethrow the last caught exception
}
catch ( exception1 const & ) {
// do process 1
}
catch ( exception2 const & ) {
// ...
}
}
int main()
{
try {
initialize();
}
catch ( ... ) {
processExceptions( "initialization" );
}
try {
stage2();
}
catch ( ... ) {
processExceptions( "stage2" );
}
}
I have never used that technique to identify when an exception was caught, but it is quite useful to avoid duplicating exception processing code in many places if it is the same.
Note that if you call the function when no exception has been thrown (outside of a catch) you will get undefined behavior and more often than not your application will die.
The other alternative is to have distinct, by-you-defined exceptions which you then handle in one central place instead of different return values. So when the exception occurs like "could not acquire input parameters" you would throw something like an "invalid_parameters exception" with some more context information added about the reason for the exception. Then in a central place you display the error.
If you really want to more centralize this, you could define your own error classes such as
class does_not_open {};
class cannot_write {};
or so. You'll need more work in your different parts, e.g., check if open succeeds; if not, throw does_not_open (etc.). But after you organize yourself this way, you can put the entire main part of your code into the following form:
try{
}
catch(does_not_open &e){
}
catch(cannot_write &e){
- your code here -
}
catch(...){
- your code here -
}
Not sure this accomplishes what you were hoping for...but gl. :)

How to log an c++ exception

Do you know how can I log the exception ?
right now the message in the catch statement is printed, but i cannot understood why insĀ“t Manage.Gere() called sussefully .
try{
Manager.Gere(&par,&Acc, coman, comando, RunComando, log, &parti, comandosS, RunComandosSuper,true);
}
catch (...)
{
log("ERROR ENTER GERE*****");
}
Perif::Gere(CString *par, CString *Acc, HANDLE coman, HANDLE comando, HANDLE RunComando, Log &log, CString *parti, HANDLE comandosS, HANDLE RunComandosSuper,bool first)
{
log->LogD("Perif :: Gere Enter****** "); //It doesnt get printed
}
A well-behaved API should only throw objects of types derived from std::exception. If that's the case, then the exception will have a member function const char *what() containing a message, which will hopefully describe the error. So you could try this, and hope that it helps:
try {
Manage.Gere(...);
} catch (const std::exception &e) {
log(e.what());
} catch (...) {
log("Manage.Gere threw unknown exception");
}
If it throws a type that isn't a std::exception, then you will need to look at the documentation and/or source for the function to see what could go wrong, and what types it does throw. If none of this is available, I would be looking for a better library.
First thing you need there is find which exceptions Manage.Gere can throw.
Then catch them specifically like catch(FirstExceptionGereThrows &exc) and when you catch all possible exceptions, you'll know what is failing in Manage.Gere.
catch(FirstException &exc){
log << "Failed because FirstException\n";
}catch(SecondException &exc){
log << "Failed because SecondException\n";
}
After, and if you are lucky enough the exceptions thrown by Manage.Gere may include some extra info about the crash which you could log as well.
catch(FirstException &exc){
log << "Failed because FirstException: " << exc.what() << "\n";
}
As others have suggested, RTFM is really the answer. However, I've found that lazy programmers often write code like:
if ( something ) {
throw "Something has happened!";
}
so it is always worthwhile trying to catch both const char * ans std::string:
try {
// stuff
}
catch( const char * s ) {
cerr << s << endl;
}
catch( const std::string & s ) {
cerr << s << endl;
}
// other catches here
You can also use my tool as an external debugger which catches C++ exceptions and automatically create minidump files for offline debugging. See http://alax.info/blog/1211 for details.
The good thing is that you don't need any code for this, or you can even debug an application which you don't have code for, or you cannot rebuild it for any reason. The dump file will get you stacks and information, and the application will be able to continue execution.