Com_Serial.cpp 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
/**
 * @brief Tool class which convey to open a serial port
 * @file serial_port.cpp
 * 
 * @author Sylvain Colomer
 * @date 19/04/19
 * @version 1.1 
 */

10
11
12

#include <iostream>
#include <string>
13
14
#include <sys/time.h>
#include <chrono>
15
16
17

using namespace std;

18
19
20
21
22
23
24
25


#include <iostream>
#include <fstream>	
extern ofstream MyFilew;
double t_oldw = -1.;


26
27
#include "../include/Com_Serial.h"

28
29
Serial_Port::Serial_Port(std::string uart_name, int baudrate)
{
30
31
32
33
34
	initialize_defaults();
	Serial_Port::uart_name = uart_name;
	Serial_Port::baudrate  = baudrate;
}

35
36
Serial_Port::Serial_Port()
{
37
38
39
	initialize_defaults();
}

40
41
Serial_Port::~Serial_Port()
{
42
43
44
	pthread_mutex_destroy(&lock);
}

45
46
void Serial_Port::initialize_defaults()
{
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	// Initialize attributes
	debug  = false;
	fd     = -1;
	status = SERIAL_PORT_CLOSED;

	uart_name = (char*)"/dev/ttyUSB0";
	baudrate  = 57600;

	// Start mutex
	int result = pthread_mutex_init(&lock, NULL);
	if ( result != 0 )
	{
		printf("\n mutex init failed\n");
		throw 1;
	}
}


/**
 * Read from Serial
 */
68
69
int Serial_Port::read_message(mavlink_message_t &message)
{
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
	uint8_t          cp;
	mavlink_status_t status;
	uint8_t          msgReceived = false;

	// --------------------------------------------------------------------------
	//   READ FROM PORT
	// --------------------------------------------------------------------------

	// this function locks the port during read
	int result = _read_port(cp);


	// --------------------------------------------------------------------------
	//   PARSE MESSAGE
	// --------------------------------------------------------------------------
	if (result > 0)
	{
		
		msgReceived = mavlink_parse_char(MAVLINK_COMM_1, cp, &message, &status);

		// check for dropped packets
		if ( (lastStatus.packet_rx_drop_count != status.packet_rx_drop_count) && debug )
		{
			printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count);
			unsigned char v=cp;
			fprintf(stderr,"%02x ", v);
		}
		lastStatus = status;
	}
	else // Couldn't read from port
	{ 
		//Display_IHM::getInstanceOf().printLog("ERROR: Could'nt read serial");
	}

	// --------------------------------------------------------------------------
	//   DEBUGGING REPORTS
	// --------------------------------------------------------------------------
	if(msgReceived && debug)
	{
		// Report info
		printf("Received message from serial with ID #%d (sys:%d|comp:%d):", message.msgid, message.sysid, message.compid);

		fprintf(stderr,"Received serial data: ");
		unsigned int i;
		uint8_t buffer[MAVLINK_MAX_PACKET_LEN];

		// check message is write length
		unsigned int messageLength = mavlink_msg_to_send_buffer(buffer, &message);

		// message length error
		if (messageLength > MAVLINK_MAX_PACKET_LEN)
		{
			fprintf(stderr, "\nFATAL ERROR: MESSAGE LENGTH IS LARGER THAN BUFFER SIZE\n");
		}

		// print out the buffer
		else
		{
			for (i=0; i<messageLength; i++)
			{
				unsigned char v=buffer[i];
				fprintf(stderr,"%02x ", v);
			}
			fprintf(stderr,"\n");
		}
	}

	// Done!
	return msgReceived;
}

/**
 * Write to Serial
 */
144
145
int Serial_Port::write_message(const mavlink_message_t &message)
{
146
147
148
149
	char buf[300];

	// Translate message to buffer
	unsigned len = mavlink_msg_to_send_buffer((uint8_t*)buf, &message);
150
 //  cout<<__FUNCTION__<<" after mavlink_msg_to_send_buffer"<<endl;
151
152
153

	// Write buffer to serial port, locks port while writing
	int bytesWritten = _write_port(buf,len);
154
//   cout<<__FUNCTION__<<" writting done"<<endl;
155
156
157
158
159
160
161

	return bytesWritten;
}

/**
 * Open Serial Port
 */
162
163
int Serial_Port::open_serial()
{
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
	fd = _open_port(uart_name.c_str());

	// Check success
	if (fd == -1)
	{
		//Display_IHM::getInstanceOf().printLog("failure, could not open port");
		return 1;
	}

	bool success = _setup_port(baudrate);

	if (!success)
	{
		//Display_IHM::getInstanceOf().printLog("failure, could not configure port");
		return 1;
	}
	if (fd <= 0)
	{
		//Display_IHM::getInstanceOf().printLog("Connection failed, exiting.\n");
		return 1;
	}
	
	lastStatus.packet_rx_drop_count = 0;

	status = true;
	return 0;
}


/**
 * Close Serial Port
 */
196
197
void Serial_Port::close_serial()
{
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
	//Display_IHM::getInstanceOf().printLog("CLOSE PORT\n");

	int result = close(fd);
	if ( result )
	{
		fprintf(stderr,"WARNING: Error on port close (%i)\n", result );
	}

	status = false;
}


/**
 * Quit Handler
 */
213
214
215
216
void Serial_Port::handle_quit()
{
	try 
   {
217
218
		close_serial();
	}
219
220
	catch (int error) 
   {
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
		fprintf(stderr,"Warning, could not stop serial port\n");
	}
}


/**
 * Helper Function - Open Serial Port File Descriptor
 */
int Serial_Port::_open_port(const char* port){
	// Open serial port
	// O_RDWR - Read and write
	// O_NOCTTY - Ignore special chars like CTRL-C
	fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);

	// Check for Errors
	if (fd == -1)
	{
		/* Could not open the port. */
		return(-1);
	}

	// Finalize
	else
	{
		fcntl(fd, F_SETFL, 0);
	}

	// Done!
	return fd;
}

/**
 * Helper Function - Setup Serial Port
 */
