简体   繁体   中英

Emitting signal when bytes are received in serial port

I am trying to connect a signal and a slot in C++ using the boost libraries. My code currently opens a file and reads data from it. However, I am trying to improve the code so that it can read and analyze data in real time using a serial port. What I would like to do is have the analyze functions called only once there is data available in the serial port.

How would I go about doing this? I have done it in Qt before, however I cannot use signals and slots in Qt because this code does not use their moc tool.

Your OS (Linux) provides you with the following mechanism when dealing with the serial port.

You can set your serial port to noncanonical mode (by unsetting ICANON flag in termios structure). Then, if MIN and TIME parameters in c_cc[] are zero, the read() function will return if and only if there is new data in the serial port input buffer (see termios man page for details). So, you may run a separate thread responsible for getting the incoming serial data:

ssize_t count, bytesReceived = 0;
char myBuffer[1024];
while(1)
{
    if (count = read(portFD, 
        myBuffer + bytesReceived, 
        sizeof(myBuffer)-bytesReceived) > 0)
    {
     /*
       Here we check the arrived bytes. If they can be processed as a complete message,
       you can alert other thread in a way you choose, put them to some kind of 
       queue etc. The details depend greatly on communication protocol being used.
       If there is not enough bytes to process, you just store them in buffer
      */
         bytesReceived += count;
         if (MyProtocolMessageComplete(myBuffer, bytesReceived))
         {
              ProcessMyData(myBuffer, bytesReceived);
              AlertOtherThread(); //emit your 'signal' here
              bytesReceived = 0;  //going to wait for next message
         }
    }
    else
    {
     //process read() error
    }
}

The main idea here is that the thread calling read() is going to be active only when new data arrives. The rest of the time OS will keep this thread in wait state. Thus it will not consume CPU time. It is up to you how to implement the actual signal part.

The example above uses regular read system call to get data from port, but you can use the boost class in the same manner. Just use syncronous read function and the result will be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM