开发者

C++/CLI try catch handling

Below is the code I am using to communicate with my arduino on windows xp. The problem I am having is when I have two commands trying to access the port at the same time, which is the UnauthroizedAccessException catch statement, it outputs the errormessage, and doesn't execute one of the commands, How could I go about coding that catch statement so that instead of catching the error or even making it to the error for the program to finish the first command and then execute with other one, something like a queue....

#include "stdafx.h"
#include <iostream>

using namespace System;
using namespace System::IO::Ports;

int main(int argc, char* argv[])
{
    using namespace std;

    String^ portName;
    int baudRate=9600;

    portName="COM4";
    // arduino settings
    SerialPort^ arduino;

    arduino = gcnew SerialPort(portName, baudRate);
    // open port
    try
    {
        arduino->Open();
        {
            if(strcmp(argv[1],"-send")==0){
                String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));

                if(String::Compare(command,"int6")==0){
                    arduino->Write("^");
                }else
                    arduino->Write(command);
            }
            if(strcmp(argv[1],"-get")==0){
                String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));
                arduino->ReadTimeout = 1000;        
                arduino->WriteLine(command);

                String^ result = arduino->ReadLine();

                Console::Write(result);
            }
        }
        // close port to arduino
        arduino->Close();
    }
    catch (IO::IOException^ e){
        Console::Write("errormessagedisconnected");开发者_开发知识库
    }
    catch (TimeoutException^ e){
        Console::Write("errormessage");
    }
    catch (UnauthorizedAccessException^ e){
        Console::Write("errormessage");
    }
    catch (ArgumentException^ e){
        Console::WriteLine(e->GetType()->Name+": incorrect port name syntax, must start with COM/com");
    }
    // end program

    return 0;
}


The best solution would be to not use exceptions here, if possible. I'd also advise you not to simultaneously run two programs that access the same serial port to avoid the exception in the first place. However, with exceptions you could do it like this:

void f()
{
    bool bFinished = FALSE;
    while(!bFinished) {
         try {
             ThisFunctionThrows();
             bFinished = TRUE;
         }
         catch(UnauthorizedAccessException^ e) {
             Console::Write("retrying in 1 sec");
             sleep(1);
         }
    }
}

You can also add a counter if you don't want to wait indefinitely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