serial.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "stdafx.h"
  2. #include "serial.h"
  3. Serial::Serial(const wchar_t* portName, DWORD baudRate /*= 115200*/)
  4. : _hSerial(INVALID_HANDLE_VALUE)
  5. {
  6. //Try to connect to the given port throuh CreateFile
  7. _hSerial = ::CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  8. //Check if the connection was successfull
  9. if(_hSerial == INVALID_HANDLE_VALUE) {
  10. throw std::exception("Serial connection failed to create");
  11. }
  12. //If connected we try to set the comm parameters
  13. DCB dcbSerialParams = {0};
  14. //Try to get the current
  15. if(!::GetCommState(_hSerial, &dcbSerialParams)) {
  16. throw std::exception("failed to get serial parameters");
  17. }
  18. //Define serial connection parameters for the arduino board
  19. dcbSerialParams.BaudRate = baudRate;
  20. dcbSerialParams.fBinary = TRUE;
  21. dcbSerialParams.Parity = NOPARITY;
  22. dcbSerialParams.ByteSize = 8;
  23. dcbSerialParams.StopBits = ONESTOPBIT;
  24. dcbSerialParams.fNull = FALSE;
  25. //Set the parameters and check for their proper application
  26. if(!::SetCommState(_hSerial, &dcbSerialParams)) {
  27. throw std::exception("Could not set Serial Port parameters");
  28. }
  29. //We wait 2s as the arduino board will be reseting
  30. ::Sleep(ARDUINO_WAIT_TIME);
  31. }
  32. Serial::~Serial(void)
  33. {
  34. if(_hSerial != INVALID_HANDLE_VALUE) {
  35. ::CloseHandle(_hSerial);
  36. _hSerial = INVALID_HANDLE_VALUE;
  37. }
  38. }
  39. size_t Serial::available()
  40. {
  41. ::ClearCommError(_hSerial, &_errors, &_status);
  42. return _status.cbInQue;
  43. }
  44. size_t Serial::readBytes(byte* data, size_t size)
  45. {
  46. auto len = std::min(size, available());
  47. DWORD bytesRead;
  48. ::ReadFile(_hSerial, data, len, &bytesRead, NULL);
  49. return bytesRead;
  50. }