bool Serial_Port::_setup_port(int baud)
{
	// Check file descriptor
	if(!isatty(fd))
	{
		fprintf(stderr, "\nERROR: file descriptor %d is NOT a serial port\n", fd);
		return false;
	}

	// Read file descritor configuration
	struct termios  config;
	if(tcgetattr(fd, &config) < 0)
	{
		fprintf(stderr, "\nERROR: could not read configuration of fd %d\n", fd);
		return false;
	}

	// Input flags - Turn off input processing
	// convert break to null byte, no CR to NL translation,
	// no NL to CR translation, don't mark parity errors or breaks
	// no input parity check, don't strip high bit off,
	// no XON/XOFF software flow control
277
	config.c_iflag &= ~(IGNBRK | BRKINT | ICRNL |INLCR | PARMRK | INPCK | ISTRIP | IXON);
278
279
280
281
282
283

	// Output flags - Turn off output processing
	// no CR to NL translation, no NL to CR-NL translation,
	// no NL to CR translation, no column 0 CR suppression,
	// no Ctrl-D suppression, no fill characters, no case mapping,
	// no local output processing
284
	config.c_oflag &= ~(OCRNL | ONLCR | ONLRET | ONOCR | OFILL | OPOST);
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330

	#ifdef OLCUC
		config.c_oflag &= ~OLCUC;
	#endif

	#ifdef ONOEOT
		config.c_oflag &= ~ONOEOT;
	#endif

	// No line processing:
	// echo off, echo newline off, canonical mode off,
	// extended input processing off, signal chars off
	config.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);

	// Turn off character processing
	// clear current char size mask, no parity checking,
	// no output processing, force 8 bit input
	config.c_cflag &= ~(CSIZE | PARENB);
	config.c_cflag |= CS8;

	// One input byte is enough to return from read()
	// Inter-character timer off
	config.c_cc[VMIN]  = 1;
	config.c_cc[VTIME] = 10; // was 0

	// Get the current options for the port
	////struct termios options;
	////tcgetattr(fd, &options);

	// Apply baudrate
	switch (baud)
	{
		case 1200:
			if (cfsetispeed(&config, B1200) < 0 || cfsetospeed(&config, B1200) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;
		case 1800:
			cfsetispeed(&config, B1800);
			cfsetospeed(&config, B1800);
			break;
		case 9600:
			cfsetispeed(&config, B9600);
			cfsetospeed(&config, B9600);
331
332
			break; 
			
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
		case 19200:
			cfsetispeed(&config, B19200);
			cfsetospeed(&config, B19200);
			break;
		case 38400:
			if (cfsetispeed(&config, B38400) < 0 || cfsetospeed(&config, B38400) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;
		case 57600:
			if (cfsetispeed(&config, B57600) < 0 || cfsetospeed(&config, B57600) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;
		case 115200:
			if (cfsetispeed(&config, B115200) < 0 || cfsetospeed(&config, B115200) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;

		// These two non-standard (by the 70'ties ) rates are fully supported on
		// current Debian and Mac OS versions (tested since 2010).
		case 460800:
			if (cfsetispeed(&config, B460800) < 0 || cfsetospeed(&config, B460800) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;
		case 921600:
			if (cfsetispeed(&config, B921600) < 0 || cfsetospeed(&config, B921600) < 0)
			{
				fprintf(stderr, "\nERROR: Could not set desired baud rate of %d Baud\n", baud);
				return false;
			}
			break;
		default:
			fprintf(stderr, "ERROR: Desired baud rate %d could not be set, aborting.\n", baud);
			return false;

			break;
	}

	// Finally, apply the configuration
	if(tcsetattr(fd, TCSAFLUSH, &config) < 0)
	{
		fprintf(stderr, "\nERROR: could not set configuration of fd %d\n", fd);
		return false;
	}

	// Done!
	return true;
391
392
}  

393
394
395
396
397


/**
 * Read Port with Lock
 */
398
399
int Serial_Port::_read_port(uint8_t &cp)
{	 
400
	// Lock
401
//   cout<<__FUNCTION__<<" : try read \n";
402
403
	pthread_mutex_lock(&lock);
	int result = read(fd, &cp, 1);
404
//   cout<<__FUNCTION__<<" : reading nb = "<<result<<"\n"; 
405
406
407
408
409
410
411
412
413
414

	// Unlock
	pthread_mutex_unlock(&lock);

	return result;
}

/**
 *  Write Port with Lock
 */
415
416
int Serial_Port::_write_port(char *buf, unsigned len)
{
417
418
419
420
421
422
423
424
425
	struct timeval tw;
	double t_currentw, dtw;
	gettimeofday(&tw, NULL);
	t_currentw = tw.tv_sec+tw.tv_usec*1e-6; 
	
// Lock
 //  cout<<__FUNCTION__<<" : try write = "<< len<<" \n";
 	pthread_mutex_lock(&lock);
 //  cout<<__FUNCTION__<<" : writing \n";
426
427
428

	// Write packet via serial link
	const int bytesWritten = static_cast<int>(write(fd, buf, len));
429
	
430

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
using namespace std::chrono;
  
// Use auto keyword to avoid typing long
// type definitions to get the timepoint
// at this instant use function now()

		auto start = high_resolution_clock::now();
      	tcdrain(fd);
		auto stop = high_resolution_clock::now();     	
		auto duration = duration_cast<microseconds>(stop - start);
		cout << "Time taken by function: " << duration.count() << " microseconds" << endl;

		MyFilew << duration.count() << endl;
/*     	  
    int iterations = 1913;
 for (int i=0; i<iterations; i++) {    
    	tcdrain(fd);

sum += add;
        add /= 2.0;
	}
        
         gettimeofday(&end, 0);
    long seconds = end.tv_sec - begin.tv_sec;
    long microseconds = end.tv_usec - begin.tv_usec;
    double elapsed = seconds + microseconds*1e-6;
    
        
459
	// Unlock
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
	/*if(t_oldw>0.)
				{
					
					
					// Wait until all data has been written
					dtw=t_currentw-t_oldw;
					cout<<"\n \n >>>>  latencytcdrain: "<<dtw<<"\n\n\n";
				
				t_oldw=t_currentw;
				cout<<"latencytcdrain = "<<t_oldw<<endl;
			  double sum = 0;
    double add = 1;

    // Start measuring time
    struct timeval begin, end;
    gettimeofday(&begin, 0);
  
			}*/
	//	   MyFilew << elapsed << endl;
			   
    pthread_mutex_unlock(&lock);

		   
483
	return bytesWritten;
484

485
486
487
}