⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tserial_event.cpp

📁 串口通讯例程
💻 CPP
📖 第 1 页 / 共 2 页
字号:

    /* --------------------------------------------- */
    if (erreur!=0)
    {
        CloseHandle(serial_handle);
        serial_handle = INVALID_HANDLE_VALUE;
    }
    else
    {
        Start_thread();
    }

    /* --------------------------------------------- */
    return(erreur);
}
/* -------------------------------------------------------------------- */
/* --------------------------    OnCharArrival ------------------------ */
/* -------------------------------------------------------------------- */
void          Tserial_event::OnCharArrival    (char c)
{
    if ((OnCharArrivalManager!=0) && ready)
        OnCharArrivalManager(c);
}
/* -------------------------------------------------------------------- */
/* --------------------------  OnConnected    ------------------------- */
/* -------------------------------------------------------------------- */
void          Tserial_event::OnConnected      (void)
{
    if ((OnConnectedManager!=0) && ready)
        OnConnectedManager();
}
/* -------------------------------------------------------------------- */
/* --------------------------  OnDisconnected ------------------------- */
/* -------------------------------------------------------------------- */
void          Tserial_event::OnDisconnected      (void)
{
    if (OnDisconnectedManager!=0)
        OnDisconnectedManager();
}
/* -------------------------------------------------------------------- */
/* --------------------------   OnCharSent    ------------------------- */
/* -------------------------------------------------------------------- */
void          Tserial_event::OnCharSent       (void)
{
    if ((OnCharSentManager!=0) && ready)
        OnCharSentManager();
}
/* -------------------------------------------------------------------- */
/* ---------------------  setManagerOnCharArrival --------------------- */
/* -------------------------------------------------------------------- */
/*
    Transmitting a null parameter will clear the variable in any case
*/
void         Tserial_event::setManagerOnCharArrival(type_charEvent manager)
{
    if ((OnCharArrivalManager==0) || (manager==0))
        OnCharArrivalManager = manager;
}
/* -------------------------------------------------------------------- */
/* ----------------------  setManagerOnConnected  --------------------- */
/* -------------------------------------------------------------------- */
void         Tserial_event::setManagerOnConnected  (type_voidEvent manager)
{
    if ((OnConnectedManager==0) || (manager==0))
        OnConnectedManager = manager;
}
/* -------------------------------------------------------------------- */
/* -----------------------  setManagerOnDisconnected  ----------------- */
/* -------------------------------------------------------------------- */
void         Tserial_event::setManagerOnDisconnected  (type_voidEvent manager)
{
    if ((OnDisconnectedManager==0) || (manager==0))
        OnDisconnectedManager = manager;
}
/* -------------------------------------------------------------------- */
/* --------------------   setManagerOnCharSent   ---------------------- */
/* -------------------------------------------------------------------- */
void         Tserial_event::setManagerOnCharSent   (type_voidEvent manager)
{
    if ((OnCharSentManager==0) || (manager==0))
        OnCharSentManager = manager;
}
/* -------------------------------------------------------------------- */
/* -----------------------   getNbrOfBytes  --------------------------- */
/* -------------------------------------------------------------------- */
int Tserial_event::getNbrOfBytes    (void)
{
    struct _COMSTAT status;
    int             n;
    unsigned long   etat;

    n = 0;

    if (serial_handle!=INVALID_HANDLE_VALUE)
    {
        ClearCommError(serial_handle, &etat, &status);
        n = status.cbInQue;
    }
    return(n);
}
/* -------------------------------------------------------------------- */
/* --------------------------    sendChar     ------------------------- */
/* -------------------------------------------------------------------- */
void Tserial_event::sendChar (char data)
{
    data_to_send = data;
    SetSignal(SIG_DATA_IN);
}
/* -------------------------------------------------------------------- */
/* --------------------------       Run       ------------------------- */
/* -------------------------------------------------------------------- */

/** 
 this function is the main loop of the Tserial object. There is a
 do while() loop executed until either an error or a PowerDown is 
 received.
 this is not a busy wait since we use the WaitForMultipleObject function
*/

