----------------------------------------------------------------------------- Read data from the serial port -----------------------------------------------------------------------------
| 258 | // Read data from the serial port |
| 259 | //----------------------------------------------------------------------------- |
| 260 | void SerialControllerImpl::Read |
| 261 | ( |
| 262 | ) |
| 263 | { |
| 264 | uint8 buffer[256]; |
| 265 | |
| 266 | OVERLAPPED overlapped; |
| 267 | memset( &overlapped, 0, sizeof(overlapped) ); |
| 268 | overlapped.hEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); |
| 269 | |
| 270 | while( true ) |
| 271 | { |
| 272 | // Try to read all available data from the serial port |
| 273 | DWORD bytesRead = 0; |
| 274 | do |
| 275 | { |
| 276 | if( ::ReadFile( m_hSerialController, buffer, 256, NULL, &overlapped ) ) |
| 277 | { |
| 278 | // Read completed |
| 279 | GetOverlappedResult( m_hSerialController, &overlapped, &bytesRead, TRUE ); |
| 280 | |
| 281 | // Copy to the stream buffer |
| 282 | if( bytesRead > 0 ) |
| 283 | m_owner->Put( buffer, bytesRead ); |
| 284 | } |
| 285 | else |
| 286 | { |
| 287 | //Wait for the read to complete |
| 288 | if( ERROR_IO_PENDING == GetLastError() ) |
| 289 | { |
| 290 | // Wait for the read to complete or the |
| 291 | // signal that this thread should exit. |
| 292 | HANDLE handles[2]; |
| 293 | handles[0] = overlapped.hEvent; |
| 294 | handles[1] = m_hExit; |
| 295 | DWORD res = WaitForMultipleObjects( 2, handles, FALSE, INFINITE ); |
| 296 | |
| 297 | if( (WAIT_OBJECT_0+1) == res ) |
| 298 | { |
| 299 | // Exit signalled. Cancel the read. |
| 300 | goto exitRead; |
| 301 | } |
| 302 | |
| 303 | if( WAIT_TIMEOUT == res ) |
| 304 | { |
| 305 | // Timed out - should never happen |
| 306 | goto exitRead; |
| 307 | } |
| 308 | |
| 309 | // Read completed |
| 310 | GetOverlappedResult( m_hSerialController, &overlapped, &bytesRead, TRUE ); |
| 311 | |
| 312 | // Copy to the stream buffer |
| 313 | if( bytesRead > 0 ) |
| 314 | m_owner->Put( buffer, bytesRead ); |
| 315 | } |
| 316 | else |
| 317 | { |