summaryrefslogtreecommitdiff
path: root/src/NMEAParser.cpp
blob: e7b0901912cfe07c6ed407cc4ae37dfd5dcc84bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
277
278
279
280
281
282
283
284
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
331
332
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 * NMEAParser.cpp
 *
 *  Created on: Aug 12, 2014
 *      Author: Cameron Karlsson
 *
 *  See the license file included with this source.
 */

#include <nmeaparse/NMEAParser.h>
#include <nmeaparse/NumberConversion.h>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cctype>

using namespace std;
using namespace nmea;



// --------- NMEA PARSE ERROR--------------

NMEAParseError::NMEAParseError(std::string msg)
	: message(msg)
{}
NMEAParseError::NMEAParseError(std::string msg, NMEASentence n)
	: message(msg), nmea(n)
{}

NMEAParseError::~NMEAParseError()
{}

std::string NMEAParseError::what(){
	return message;
}




// --------- NMEA SENTENCE --------------

NMEASentence::NMEASentence() 
: isvalid(false)
, checksumIsCalculated(false)
, calculatedChecksum(0)
, parsedChecksum(0)
{ }

NMEASentence::~NMEASentence()
{ }

bool NMEASentence::valid() const {
	return isvalid;
}

bool NMEASentence::checksumOK() const {
	return (checksumIsCalculated)
		&&
		(parsedChecksum == calculatedChecksum);
}



// true if the text contains a non-alpha numeric value
bool hasNonAlphaNum(string txt){
	for (size_t i = 0; i < txt.size(); i++){
		if ( !isalnum(txt[i]) ){
			return true;
		}
	}
	return false;
}

// true if alphanumeric or '-'
bool validParamChars(string txt){
	for (size_t i = 0; i < txt.size(); i++){
		if (!isalnum(txt[i])){
			if (txt[i] != '-' && txt[i] != '.'){
				return false;
			}
		}
	}
	return true;
}

// remove all whitespace
void squish(string& str){

	char chars[] = {'\t',' '};
	for (size_t i = 0; i < sizeof(chars); ++i)
	{
		// needs include <algorithm>
		str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
	}
}

// remove side whitespace
void trim(string& str){
	stringstream trimmer;
	trimmer << str;
	str.clear();
	trimmer >> str;
}


// --------- NMEA PARSER --------------



NMEAParser::NMEAParser() 
: log(false)
, maxbuffersize(NMEA_PARSER_MAX_BUFFER_SIZE)
, fillingbuffer(false)
{ }

NMEAParser::~NMEAParser() 
{ }


void NMEAParser::setSentenceHandler(std::string cmdKey, std::function<void(const NMEASentence&)> handler){
	eventTable.erase(cmdKey);
	eventTable.insert({ cmdKey, handler });
}
string NMEAParser::getRegisteredSentenceHandlersCSV()
{
	if(eventTable.empty()){
		return "";
	}

	ostringstream ss;
	for( auto it = eventTable.begin(); it != eventTable.end(); it++){
		ss << it->first;

		if( ! it->second ){
			ss << "(not callable)";
		}
		ss << ",";
	}
	string s = ss.str();
	if( ! s.empty() ){
		s.resize(s.size()-1); // chop off comma
	}
	return s;
}

void NMEAParser::readByte(uint8_t b){
	uint8_t startbyte = '$';

	if (fillingbuffer){
		if (b == '\n'){
			buffer.push_back(b);
			try {
				readSentence(buffer);
				buffer.clear();
				fillingbuffer = false;
			}
			catch (exception&){
				// If anything happens, let it pass through, but reset the buffer first.
				buffer.clear();
				fillingbuffer = false;
				throw;
			}
		}
		else{
			if (buffer.size() < maxbuffersize){
				buffer.push_back(b);
			}
			else {
				buffer.clear();			//clear the host buffer so it won't overflow.
				fillingbuffer = false;
			}
		}
	}
	else {
		if (b == startbyte){			// only start filling when we see the start byte.
			fillingbuffer = true;
			buffer.push_back(b);
		}
	}
}

void NMEAParser::readBuffer(uint8_t* b, uint32_t size){
	for (uint32_t i = 0; i < size; ++i){
		readByte(b[i]);
	}
}