void Tserial_event::Run(void)
{
    int           done;
    long          status;
    unsigned long read_nbr, result_nbr;
    char          data;
    char          success;

    ready             = true;
    done              = 0;
    tx_in_progress    = 0;
    rx_in_progress    = 0;
    OnConnected();
    GetLastError();     // just to clear any pending error

    /* ----------------------------------------------------------- */
    while(!done)
    {
        /* ---------------------------------------------------- */
        /*            checking for incoming                     */
        /* ---------------------------------------------------- */
        if (!rx_in_progress)      // if no reception is in progress
        {                         // I start a new one
            do
            {
                success = (char) ReadFile(serial_handle,&data,1,&read_nbr,&ovReader);
                // reading one byte only to have immediate answer on each byte
                if (success)
                {
                    // immediate return => data processing 
                    ResetEvent(serial_events[SIG_COM_READER]);
                    OnCharArrival(data);
                    rx_in_progress = 0;
                }
                else
                {
                    if(GetLastError() != ERROR_IO_PENDING )
                        done=1;
                    else
                        rx_in_progress=1; // read is pending
                                          // will wait for completion in
                                          // WaitForMultipleObjects
                }
            }
            while(success); 
            // as long as the read is returning data, I'll read them
        }

        /* ---------------------------------------------------- */
        /*            Waiting  for signals                      */
        /* ---------------------------------------------------- */
        if (!done)
        {
            // Main wait function. Waiting for something to happen. 
            // This may be either the completion of a Read or a Write or
            // the reception of Power On, Power Down, new Tx
            //
            status = WaitForMultipleObjects(TSERIAL_SIGNAL_NBR, serial_events,
                                            FALSE, INFINITE);

            /* processing answer to filter other failures */
            status = status - WAIT_OBJECT_0;
            if ((status<0) || (status>=TSERIAL_SIGNAL_NBR))
                done=1;
            else
            {
                /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
                /* ++++++++++++++++++++ EVENT DISPATCHER ++++++++++++++++++ */
                /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
                switch(status)
                {
                    /* ######################################################## */
                    case SIG_POWER_ON :
                        /* * /
                        printf("Tserial : power on\n");
                        /* */
                        break;
                    /* ######################################################## */
                    case SIG_POWER_DOWN:
                        /* * /
                        printf("Tserial : power down\n");
                        /* */
                        done = 1;
                        break;
                    /* ######################################################## */
                    case SIG_DATA_IN:
                        // Signal asserted that there is a new valid data
                        // in the "data_to_send" variable
                        success = (char) WriteFile(serial_handle, &data_to_send, 1,
                                            &result_nbr, &ovWriter);
                        // sending data on the port
                        if (success)
                        {
                            // as long as the write is returning immediately,
                            // I'll be ready to send additonnal data
                            tx_in_progress = 0;
                            OnCharSent();
                            // calling the frame to indicate that the transmission
                            // is over and we're ready to receive a new data
                        }
                        else
                        {
                            if(GetLastError() == ERROR_IO_PENDING )
                                tx_in_progress=1;       // write is pending
                            else
                                done = 1;               // failure !
                        }

                        break;
                    /* ######################################################## */
                    case SIG_COM_READER:
                        // reading the result of the terminated read
                        if (GetOverlappedResult(serial_handle, &ovReader,
                            &result_nbr, FALSE))
                        {
                            // no error => OK
                            // Read operation completed successfully
                            ResetEvent(serial_events[SIG_COM_READER]);
                            // Write operation completed successfully
                            if (result_nbr)
                                OnCharArrival(data);
                            // if incoming data, I process them
                            rx_in_progress = 0; // read has ended
                        }
                        else
                        {
                            // GetOverlapped didn't succeed !
                            // What's the reason ?
                            if(GetLastError() == ERROR_IO_PENDING )
                                // still pending ?? ok no proble, I'll
                                // wait for completion
                                rx_in_progress = 1; // read not ended
                            else
                                // other reason !? this is a failure
                                // exiting
                                done = 1;  // failure
                        }
                        break;
                    /* ######################################################## */
                    case SIG_COM_WRITER:
                        // WriteFile has terminated
                        // checkin the result of the operation
                        if (GetOverlappedResult(serial_handle, &ovWriter,
                            &result_nbr, FALSE))
                        {
                            // Write operation completed successfully
                            ResetEvent(serial_events[SIG_COM_WRITER]);
                            // Write operation completed successfully
                            tx_in_progress = 0; // write has ended
                            OnCharSent();       // checking if there are
                                                // other messages waiting
                        }
                        else
                        {
                            // GetOverlapped didn't succeed !
                            // What's the reason ?
                            if(GetLastError() == ERROR_IO_PENDING )
                                // still pending ?? ok no proble, I'll
                                // wait for completion
                                tx_in_progress = 1; // write not ended
                            else
                                // other reason !? this is a failure
                                // exiting
                                done = 1;  // failure
                        }
                        break;
                    /* ######################################################## */
                }
                /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
                /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
                /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            }
        }
    };

    powerDown();
}
/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -