C++ - ensuring full serial response -
i trying read serial response hardware device. string read long , need portion of it. portion of string want use std::string.substr(x,y);
. problem run exception error because buffer reading doesn't have y characters. here code use read values:
while(1) { char szbuff[50+1] = {0}; char wzbuff[14] = {"at+csq\r"}; dword dzbytesread = 0; dword dwbytesread = 0; if(!writefile(hserial, wzbuff, 7, &dzbytesread, null)) std::cout << "write error"; if(!readfile(hserial, szbuff, 50, &dwbytesread, null)) std::cout << "read error"; std:: cout << szbuff; std::string test = std::string(szbuff).substr(8,10); std::cout << test; sleep(500);
i issuing command "at+csq". returns:
n, n
ok
it returns 2 integer values seperated comma followed new line, followed "ok".
my question is, how can make sure read values serial port before grabbing substring? understand, last character received should new line.
the interface of readfile
function seems provide number of bytes read. if know length expected, should loop trying reading file (probably port descriptor) until expected number of bytes read.
if length of response not known, might have read , check in read buffer whether separator token has been read or not (in case protocol seems indicate new-line can used determine eom --end of message)
if can use other libraries, consider using boost::asio
, read_until
functionality (or equivalent in whatever libraries using). while code manage not rocket science, in cases there no point in reinventing wheel.
Comments
Post a Comment