void NMEAParser::readLine(string cmd){
	cmd += "\r\n";
	for (size_t i = 0; i < cmd.size(); ++i){
		readByte(cmd[i]);
	}
}

// Loggers
void NMEAParser::onInfo(NMEASentence& nmea, string txt){
	if (log){
		cout << "[Info]    " << txt << endl;
	}
}
void NMEAParser::onWarning(NMEASentence& nmea, string txt){
	if (log){
		cout << "[Warning] " << txt << endl;
	}
}
void NMEAParser::onError(NMEASentence& nmea, string txt){
	throw NMEAParseError("[ERROR] " + txt);
}

// takes a complete NMEA string and gets the data bits from it,
// calls the corresponding handler in eventTable, based on the 5 letter sentence code
void NMEAParser::readSentence(std::string cmd){

	NMEASentence nmea;

	onInfo(nmea, "Processing NEW string...");
	
	if (cmd.size() == 0){
		onWarning(nmea, "Blank string -- Skipped processing.");
		return;
	}
	
	// If there is a newline at the end (we are coming from the byte reader
	if ( *(cmd.end()-1) == '\n'){
		if (*(cmd.end() - 2) == '\r'){	// if there is a \r before the newline, remove it.
			cmd = cmd.substr(0, cmd.size() - 2);
		}
		else
		{
			onWarning(nmea, "Malformed newline, missing carriage return (\\r) ");
			cmd = cmd.substr(0, cmd.size()-1);
		}
	}

	ios_base::fmtflags oldflags = cout.flags();

	// Remove all whitespace characters.
	size_t beginsize = cmd.size();
	squish(cmd);
	if (cmd.size() != beginsize){
		stringstream ss;
		ss << "New NMEA string was full of " << (beginsize - cmd.size()) << " whitespaces!";
		onWarning(nmea, ss.str());
	}

	
	onInfo(nmea, string("NMEA string: (\"") + cmd + "\")");
	

	// Seperates the data now that everything is formatted
	try{
		parseText(nmea, cmd);
	}
	catch (NMEAParseError&){
		throw;
	}
	catch (std::exception& e){
		string s = " >> NMEA Parser Internal Error: Indexing error?... ";
		throw std::runtime_error(s + e.what());
	}
	cout.flags(oldflags);  //reset

	// Handle/Throw parse errors
	if (!nmea.valid()){

		size_t linewidth = 35;
		stringstream ss;
		if (nmea.text.size() > linewidth){
			ss << "Invalid text. (\"" << nmea.text.substr(0, linewidth) << "...\")";
		}
		else{
			ss << "Invalid text. (\"" << nmea.text << "\")";
		}

		onError(nmea, ss.str());
		return;
	}
	

	// Call the "any sentence" event handler, even if invalid checksum, for possible logging elsewhere.
	onInfo(nmea, "Calling generic onSentence().");
	onSentence(nmea);


	// Call event handlers based on map entries
	function<void(const NMEASentence&)> handler = eventTable[nmea.name];
	if (handler){
		onInfo(nmea, string("Calling specific handler for sentence named \"") + nmea.name + "\"");
		handler(nmea);
	}
	else
	{
		onWarning(nmea, string("Null event handler for type (name: \"") + nmea.name + "\")");
	}





	cout.flags(oldflags);  //reset

}

// takes the string *between* the '$' and '*' in nmea sentence,
// then calculates a rolling XOR on the bytes
uint8_t NMEAParser::calculateChecksum(string s){
	uint8_t checksum = 0;
	for (size_t i = 0; i < s.size(); i++){
		checksum = checksum ^ s[i];
	}

	// will display the calculated checksum in hex
	//if(log)
	//{
	//	ios_base::fmtflags oldflags = cout.flags();
	//	cout << "NMEA parser Info: calculated CHECKSUM for \""  << s << "\": 0x" << std::hex << (int)checksum << endl;
	//	cout.flags(oldflags);  //reset
	//}
	return checksum;
}


void NMEAParser::parseText(NMEASentence& nmea, string txt){

	if (txt.size() == 0){
		nmea.isvalid = false;
		return;
	}

	nmea.isvalid = false;	// assume it's invalid first
	nmea.text = txt;		// save the received text of the sentence

	// Looking for index of last '$'
	size_t startbyte = 0;
	size_t dollar = txt.find_last_of('$');
	if (dollar == string::npos){
		// No dollar sign... INVALID!
		return;
	}
	else
	{
		startbyte = dollar;
	}


	// Get rid of data up to last'$'
	txt = txt.substr(startbyte + 1);


	// Look for checksum
	size_t checkstri = txt.find_last_of('*');
	bool haschecksum = checkstri != string::npos;
	if (haschecksum){
		// A checksum was passed in the message, so calculate what we expect to see
		nmea.calculatedChecksum = calculateChecksum(txt.substr(0, checkstri));
	}
	else
	{
		// No checksum is only a warning because some devices allow sending data with no checksum.
		onWarning(nmea, "No checksum information provided. Could not find '*'.");
	}

	// Handle comma edge cases
	size_t comma = txt.find(',');
	if (comma == string::npos){		//comma not found, but there is a name...
		if (txt.size() > 0)
		{	// the received data must just be the name
			if ( hasNonAlphaNum(txt) ){
				nmea.isvalid = false;
				return;
			}
			nmea.name = txt;
			nmea.isvalid = true;
			return;
		}
		else
		{	//it is a '$' with no information
			nmea.isvalid = false;
			return;	
		}
	}

	//"$," case - no name
	if (comma == 0){
		nmea.isvalid = false;
		return;
	}


	//name should not include first comma
	nmea.name = txt.substr(0, comma);	
	if ( hasNonAlphaNum(nmea.name) ){
		nmea.isvalid = false;
		return;
	}


	//comma is the last character/only comma
	if (comma + 1 == txt.size()){		
		nmea.parameters.push_back("");
		nmea.isvalid = true;
		return;	
	}


	//move to data after first comma
	txt = txt.substr(comma + 1, txt.size() - (comma + 1));

	//parse parameters according to csv
	istringstream f(txt);
	string s;
	while (getline(f, s, ',')) {
		//cout << s << endl;
		nmea.parameters.push_back(s);
	}


	//above line parsing does not add a blank parameter if there is a comma at the end...
	// so do it here.
	if (*(txt.end() - 1) == ','){

		// supposed to have checksum but there is a comma at the end... invalid
		if (haschecksum){
			nmea.isvalid = false;
			return;
		}

		//cout << "NMEA parser Warning: extra comma at end of sentence, but no information...?" << endl;		// it's actually standard, if checksum is disabled
		nmea.parameters.push_back("");

		stringstream sz;
		sz << "Found " << nmea.parameters.size() << " parameters.";
		onInfo(nmea, sz.str());

	}
	else
	{
		stringstream sz;
		sz << "Found " << nmea.parameters.size() << " parameters.";
		onInfo(nmea, sz.str());

		//possible checksum at end...
		size_t endi = nmea.parameters.size() - 1;
		size_t checki = nmea.parameters[endi].find_last_of('*');
		if (checki != string::npos){
			string last = nmea.parameters[endi];
			nmea.parameters[endi] = last.substr(0, checki);
			if (checki == last.size() - 1){
				onError(nmea, "Checksum '*' character at end, but no data.");
			}
			else{
				nmea.checksum = last.substr(checki + 1, last.size() - checki);		//extract checksum without '*'

				onInfo(nmea, string("Found checksum. (\"*") + nmea.checksum + "\")");

				try
				{
					nmea.parsedChecksum = (uint8_t)parseInt(nmea.checksum, 16);
					nmea.checksumIsCalculated = true;
				}
				catch( NumberConversionError& )
				{
					onError(nmea, string("parseInt() error. Parsed checksum string was not readable as hex. (\"") +  nmea.checksum + "\")");
				}
				
				onInfo(nmea, string("Checksum ok? ") + (nmea.checksumOK() ? "YES" : "NO") + "!");
				

			}
		}
	}


	for (size_t i = 0; i < nmea.parameters.size(); i++){
		if (!validParamChars(nmea.parameters[i])){
			nmea.isvalid = false;
			stringstream ss;
			ss << "Invalid character (non-alpha-num) in parameter " << i << " (from 0): \"" << nmea.parameters[i] << "\"";
			onError(nmea, ss.str() );
			break;
		}
	}


	nmea.isvalid = true;

	return;

}