Attempts to read some data from the port. Returns how much it actually read. Returns how much it actually read
| 891 | // Attempts to read some data from the port. Returns how much it actually read. |
| 892 | // Returns how much it actually read |
| 893 | unsigned int SerialIO::read(void* data, unsigned int dataLength) { |
| 894 | if ((data == nullptr) || (dataLength == 0)) return 0; |
| 895 | if (!isPortOpen()) return 0; |
| 896 | |
| 897 | #ifdef FTDI_D2XX_AVAILABLE |
| 898 | if (m_ftdi.isOpen()) { |
| 899 | m_ftdi.FT_SetTimeouts(m_readTimeout + (m_readTimeoutMultiplier * dataLength), m_writeTimeout + (m_writeTimeoutMultiplier * dataLength)); |
| 900 | |
| 901 | DWORD dataRead = 0; |
| 902 | if (m_ftdi.FT_Read((LPVOID)data, dataLength, &dataRead) != FTDI::FT_STATUS::FT_OK) dataRead = 0; |
| 903 | return dataRead; |
| 904 | } |
| 905 | #endif |
| 906 | |
| 907 | #ifdef _WIN32 |
| 908 | DWORD read = 0; |
| 909 | if (!ReadFile(m_portHandle, data, dataLength, &read, NULL)) read = 0; |
| 910 | return read; |
| 911 | #else |
| 912 | unsigned int totalTime = m_readTimeout + (m_readTimeoutMultiplier * dataLength); |
| 913 | |
| 914 | struct timeval timeout; |
| 915 | timeout.tv_sec = totalTime / 1000; |
| 916 | timeout.tv_usec = (totalTime - (timeout.tv_sec * 1000)) * 1000; |
| 917 | |
| 918 | size_t read = 0; |
| 919 | unsigned char* buffer = (unsigned char*)data; |
| 920 | |
| 921 | fd_set fds; |
| 922 | FD_ZERO(&fds); |
| 923 | FD_SET(m_portHandle, &fds); |
| 924 | |
| 925 | while (read < dataLength) { |
| 926 | if ((timeout.tv_sec < 1) && (timeout.tv_usec < 1)) { |
| 927 | break; |
| 928 | } |
| 929 | |
| 930 | int result = select(m_portHandle + 1, &fds, NULL, NULL, &timeout); |
| 931 | |
| 932 | if (result < 0) { |
| 933 | if (errno == EINTR || errno == EAGAIN) continue; else return 0; |
| 934 | } |
| 935 | else if (result == 0) break; |
| 936 | result = ::read(m_portHandle, buffer, dataLength - read); |
| 937 | |
| 938 | if (result < 0) { |
| 939 | if (errno == EINTR || errno == EAGAIN) continue; else return 0; |
| 940 | } |
| 941 | read += result; |
| 942 | buffer += result; |
| 943 | } |
| 944 | |
| 945 | return read; |
| 946 | |
| 947 | |
| 948 | #endif |
| 949 | |
| 950 | return 0; |
no test coverage detected