1515int hSerialPort;
1616termios2 tty;
1717
18- std::ofstream log (" log.log" , std::ios::out);
18+ std::ofstream logging (" log.log" , std::ios::out);
1919
2020void (*errorCallback)(int errorCode);
2121void (*readCallback)(int bytes);
@@ -32,16 +32,17 @@ void serialOpen(
3232 // Open new serial connection
3333 hSerialPort = open (portName, O_RDWR);
3434
35+ // Error if open fails
3536 if (hSerialPort == -1 ){
36- log << strerror (errno);
37- }
38- else {
39- log << hSerialPort;
37+ errorCallback (status (StatusCodes::INVALID_HANDLE_ERROR));
38+ return ;
4039 }
41-
4240
43- // Error if open fails
44- ioctl (hSerialPort, TCGETS2, &tty);
41+ // Get the current com configuration
42+ if (ioctl (hSerialPort, TCGETS2, &tty) == -1 ){
43+ errorCallback (status (StatusCodes::GET_STATE_ERROR));
44+ return ;
45+ }
4546
4647 tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
4748 tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
@@ -69,9 +70,9 @@ void serialOpen(
6970 tty.c_ispeed = baudrate;
7071 tty.c_ospeed = baudrate;
7172
72-
7373 // Data bits
7474 tty.c_cflag &= ~CSIZE; // CSIZE is a mask for the number of bits per character
75+
7576 switch (dataBits) {
7677 case 5 :
7778 tty.c_cflag |= CS5;
@@ -87,7 +88,6 @@ void serialOpen(
8788 break ;
8889 }
8990
90-
9191 // parity
9292 switch (parity) {
9393 case 0 :
@@ -116,13 +116,22 @@ void serialOpen(
116116 }
117117
118118 // Save tty settings, also checking for error
119- ioctl (hSerialPort, TCSETS2, &tty);
119+ if (ioctl (hSerialPort, TCSETS2, &tty) == -1 ){
120+ errorCallback (status (StatusCodes::SET_STATE_ERROR));
121+ return ;
122+ }
120123
121- // returnStatus(StatusCodes::SUCCESS) ;
124+ return ;
122125}
123126
124127void serialClose () {
125- close (hSerialPort);
128+ // Error if close fails
129+ if (close (hSerialPort) == -1 ) {
130+ errorCallback (status (StatusCodes::CLOSE_HANDLE_ERROR));
131+ return ;
132+ }
133+
134+ return ;
126135}
127136
128137auto serialRead (
@@ -131,7 +140,14 @@ auto serialRead(
131140 const int timeout,
132141 const int multiplier
133142) -> int {
134- return read (hSerialPort, static_cast <char *>(buffer), bufferSize);
143+ int bytesRead = read (hSerialPort, static_cast <char *>(buffer), bufferSize);
144+
145+ if (bytesRead >= 0 ){
146+ return bytesRead;
147+ }
148+
149+ errorCallback (status (StatusCodes::READ_ERROR));
150+ return 0 ;
135151}
136152
137153auto serialReadUntil (
@@ -155,12 +171,10 @@ auto serialWrite(
155171
156172 int bytesWritten = write (hSerialPort, tmp, bufferSize);
157173
158- if (bytesWritten > 0 ){
174+ if (bytesWritten >= 0 ){
159175 return bytesWritten;
160176 }
161177
162- log << strerror (errno);
163-
164178 errorCallback (status (StatusCodes::WRITE_ERROR));
165179 return 0 ;
166180}
0 commit comments