Steefmaester

serialib

Sep 8th, 2016
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 29.74 KB | None | 0 0
  1. //serialib.h
  2. /*!
  3. \file    serialib.h
  4. \brief   Serial library to communicate throught serial port, or any device emulating a serial port.
  5. \author  Philippe Lucidarme (University of Angers) <[email protected]>
  6. \version 1.2
  7. \date    28 avril 2011
  8. This Serial library is used to communicate through serial port.
  9.  
  10. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  11. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  12. PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM,
  13. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  14. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  15.  
  16. This is a licence-free software, it can be used by anyone who try to build a better world.
  17. */
  18.  
  19.  
  20. #ifndef SERIALIB_H
  21. #define SERIALIB_H
  22.  
  23.  
  24. // Used for TimeOut operations
  25.  
  26. // Include for windows
  27. #if defined (_WIN32) || defined( _WIN64)
  28.     // Accessing to the serial port under Windows
  29.     #include <windows.h>
  30.     #include <time.h>
  31. #endif
  32.  
  33. // Include for Linux
  34. #ifdef __linux__
  35.     #include <stdlib.h>
  36.     #include <sys/types.h>
  37.     #include <sys/shm.h>
  38.     #include <sys/time.h>
  39.     #include <termios.h>
  40.     #include <string.h>
  41.     #include <iostream>
  42.     // File control definitions
  43.     #include <fcntl.h>
  44.     #include <unistd.h>
  45.     #include <sys/ioctl.h>
  46. #endif
  47.  
  48.  
  49.  
  50. /*!  \class serialib
  51.      \brief     This class can manage a serial port. The class allows basic operations (opening the connection, reading, writing data and closing the connection).
  52.      \example   Example1.cpp
  53.    */
  54.  
  55.  
  56. class serialib
  57. {
  58. public:
  59.     // Constructor of the class
  60.     serialib    ();
  61.  
  62.     // Destructor
  63.     ~serialib   ();
  64.  
  65.  
  66.  
  67.     //_________________________________________
  68.     // ::: Configuration and initialization :::
  69.  
  70.  
  71.     // Open a device
  72.     char    Open        (const char *Device,const unsigned int Bauds);
  73.  
  74.     // Close the current device
  75.     void    Close();
  76.  
  77.  
  78.  
  79.     //___________________________________________
  80.     // ::: Read/Write operation on characters :::
  81.  
  82.  
  83.     // Write a char
  84.     char    WriteChar   (char);
  85.  
  86.     // Read a char (with timeout)
  87.     char    ReadChar    (char *pByte,const unsigned int TimeOut_ms=NULL);
  88.  
  89.  
  90.  
  91.     //________________________________________
  92.     // ::: Read/Write operation on strings :::
  93.  
  94.  
  95.     // Write a string
  96.     char    WriteString (const char *String);
  97.     // Read a string (with timeout)
  98.     int     ReadString  (   char *String,
  99.                             char FinalChar,
  100.                             unsigned int MaxNbBytes,
  101.                             const unsigned int TimeOut_ms=NULL);
  102.  
  103.  
  104.  
  105.     // _____________________________________
  106.     // ::: Read/Write operation on bytes :::
  107.  
  108.  
  109.     // Write an array of bytes
  110.     char    Write       (const void *Buffer, const unsigned int NbBytes);
  111.  
  112.     // Read an array of byte (with timeout)
  113.     int     Read        (void *Buffer,unsigned int MaxNbBytes,const unsigned int TimeOut_ms=NULL);
  114.  
  115.  
  116.     // _________________________
  117.     // ::: Special operation :::
  118.  
  119.  
  120.     // Empty the received buffer
  121.     void    FlushReceiver();
  122.  
  123.     // Return the number of bytes in the received buffer
  124.     int     Peek();
  125.  
  126. private:
  127.     // Read a string (no timeout)
  128.     int     ReadStringNoTimeOut  (char *String,char FinalChar,unsigned int MaxNbBytes);
  129.  
  130.  
  131. #if defined (_WIN32) || defined( _WIN64)
  132.     HANDLE          hSerial;
  133.     COMMTIMEOUTS    timeouts;
  134. #endif
  135. #ifdef __linux__
  136.     int             fd;
  137. #endif
  138.  
  139. };
  140.  
  141.  
  142.  
  143. /*!  \class     TimeOut
  144.      \brief     This class can manage a timer which is used as a timeout.
  145.    */
  146. // Class TimeOut
  147. class TimeOut
  148. {
  149. public:
  150.  
  151.     // Constructor
  152.     TimeOut();
  153.  
  154.     // Init the timer
  155.     void                InitTimer();
  156.     #if defined (_WIN32) || defined( _WIN64)
  157.     int _gettimeofday(struct timeval* p, void* tz);
  158.     #endif
  159.     // Return the elapsed time since initialization
  160.     unsigned long int   ElapsedTime_ms();
  161.  
  162. private:    
  163.     struct timeval      PreviousTime;
  164. };
  165.  
  166.  
  167.  
  168. /*!
  169.   \mainpage serialib class
  170.  
  171.   \brief
  172.        \htmlonly
  173.        <TABLE>
  174.        <TR><TD>
  175.             <a href="../serialibv1.2.zip" title="Download the serialib class">
  176.                 <TABLE>
  177.                 <TR><TD><IMG SRC="download.png" BORDER=0 WIDTH=100> </TD></TR>
  178.                 <TR><TD><P ALIGN="center">[Download]</P> </TD></TR>
  179.                 </TABLE>
  180.             </A>
  181.             </TD>
  182.             <TD>
  183.                 <script type="text/javascript"><!--google_ad_client = "ca-pub-0665655683291467";
  184.                 google_ad_slot = "0230365165";
  185.                 google_ad_width = 728;
  186.                 google_ad_height = 90;
  187.                 //-->
  188.                 </script>
  189.                 <script type="text/javascript"
  190.                 src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
  191.                 </script>
  192.             </TD>
  193.         </TR>
  194.         </TABLE>
  195.  
  196.         \endhtmlonly
  197.  
  198.     The class serialib offers simple access to the serial port devices for windows and linux. It can be used for any serial device (Built-in serial port, USB to RS232 converter, arduino board or any hardware using or emulating a serial port)
  199.     \image html serialib.png
  200.     The class can be used under Windows and Linux.
  201.     The class allows basic operations like :
  202.     - opening and closing connection
  203.     - reading data (characters, array of bytes or strings)
  204.     - writing data (characters, array of bytes or strings)
  205.     - non-blocking functions (based on timeout).
  206.  
  207.  
  208.   \author   Philippe Lucidarme (University of Angers) <[email protected]>
  209.   \date     1th may 2011 (Last update: 25th september 2012)
  210.   \version  1.2
  211.  
  212. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  213. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  214. PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM,
  215. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  216. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  217.  
  218. This is a licence-free software, it can be used by anyone who try to build a better world.
  219. */
  220.  
  221.  
  222.  
  223.  
  224. #endif // SERIALIB_H
  225.  
  226.  
  227.  
  228.  
  229. //serialib.cpp
  230. /*!
  231.  \file    serialib.cpp
  232.  \brief   Class to manage the serial port
  233.  \author  Philippe Lucidarme (University of Angers) <[email protected]>
  234.  \version 1.2
  235.  \date    28 avril 2011
  236.  
  237. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  238. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  239. PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM,
  240. DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  241. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  242.  
  243.  
  244. This is a licence-free software, it can be used by anyone who try to build a better world.
  245.  */
  246.  
  247. #include "serialib.h"
  248.  
  249.  
  250.  
  251.  
  252. /*!
  253.     \brief      Constructor of the class serialib.
  254. */
  255. // Class constructor
  256. serialib::serialib()
  257. {}
  258.  
  259.  
  260. /*!
  261.     \brief      Destructor of the class serialib. It close the connection
  262. */
  263. // Class desctructor
  264. serialib::~serialib()
  265. {
  266.     Close();
  267. }
  268.  
  269.  
  270.  
  271. //_________________________________________
  272. // ::: Configuration and initialization :::
  273.  
  274.  
  275.  
  276. /*!
  277.      \brief Open the serial port
  278.      \param Device : Port name (COM1, COM2, ... for Windows ) or (/dev/ttyS0, /dev/ttyACM0, /dev/ttyUSB0 ... for linux)
  279.      \param Bauds : Baud rate of the serial port.
  280.  
  281.                 \n Supported baud rate for Windows :
  282.                         - 110
  283.                         - 300
  284.                         - 600
  285.                         - 1200
  286.                         - 2400
  287.                         - 4800
  288.                         - 9600
  289.                         - 14400
  290.                         - 19200
  291.                         - 38400
  292.                         - 56000
  293.                         - 57600
  294.                         - 115200
  295.                         - 128000
  296.                         - 256000
  297.  
  298.                \n Supported baud rate for Linux :\n
  299.                         - 110
  300.                         - 300
  301.                         - 600
  302.                         - 1200
  303.                         - 2400
  304.                         - 4800
  305.                         - 9600
  306.                         - 19200
  307.                         - 38400
  308.                         - 57600
  309.                         - 115200
  310.  
  311.      \return 1 success
  312.      \return -1 device not found
  313.      \return -2 error while opening the device
  314.      \return -3 error while getting port parameters
  315.      \return -4 Speed (Bauds) not recognized
  316.      \return -5 error while writing port parameters
  317.      \return -6 error while writing timeout parameters
  318.   */
  319. char serialib::Open(const char *Device,const unsigned int Bauds)
  320. {
  321. #if defined (_WIN32) || defined( _WIN64)
  322.  
  323.     // Open serial port
  324.     hSerial = CreateFileA(  Device,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  325.     if(hSerial==INVALID_HANDLE_VALUE) {
  326.         if(GetLastError()==ERROR_FILE_NOT_FOUND)
  327.             return -1;                                                  // Device not found
  328.         return -2;                                                      // Error while opening the device
  329.     }
  330.  
  331.     // Set parameters
  332.     DCB dcbSerialParams = {0};                                          // Structure for the port parameters
  333.     dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
  334.     if (!GetCommState(hSerial, &dcbSerialParams))                       // Get the port parameters
  335.         return -3;                                                      // Error while getting port parameters
  336.     switch (Bauds)                                                      // Set the speed (Bauds)
  337.     {
  338.     case 110  :     dcbSerialParams.BaudRate=CBR_110; break;
  339.     case 300  :     dcbSerialParams.BaudRate=CBR_300; break;
  340.     case 600  :     dcbSerialParams.BaudRate=CBR_600; break;
  341.     case 1200 :     dcbSerialParams.BaudRate=CBR_1200; break;
  342.     case 2400 :     dcbSerialParams.BaudRate=CBR_2400; break;
  343.     case 4800 :     dcbSerialParams.BaudRate=CBR_4800; break;
  344.     case 9600 :     dcbSerialParams.BaudRate=CBR_9600; break;
  345.     case 14400 :    dcbSerialParams.BaudRate=CBR_14400; break;
  346.     case 19200 :    dcbSerialParams.BaudRate=CBR_19200; break;
  347.     case 38400 :    dcbSerialParams.BaudRate=CBR_38400; break;
  348.     case 56000 :    dcbSerialParams.BaudRate=CBR_56000; break;
  349.     case 57600 :    dcbSerialParams.BaudRate=CBR_57600; break;
  350.     case 115200 :   dcbSerialParams.BaudRate=CBR_115200; break;
  351.     case 128000 :   dcbSerialParams.BaudRate=CBR_128000; break;
  352.     case 256000 :   dcbSerialParams.BaudRate=CBR_256000; break;
  353.     default : return -4;
  354. }    
  355.     dcbSerialParams.ByteSize=8;                                         // 8 bit data
  356.     dcbSerialParams.StopBits=ONESTOPBIT;                                // One stop bit
  357.     dcbSerialParams.Parity=NOPARITY;                                    // No parity
  358.     if(!SetCommState(hSerial, &dcbSerialParams))                        // Write the parameters
  359.         return -5;                                                      // Error while writing
  360.  
  361.     // Set TimeOut
  362.     timeouts.ReadIntervalTimeout=0;                                     // Set the Timeout parameters
  363.     timeouts.ReadTotalTimeoutConstant=MAXDWORD;                         // No TimeOut
  364.     timeouts.ReadTotalTimeoutMultiplier=0;
  365.     timeouts.WriteTotalTimeoutConstant=MAXDWORD;
  366.     timeouts.WriteTotalTimeoutMultiplier=0;
  367.     if(!SetCommTimeouts(hSerial, &timeouts))                            // Write the parameters
  368.         return -6;                                                      // Error while writting the parameters
  369.     return 1;                                                           // Opening successfull
  370.  
  371. #endif
  372. #ifdef __linux__    
  373.     struct termios options;                                             // Structure with the device's options
  374.  
  375.  
  376.     // Open device
  377.     fd = open(Device, O_RDWR | O_NOCTTY | O_NDELAY);                    // Open port
  378.     if (fd == -1) return -2;                                            // If the device is not open, return -1
  379.     fcntl(fd, F_SETFL, FNDELAY);                                        // Open the device in nonblocking mode
  380.  
  381.     // Set parameters
  382.     tcgetattr(fd, &options);                                            // Get the current options of the port
  383.     bzero(&options, sizeof(options));                                   // Clear all the options
  384.     speed_t         Speed;
  385.     switch (Bauds)                                                      // Set the speed (Bauds)
  386.     {
  387.     case 110  :     Speed=B110; break;
  388.     case 300  :     Speed=B300; break;
  389.     case 600  :     Speed=B600; break;
  390.     case 1200 :     Speed=B1200; break;
  391.     case 2400 :     Speed=B2400; break;
  392.     case 4800 :     Speed=B4800; break;
  393.     case 9600 :     Speed=B9600; break;
  394.     case 19200 :    Speed=B19200; break;
  395.     case 38400 :    Speed=B38400; break;
  396.     case 57600 :    Speed=B57600; break;
  397.     case 115200 :   Speed=B115200; break;
  398.     case 500000 :   Speed=B500000; break;
  399.     default : return -4;
  400. }
  401.     cfsetispeed(&options, Speed);                                       // Set the baud rate at 115200 bauds
  402.     cfsetospeed(&options, Speed);
  403.     options.c_cflag |= ( CLOCAL | CREAD |  CS8);                        // Configure the device : 8 bits, no parity, no control
  404.     options.c_iflag |= ( IGNPAR | IGNBRK );
  405.     options.c_cc[VTIME]=0;                                              // Timer unused
  406.     options.c_cc[VMIN]=0;                                               // At least on character before satisfy reading
  407.     tcsetattr(fd, TCSANOW, &options);                                   // Activate the settings
  408.     return (1);                                                         // Success
  409. #endif
  410. }
  411.  
  412.  
  413. /*!
  414.      \brief Close the connection with the current device
  415. */
  416. void serialib::Close()
  417. {
  418. #if defined (_WIN32) || defined( _WIN64)
  419.     CloseHandle(hSerial);
  420. #endif
  421. #ifdef __linux__
  422.     close (fd);
  423. #endif
  424. }
  425.  
  426.  
  427.  
  428.  
  429. //___________________________________________
  430. // ::: Read/Write operation on characters :::
  431.  
  432.  
  433.  
  434. /*!
  435.      \brief Write a char on the current serial port
  436.      \param Byte : char to send on the port (must be terminated by '\0')
  437.      \return 1 success
  438.      \return -1 error while writting data
  439.   */
  440. char serialib::WriteChar(const char Byte)
  441. {
  442. #if defined (_WIN32) || defined( _WIN64)
  443.     DWORD dwBytesWritten;                                               // Number of bytes written
  444.     if(!WriteFile(hSerial,&Byte,1,&dwBytesWritten,NULL))                // Write the char
  445.         return -1;                                                      // Error while writing
  446.     return 1;                                                           // Write operation successfull
  447. #endif
  448. #ifdef __linux__
  449.     if (write(fd,&Byte,1)!=1)                                           // Write the char
  450.         return -1;                                                      // Error while writting
  451.     return 1;                                                           // Write operation successfull
  452. #endif
  453. }
  454.  
  455.  
  456.  
  457. //________________________________________
  458. // ::: Read/Write operation on strings :::
  459.  
  460.  
  461. /*!
  462.      \brief Write a string on the current serial port
  463.      \param String : string to send on the port (must be terminated by '\0')
  464.      \return 1 success
  465.      \return -1 error while writting data
  466.   */
  467. char serialib::WriteString(const char *String)
  468. {
  469. #if defined (_WIN32) || defined( _WIN64)
  470.     DWORD dwBytesWritten;                                               // Number of bytes written
  471.     if(!WriteFile(hSerial,String,strlen(String),&dwBytesWritten,NULL))  // Write the string
  472.         return -1;                                                      // Error while writing
  473.     return 1;                                                           // Write operation successfull
  474. #endif
  475. #ifdef __linux__
  476.     int Lenght=strlen(String);                                          // Lenght of the string
  477.     if (write(fd,String,Lenght)!=Lenght)                                // Write the string
  478.         return -1;                                                      // error while writing
  479.     return 1;                                                           // Write operation successfull
  480. #endif
  481. }
  482.  
  483. // _____________________________________
  484. // ::: Read/Write operation on bytes :::
  485.  
  486.  
  487.  
  488. /*!
  489.      \brief Write an array of data on the current serial port
  490.      \param Buffer : array of bytes to send on the port
  491.      \param NbBytes : number of byte to send
  492.      \return 1 success
  493.      \return -1 error while writting data
  494.   */
  495. char serialib::Write(const void *Buffer, const unsigned int NbBytes)
  496. {
  497. #if defined (_WIN32) || defined( _WIN64)
  498.     DWORD dwBytesWritten;                                               // Number of byte written
  499.     if(!WriteFile(hSerial, Buffer, NbBytes, &dwBytesWritten, NULL))     // Write data
  500.         return -1;                                                      // Error while writing
  501.     return 1;                                                           // Write operation successfull
  502. #endif
  503. #ifdef __linux__
  504.     if (write (fd,Buffer,NbBytes)!=(ssize_t)NbBytes)                              // Write data
  505.         return -1;                                                      // Error while writing
  506.     return 1;                                                           // Write operation successfull
  507. #endif
  508. }
  509.  
  510.  
  511.  
  512. /*!
  513.      \brief Wait for a byte from the serial device and return the data read
  514.      \param pByte : data read on the serial device
  515.      \param TimeOut_ms : delay of timeout before giving up the reading
  516.             If set to zero, timeout is disable (Optional)
  517.      \return 1 success
  518.      \return 0 Timeout reached
  519.      \return -1 error while setting the Timeout
  520.      \return -2 error while reading the byte
  521.   */
  522. char serialib::ReadChar(char *pByte,unsigned int TimeOut_ms)
  523. {
  524. #if defined (_WIN32) || defined(_WIN64)
  525.  
  526.     DWORD dwBytesRead = 0;
  527.     timeouts.ReadTotalTimeoutConstant=TimeOut_ms;                       // Set the TimeOut
  528.     if(!SetCommTimeouts(hSerial, &timeouts))                            // Write the parameters
  529.         return -1;                                                      // Error while writting the parameters
  530.     if(!ReadFile(hSerial,pByte, 1, &dwBytesRead, NULL))                 // Read the byte
  531.         return -2;                                                      // Error while reading the byte
  532.     if (dwBytesRead==0) return 0;                                       // Return 1 if the timeout is reached
  533.     return 1;                                                           // Success
  534. #endif
  535. #ifdef __linux__
  536.     TimeOut         Timer;                                              // Timer used for timeout
  537.     Timer.InitTimer();                                                  // Initialise the timer
  538.     while (Timer.ElapsedTime_ms()<TimeOut_ms || TimeOut_ms==0)          // While Timeout is not reached
  539.     {
  540.         switch (read(fd,pByte,1)) {                                     // Try to read a byte on the device
  541.         case 1  : return 1;                                             // Read successfull
  542.         case -1 : return -2;                                            // Error while reading
  543.         }
  544.     }
  545.     return 0;
  546. #endif
  547. }
  548.  
  549.  
  550.  
  551. /*!
  552.      \brief Read a string from the serial device (without TimeOut)
  553.      \param String : string read on the serial device
  554.      \param FinalChar : final char of the string
  555.      \param MaxNbBytes : maximum allowed number of bytes read
  556.      \return >0 success, return the number of bytes read
  557.      \return -1 error while setting the Timeout
  558.      \return -2 error while reading the byte
  559.      \return -3 MaxNbBytes is reached
  560.   */
  561. int serialib::ReadStringNoTimeOut(char *String,char FinalChar,unsigned int MaxNbBytes)
  562. {
  563.     unsigned int    NbBytes=0;                                          // Number of bytes read
  564.     char            ret;                                                // Returned value from Read
  565.     while (NbBytes<MaxNbBytes)                                          // While the buffer is not full
  566.     {                                                                   // Read a byte with the restant time
  567.         ret=ReadChar(&String[NbBytes]);
  568.         if (ret==1)                                                     // If a byte has been read
  569.         {
  570.             if (String[NbBytes]==FinalChar)                             // Check if it is the final char
  571.             {
  572.                 String  [++NbBytes]=0;                                  // Yes : add the end character 0
  573.                 return NbBytes;                                         // Return the number of bytes read
  574.             }
  575.             NbBytes++;                                                  // If not, just increase the number of bytes read
  576.         }
  577.         if (ret<0) return ret;                                          // Error while reading : return the error number
  578.     }
  579.     return -3;                                                          // Buffer is full : return -3
  580. }
  581.  
  582. /*!
  583.      \brief Read a string from the serial device (with timeout)
  584.      \param String : string read on the serial device
  585.      \param FinalChar : final char of the string
  586.      \param MaxNbBytes : maximum allowed number of bytes read
  587.      \param TimeOut_ms : delay of timeout before giving up the reading (optional)
  588.      \return  >0 success, return the number of bytes read
  589.      \return  0 timeout is reached
  590.      \return -1 error while setting the Timeout
  591.      \return -2 error while reading the byte
  592.      \return -3 MaxNbBytes is reached
  593.   */
  594. int serialib::ReadString(char *String,char FinalChar,unsigned int MaxNbBytes,unsigned int TimeOut_ms)
  595. {
  596.     if (TimeOut_ms==0)
  597.         return ReadStringNoTimeOut(String,FinalChar,MaxNbBytes);
  598.  
  599.     unsigned int    NbBytes=0;                                          // Number of bytes read
  600.     char            ret;                                                // Returned value from Read
  601.     TimeOut         Timer;                                              // Timer used for timeout
  602.     long int        TimeOutParam;
  603.     Timer.InitTimer();                                                  // Initialize the timer
  604.  
  605.     while (NbBytes<MaxNbBytes)                                          // While the buffer is not full
  606.     {                                                                   // Read a byte with the restant time
  607.         TimeOutParam=TimeOut_ms-Timer.ElapsedTime_ms();                 // Compute the TimeOut for the call of ReadChar
  608.         if (TimeOutParam>0)                                             // If the parameter is higher than zero
  609.         {
  610.             ret=ReadChar(&String[NbBytes],TimeOutParam);                // Wait for a byte on the serial link            
  611.             if (ret==1)                                                 // If a byte has been read
  612.             {
  613.  
  614.                 if (String[NbBytes]==FinalChar)                         // Check if it is the final char
  615.                 {
  616.                     String  [++NbBytes]=0;                              // Yes : add the end character 0
  617.                     return NbBytes;                                     // Return the number of bytes read
  618.                 }
  619.                 NbBytes++;                                              // If not, just increase the number of bytes read
  620.             }
  621.             if (ret<0) return ret;                                      // Error while reading : return the error number
  622.         }
  623.         if (Timer.ElapsedTime_ms()>TimeOut_ms) {                        // Timeout is reached
  624.             String[NbBytes]=0;                                          // Add the end caracter
  625.             return 0;                                                   // Return 0
  626.         }
  627.     }
  628.     return -3;                                                          // Buffer is full : return -3
  629. }
  630.  
  631.  
  632. /*!
  633.      \brief Read an array of bytes from the serial device (with timeout)
  634.      \param Buffer : array of bytes read from the serial device
  635.      \param MaxNbBytes : maximum allowed number of bytes read
  636.      \param TimeOut_ms : delay of timeout before giving up the reading
  637.      \return 1 success, return the number of bytes read
  638.      \return 0 Timeout reached
  639.      \return -1 error while setting the Timeout
  640.      \return -2 error while reading the byte
  641.   */
  642. int serialib::Read (void *Buffer,unsigned int MaxNbBytes,unsigned int TimeOut_ms)
  643. {
  644. #if defined (_WIN32) || defined(_WIN64)
  645.     DWORD dwBytesRead = 0;
  646.     timeouts.ReadTotalTimeoutConstant=(DWORD)TimeOut_ms;                // Set the TimeOut
  647.     if(!SetCommTimeouts(hSerial, &timeouts))                            // Write the parameters
  648.         return -1;                                                      // Error while writting the parameters
  649.     if(!ReadFile(hSerial,Buffer,(DWORD)MaxNbBytes,&dwBytesRead, NULL))  // Read the bytes from the serial device
  650.         return -2;                                                      // Error while reading the byte
  651.     if (dwBytesRead!=(DWORD)MaxNbBytes) return 0;                       // Return 0 if the timeout is reached
  652.     return 1;                                                           // Success
  653. #endif
  654. #ifdef __linux__
  655.     TimeOut          Timer;                                             // Timer used for timeout
  656.     Timer.InitTimer();                                                  // Initialise the timer
  657.     unsigned int     NbByteRead=0;
  658.     while (Timer.ElapsedTime_ms()<TimeOut_ms || TimeOut_ms==0)          // While Timeout is not reached
  659.     {
  660.         unsigned char* Ptr=(unsigned char*)Buffer+NbByteRead;           // Compute the position of the current byte
  661.         int Ret=read(fd,(void*)Ptr,MaxNbBytes-NbByteRead);              // Try to read a byte on the device
  662.         if (Ret==-1) return -2;                                         // Error while reading
  663.         if (Ret>0) {                                                    // One or several byte(s) has been read on the device
  664.             NbByteRead+=Ret;                                            // Increase the number of read bytes
  665.             if (NbByteRead>=MaxNbBytes)                                 // Success : bytes has been read
  666.                 return 1;
  667.         }
  668.     }
  669.     return 0;                                                           // Timeout reached, return 0
  670. #endif
  671. }
  672.  
  673.  
  674.  
  675.  
  676. // _________________________
  677. // ::: Special operation :::
  678.  
  679.  
  680.  
  681. /*!
  682.     \brief Empty receiver buffer (UNIX only)
  683. */
  684.  
  685. void serialib::FlushReceiver()
  686. {
  687. #ifdef __linux__
  688.     tcflush(fd,TCIFLUSH);
  689. #endif
  690. }
  691.  
  692.  
  693.  
  694. /*!
  695.     \brief  Return the number of bytes in the received buffer (UNIX only)
  696.     \return The number of bytes in the received buffer
  697. */
  698. int serialib::Peek()
  699. {
  700.     int Nbytes=0;
  701. #ifdef __linux__
  702.     ioctl(fd, FIONREAD, &Nbytes);
  703. #endif
  704.     return Nbytes;
  705. }
  706.  
  707. // ******************************************
  708. //  Class TimeOut
  709. // ******************************************
  710.  
  711.  
  712. /*!
  713.     \brief      Constructor of the class TimeOut.
  714. */
  715. // Constructor
  716. TimeOut::TimeOut()
  717. {}
  718.  
  719. // Implementation de gettimeofday pour Microsoft Windows
  720. // http://mathieuturcotte.ca/textes/windows-gettimeofday/
  721. #if defined (_WIN32) || defined(_WIN64)
  722. int TimeOut::_gettimeofday(struct timeval* p, void* tz) {
  723.     ULARGE_INTEGER ul; // As specified on MSDN.
  724.     FILETIME ft;
  725.  
  726.     // Returns a 64-bit value representing the number of
  727.     // 100-nanosecond intervals since January 1, 1601 (UTC).
  728.     GetSystemTimeAsFileTime(&ft);
  729.  
  730.     // Fill ULARGE_INTEGER low and high parts.
  731.     ul.LowPart = ft.dwLowDateTime;
  732.     ul.HighPart = ft.dwHighDateTime;
  733.     // Convert to microseconds.
  734.     ul.QuadPart /= 10ULL;
  735.     // Remove Windows to UNIX Epoch delta.
  736.     ul.QuadPart -= 11644473600000000ULL;
  737.     // Modulo to retrieve the microseconds.
  738.     p->tv_usec = (long)(ul.QuadPart % 1000000LL);
  739.     // Divide to retrieve the seconds.
  740.     p->tv_sec = (long)(ul.QuadPart / 1000000LL);
  741.  
  742.     return 0;
  743. }
  744. #endif
  745.  
  746. /*!
  747.     \brief      Initialise the timer. It writes the current time of the day in the structure PreviousTime.
  748. */
  749. //Initialize the timer
  750. void TimeOut::InitTimer()
  751. {
  752.     #if defined (_WIN32) || defined(_WIN64)
  753.     _gettimeofday(&PreviousTime, NULL);
  754.     #endif
  755.     #ifdef __linux__
  756.     gettimeofday(&PreviousTime, NULL);
  757.     #endif
  758. }
  759.  
  760. /*!
  761.     \brief      Returns the time elapsed since initialization.  It write the current time of the day in the structure CurrentTime.
  762.                 Then it returns the difference between CurrentTime and PreviousTime.
  763.     \return     The number of microseconds elapsed since the functions InitTimer was called.
  764.   */
  765. //Return the elapsed time since initialization
  766. unsigned long int TimeOut::ElapsedTime_ms()
  767. {
  768.     struct timeval CurrentTime;
  769.     int sec,usec;
  770.     #if defined (_WIN32) || defined(_WIN64)
  771.     _gettimeofday(&CurrentTime, NULL);
  772.     #endif
  773.     #ifdef __linux__
  774.     gettimeofday(&CurrentTime, NULL);
  775.     #endif                                                              // Get current time
  776.     sec=CurrentTime.tv_sec-PreviousTime.tv_sec;                         // Compute the number of second elapsed since last call
  777.     usec=CurrentTime.tv_usec-PreviousTime.tv_usec;                      // Compute
  778.     if (usec<0) {                                                       // If the previous usec is higher than the current one
  779.         usec=1000000-PreviousTime.tv_usec+CurrentTime.tv_usec;          // Recompute the microseonds
  780.         sec--;                                                          // Substract one second
  781.     }
  782.     return sec*1000+usec/1000;
  783. }
Advertisement
Add Comment
Please, Sign In to add comment