Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2021
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.85 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <iostream>
  4. #include <windows.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <chrono>
  8. #include <vector>
  9.  
  10. #include <clocale>
  11. #include <locale>
  12. #include <string>
  13. #include <vector>
  14.  
  15. #define CONNECTION_WAIT_TIME 2000
  16.  
  17.  
  18. typedef std::chrono::high_resolution_clock Clock;
  19.  
  20. typedef unsigned char byte;
  21.  
  22. class SerialReceiver {
  23.  
  24. public:
  25.  
  26.     SerialReceiver() :
  27.         hSerial(NULL),
  28.         connected(false)
  29.     {
  30.  
  31.  
  32.     }
  33.  
  34.     ~SerialReceiver() {
  35.  
  36.     }
  37. public:
  38.  
  39.     std::string w2s(const std::wstring &var)
  40.     {
  41.         static std::locale loc("");
  42.         auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
  43.         return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var);
  44.     }
  45.  
  46.     std::wstring s2w(const std::string &var)
  47.     {
  48.         static std::locale loc("");
  49.         auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc);
  50.         return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var);
  51.     }
  52.  
  53.     //bool openSerialConnection(LPCWSTR port)
  54.     bool openSerialConnection(std::string port)
  55.     {
  56.         connected = false;
  57.  
  58.         portName = s2w(port);
  59.  
  60.         //Try to connect to the given port throuh CreateFile
  61.         hSerial = CreateFile(portName.c_str(),
  62.             GENERIC_READ | GENERIC_WRITE,
  63.             0,
  64.             NULL,
  65.             OPEN_EXISTING,
  66.             FILE_ATTRIBUTE_NORMAL,
  67.             NULL);
  68.  
  69.         //Check if the connection was successfull
  70.         if (hSerial == INVALID_HANDLE_VALUE)
  71.         {
  72.  
  73.             closeSerialConnection();
  74.  
  75.             //If not success full display an Error
  76.             if (GetLastError() == ERROR_FILE_NOT_FOUND) {
  77.  
  78.                 //Print Error if neccessary
  79.                 printf("ERROR: Handle was not attached. Reason: %ls not available.\n", portName.c_str());
  80.  
  81.             }
  82.             else
  83.             {
  84.                 printf("ERROR!!!");
  85.             }
  86.         }
  87.         else
  88.         {
  89.  
  90.             //If connected we try to set the comm parameters
  91.             DCB dcbSerialParams = { 0 };
  92.  
  93.             //Try to get the current
  94.             if (!GetCommState(hSerial, &dcbSerialParams))
  95.             {
  96.                 //If impossible, show an error
  97.                 printf("failed to get current serial parameters!");
  98.             }
  99.             else
  100.             {
  101.                 //Define serial connection parameters for the arduino board
  102.                 //dcbSerialParams.BaudRate = CBR_115200;
  103.                 dcbSerialParams.BaudRate = CBR_115200;
  104.                 dcbSerialParams.ByteSize = 8;
  105.                 dcbSerialParams.StopBits = ONESTOPBIT;
  106.                 dcbSerialParams.Parity = NOPARITY;
  107.                 //Setting the DTR to Control_Enable ensures that the Arduino is properly
  108.                 //reset upon establishing a connection
  109.                 dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;
  110.  
  111.                 //Set the parameters and check for their proper application
  112.                 if (!SetCommState(hSerial, &dcbSerialParams))
  113.                 {
  114.                     printf("ALERT: Could not set Serial Port parameters");
  115.                     connected = false;
  116.                 }
  117.                 else
  118.                 {
  119.                     //If everything went fine we're connected
  120.                     connected = true;
  121.                     //Flush any remaining characters in the buffers
  122.                     PurgeComm(hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
  123.                     //We wait 2s as the arduino board will be reseting
  124.                     Sleep(CONNECTION_WAIT_TIME);
  125.  
  126.                     printf("Serial connection on port %ls established\n", portName.c_str());
  127.  
  128.                     // flush serial pipeline
  129.                     ClearCommError(hSerial, &errors, &status);
  130.                     if (status.cbInQue > 0)
  131.                     {
  132.                         int byteAvailable = status.cbInQue;
  133.                         DWORD byteflushed = status.cbInQue;
  134.                         char *temp = new char[byteAvailable];
  135.                         ReadFile(hSerial, temp, byteAvailable, &byteflushed, NULL);
  136.                         delete temp;
  137.                     }
  138.                     return true;
  139.  
  140.                 }
  141.             }
  142.  
  143.  
  144.         }
  145.  
  146.         return false;
  147.  
  148.     }
  149.  
  150.     inline u_short ByteSwap(u_short in)
  151.     {
  152.         u_short out;
  153.         char *indata = (char *)&in;
  154.         char *outdata = (char *)&out;
  155.         outdata[0] = indata[1];
  156.         outdata[1] = indata[0];
  157.         return out;
  158.     }
  159.     bool closeSerialConnection() {
  160.  
  161.         Sleep(100);
  162.  
  163.         connected = false;
  164.         std::cout << "Closing connection..." << std::endl;
  165.         int success = (int)CloseHandle(hSerial);
  166.         if (success == 0)
  167.             return false;
  168.         return true;    // close serial connection
  169.     }
  170.  
  171.     int ReadData(char *buffer, const unsigned int nbChar)
  172.     {
  173.         DWORD bytesRead;
  174.         unsigned int toRead;
  175.  
  176.         ClearCommError(hSerial, &errors, &status);
  177.  
  178.         if (status.cbInQue>0)
  179.         {
  180.  
  181.             if (status.cbInQue >= nbChar)
  182.             {
  183.                 toRead = nbChar;
  184.             }
  185.             else // not enough for one package, return
  186.                 return 0;
  187.  
  188.             if (ReadFile(hSerial, buffer, toRead, &bytesRead, NULL))
  189.             {
  190.                 return bytesRead;
  191.             }
  192.  
  193.         }
  194.         return 0;
  195.  
  196.     }
  197.  
  198.     void UpdateData(){
  199.         readResult = ReadData(incomingData, dataLength);
  200.  
  201.     }
  202.     bool isConnected() { return connected; }
  203.     private:
  204.  
  205.     std::wstring portName;
  206.     HANDLE hSerial = NULL;
  207.     COMSTAT status; //Get various information about the connection
  208.     DWORD errors;   //Keep track of last error
  209.     bool connected = false;
  210.  
  211.     std::vector<char> incomingDataCollection;
  212.  
  213.     char incomingData[16] = ""; // don't forget to pre-allocate memory
  214.     int dataLength = 16;
  215.     int readResult = 0;
  216.  
  217. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement