c++ - Win32 API: how to read the serial, or exit within a timeout if wasn't a data -


i need function read data serial port, or return if no data within time interval. e.g. under gnu/linux bundle poll()orselect()+read(). there way in windows using handle file?

below code illustrate: should work needed, function getoverlappedresult() either buggy, either not documented; instead of number of bytes read @ moment reports nothing(not zero, i.e. if didn't initialized third argument lpnumberofbytestransferred, going contain junk).

//note: `file` argument should opened in non-blocking mode long readdata(handle file, char* buf, long szbuf, int mstimeout){     overlapped readstate = {0};     readstate.hevent = createevent(0, true, false, "☠");     if (!readstate.hevent){         printlasterr();         return -1;     }     unsigned long bytesread = 0; //number of bytes read     if (!readfile(file, buf, szbuf, &bytesread, &readstate)){         //this creates reading event. below waiting complete, , cancel in         //case of timeout.         if (getlasterror() != error_io_pending){             printlasterr();             return -1;         }         //no, can't use here waitforsingleobject(), exiting disregard fact         //is reading still performing, or no more data remains(in case of serial port).         while(1){             std::this_thread::sleep_for(std::chrono::milliseconds( mstimeout ));             unsigned long ret;             puts("result getting");             if (!getoverlappedresult(file, &readstate, &ret, false)                 && getlasterror() != error_io_incomplete){ //error                 printlasterr();                 return -1;             }             printf("result %lu\n",ret);             if(ret == bytesread){//no more bytes read                 return bytesread;             }             bytesread = ret;         }     } else { //completed         printf("bytes read %i\n");         assert(bytesread <= long_max);//we return signed, error         return (long)bytesread;     } } 

call setcommtimeouts after open com port. sets readfile return after interval if no data received. call readfile. no overlap or event or getoverlappedresult needed.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -