win32: serial socket timeouts. bugzid: 654
[deb_libcec.git] / src / lib / platform / windows / serialport.cpp
index fe917255d5ad2e921b4ce628077ea42d57027c49..96e743f80e0759fba864a6fa9ad171128a0bd850 100644 (file)
@@ -48,32 +48,38 @@ void FormatWindowsError(int iErrorCode, CStdString &strMessage)
   }
 }
 
-bool CSerialSocket::SetTimeouts(serial_socket_t socket, int* iError, DWORD iTimeout)
+bool CSerialSocket::SetTimeouts(serial_socket_t socket, int* iError, DWORD iTimeoutMs)
 {
   if (socket == INVALID_HANDLE_VALUE)
          return false;
 
-  if (iTimeout == m_iCurrentTimeout)
+  if (iTimeoutMs == m_iCurrentReadTimeout)
     return true;
 
   COMMTIMEOUTS cto;
-  if (!GetCommTimeouts(socket, &cto))
+  if (iTimeoutMs == 0)
   {
-    *iError = GetLastError();
-    return false;
+    cto.ReadIntervalTimeout         = MAXDWORD;
+    cto.ReadTotalTimeoutConstant    = 0;
+    cto.ReadTotalTimeoutMultiplier  = 0;
+  }
+  else
+  {
+    cto.ReadIntervalTimeout         = 0;
+    cto.ReadTotalTimeoutConstant    = iTimeoutMs;
+    cto.ReadTotalTimeoutMultiplier  = 0;
   }
-
-  cto.ReadIntervalTimeout         = 0;
-  cto.ReadTotalTimeoutConstant    = iTimeout;
-  cto.ReadTotalTimeoutMultiplier  = 0;
 
   if (!SetCommTimeouts(socket, &cto))
   {
     *iError = GetLastError();
     return false;
   }
+  else
+  {
+    m_iCurrentReadTimeout = iTimeoutMs;
+  }
 
-  m_iCurrentTimeout = iTimeout;
   return true;
 }
 
@@ -98,20 +104,13 @@ ssize_t CSerialSocket::Write(void* data, size_t len)
 
 ssize_t CSerialSocket::Read(void* data, size_t len, uint64_t iTimeoutMs /* = 0 */)
 {
-  if (IsOpen())
-  {
-    DWORD iTimeout((DWORD)iTimeoutMs);
-    if (iTimeout != iTimeoutMs)
-      return -1;
-
-    int iError(0);
-    if (!SetTimeouts(m_socket, &iError, iTimeout))
-      return -1;
-
-    return SerialSocketRead(m_socket, &m_iError, data, len, iTimeoutMs);
-  }
+  DWORD dwTimeoutMs((DWORD)iTimeoutMs);
+  if (iTimeoutMs != (uint64_t)iTimeoutMs)
+    dwTimeoutMs = MAXDWORD;
 
-  return -1;
+  return IsOpen() && SetTimeouts(m_socket, &m_iError, dwTimeoutMs) ?
+    SerialSocketRead(m_socket, &m_iError, data, len, iTimeoutMs) :
+    -1;
 }
 
 bool CSerialSocket::Open(uint64_t iTimeoutMs /* = 0 */)
@@ -161,7 +160,7 @@ bool CSerialSocket::Open(uint64_t iTimeoutMs /* = 0 */)
     return false;
   }
 
-  if (!SetTimeouts(m_socket, &m_iError, MAXDWORD))
+  if (!SetTimeouts(m_socket, &m_iError, 0))
   {
     m_strError = "unable to set timeouts";
     FormatWindowsError(GetLastError(), m_strError);