summaryrefslogtreecommitdiff
path: root/plugins/gpsnmea/gpsnmea.cpp
blob: 8a547b4e05c34b48a8f1ca8abe6b18280e611dbc (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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/*
Copyright (C) 2012 Intel Corporation

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "gpsnmea.h"
#include "timestamp.h"
#include "serialport.hpp"
#include "bluetooth.hpp"
#include "bluetooth5.h"
#include <listplusplus.h>
#include <superptr.hpp>
#include <ambplugin.h>

#include <dbusplugin.h>
#include <dbusexport.h>

#include <iostream>
#include <boost/assert.hpp>
#include <boost/algorithm/string.hpp>
#include <time.h>


using namespace std;

#include "debugout.h"
#include "abstractpropertytype.h"

#define GPSTIME "GpsTime"
#define GPSSPEED "GpsSpeed"
#define GpsFix "GpsFix"
#define GpsSatsUsed "GpsSatsUsed"
#define GpsNmea "GpsNmea"

template<typename T2>
inline T2 lexical_cast(const std::string &in) {
	T2 out;
	std::stringstream ss;
	ss << std::hex << in;
	ss >> out;
	return out;
}

class GpsInfo: public DBusSink
{
public:
	GpsInfo(VehicleProperty::Property, AbstractRoutingEngine* re, GDBusConnection* connection)
		:DBusSink("GpsInfo", re, connection, map<string, string>())
	{
		wantPropertyVariant(GPSTIME, "GpsTime", VariantType::Read);
		wantPropertyVariant(GPSSPEED, "Speed", VariantType::Read);
		wantPropertyVariant(GpsFix, "Fix", VariantType::Read);
		wantPropertyVariant(GpsSatsUsed, "SattelitesUsed", VariantType::Read);
		wantPropertyVariant(GpsNmea, "RawNmea", VariantType::Read);
	}
};

class Location
{
public:
	enum FixType {
		NoFix = 1,
		Fix2D = 2,
		Fix3D = 3
	};

	Location(AmbPluginImpl *source, std::shared_ptr<AbstractPropertyType> lat,
			 std::shared_ptr<AbstractPropertyType> lon,
			 std::shared_ptr<AbstractPropertyType> alt,
			 std::shared_ptr<AbstractPropertyType> dir,
			 std::shared_ptr<AbstractPropertyType> spd,
			 std::shared_ptr<AbstractPropertyType> time,
			 std::shared_ptr<AbstractPropertyType> fix,
			 std::shared_ptr<AbstractPropertyType> satsUsed,
			 std::shared_ptr<AbstractPropertyType> vspd);

	void parse(std::string gprmc);

	AbstractPropertyType * latitude()
	{
		return mLatitude.get();
	}

	AbstractPropertyType * longitude()
	{
		return mLongitude.get();
	}

	AbstractPropertyType * altitude()
	{
		return mAltitude.get();
	}

	AbstractPropertyType * direction()
	{
		return mDirection.get();
	}

	AbstractPropertyType * speed()
	{
		return mSpeed.get();
	}

	AbstractPropertyType * gpsTime()
	{
		return mGpsTime.get();
	}

	std::list<AbstractPropertyType*> fix()
	{
		std::list<AbstractPropertyType*> l;

		l.push_back(mLatitude.get());
		l.push_back(mLongitude.get());
		l.push_back(mAltitude.get());
		l.push_back(mDirection.get());
		l.push_back(mSpeed.get());
		l.push_back(mGpsTime.get());

		return l;
	}

private: ///methods:

	void parseGprmc(string gprmc);
	void parseGpgga(string gpgga);
	void parseGpgsa(string gpgsa);

	void parseTime(std::string h, std::string m, std::string s, string dd, string mm, string yy);
	void parseLatitude(std::string d, std::string m, std::string ns);
	void parseLongitude(std::string d, string m, string ew);
	void parseSpeed(std::string spd);
	void parseDirection(std::string dir);
	void parseAltitude(std::string alt);

	double degsToDecimal(double degs);

private:

	std::shared_ptr<AbstractPropertyType> mLatitude;
	std::shared_ptr<AbstractPropertyType> mLongitude;
	std::shared_ptr<AbstractPropertyType> mAltitude;
	std::shared_ptr<AbstractPropertyType> mDirection;
	std::shared_ptr<AbstractPropertyType> mSpeed;
	std::shared_ptr<AbstractPropertyType> mVehicleSpeed;
	std::shared_ptr<AbstractPropertyType> mGpsTime;
	std::shared_ptr<AbstractPropertyType> mFix;
	std::shared_ptr<AbstractPropertyType> mSatelitesUsed;

	bool isActive;

	AmbPluginImpl * parent;

};

Location::Location(AmbPluginImpl* source,
				   std::shared_ptr<AbstractPropertyType> lat,
				   std::shared_ptr<AbstractPropertyType> lon,
				   std::shared_ptr<AbstractPropertyType> alt,
				   std::shared_ptr<AbstractPropertyType> dir,
				   std::shared_ptr<AbstractPropertyType> spd,
				   std::shared_ptr<AbstractPropertyType> time,
				   std::shared_ptr<AbstractPropertyType> fix,
				   std::shared_ptr<AbstractPropertyType> satsUsed,
				   std::shared_ptr<AbstractPropertyType> vspd)
	:parent(source), isActive(false)
{
	mLatitude = lat;
	mLongitude = lon;
	mAltitude = alt;
	mDirection = dir;
	mSpeed = spd;
	mGpsTime = time;
	mFix = fix;
	mSatelitesUsed = satsUsed;
	mVehicleSpeed = vspd;
}

void Location::parse(string nmea)
{
	if(boost::algorithm::starts_with(nmea,"GPRMC") || boost::algorithm::starts_with(nmea,"GNRMC"))
	{
		parseGprmc(nmea);
	}
	else if(boost::algorithm::starts_with(nmea,"GPGGA"))
	{
		parseGpgga(nmea);
	}
	else if(boost::algorithm::starts_with(nmea, "GPGSA"))
	{
		parseGpgsa(nmea);
	}
	else
	{
		DebugOut(7)<<"unknown/unhandled message: "<<nmea<<endl;
	}
}

void Location::parseGprmc(string gprmc)
{
	DebugOut(7)<<"parsing gprmc message"<<endl;

	std::vector<std::string> tokens;
	boost::split(tokens, gprmc, boost::is_any_of(","));

	if(!tokens.size())
	{
		return;
	}

	if(tokens[2] == "A")
	{
		isActive = true;
	}

	if(tokens[1].empty() || tokens[9].empty() || tokens[3].empty() || tokens[4].empty() || tokens[5].empty() || tokens[6].empty() || tokens[7].empty() || tokens[8].empty())
	{
		return;
	}

	parseTime(tokens[1].substr(0,2),tokens[1].substr(2,2),tokens[1].substr(4,2),tokens[9].substr(0,2),tokens[9].substr(2,2),tokens[9].substr(4,2));

	parseLatitude(tokens[3], "", tokens[4]);
	parseLongitude(tokens[5], "", tokens[6]);
	parseSpeed(tokens[7]);
	parseDirection(tokens[8]);

}

void Location::parseGpgga(string gpgga)
{

	std::vector<std::string> tokens;
	boost::split(tokens, gpgga, boost::is_any_of(","));

	if(tokens.size() != 15)
	{
		DebugOut()<<"Invalid GPGGA message: "<<gpgga<<endl;
		return;
	}

	parseLatitude(tokens[2],"",tokens[3]);
	parseLongitude(tokens[4],"",tokens[5]);
	if(tokens[6] != "0")
	{
		isActive = true;
	}
	else isActive = false;

	parseAltitude(tokens[9]);
}

void Location::parseGpgsa(string gpgsa)
{
	std::vector<std::string> tokens;
	boost::split(tokens, gpgsa, boost::is_any_of(","));

	if(tokens.size() != 18)
	{
		DebugOut()<<"Invalid GPGSA message: "<<gpgsa<<endl;
		return;
	}

	Location::FixType fix = (Location::FixType)boost::lexical_cast<int>(tokens[2]);

	uint16_t numsats = 0;

	for(int i=3; i<15; i++)
	{
		std::string sat = tokens[i];
		if(!sat.empty())
		{
			numsats ++;
		}
	}

	if(mFix->value<Location::FixType>() != fix)
		parent->setValue(mFix, fix);

	if(mSatelitesUsed->value<uint16_t>() != numsats)
		parent->setValue(mSatelitesUsed, numsats);
}

void Location::parseTime(string h, string m, string s, string dd, string mm, string yy)
{
	try
	{
		tm t;
		t.tm_hour = boost::lexical_cast<int>(h);
		t.tm_min = boost::lexical_cast<int>(m);
		t.tm_sec = boost::lexical_cast<int>(s);
		t.tm_mday = boost::lexical_cast<int>(dd);
		t.tm_mon = boost::lexical_cast<int>(mm) - 1;
		t.tm_year = boost::lexical_cast<int>(yy) + 100;

		time_t time = timegm(&t);

		if(mGpsTime->value<double>() != (double(time)))
		{
			parent->setValue(mGpsTime, double(time));
		}
	}
	catch(...)
	{
		DebugOut(5)<<"Failed to parse time "<<endl;
	}
}

void Location::parseLatitude(string d, string m, string ns)
{
	try
	{
		if(d.empty() )
			return;

		double degs = boost::lexical_cast<double>(d + m);
		double dec = degsToDecimal(degs);

		if(ns == "S")
			dec *= -1;

		if(mLatitude->value<double>() != dec)
		{
			parent->setValue(mLatitude, dec);
		}
	}
	catch(...)
	{
		DebugOut(5)<<"Failed to parse latitude"<<endl;
	}
}

void Location::parseLongitude(string d, string m, string ew)
{
	try
	{
		if(d.empty()) return;

		double degs = boost::lexical_cast<double>(d + m);
		double dec = degsToDecimal(degs);

		if(ew == "W")
			dec *= -1;

		if(mLongitude->value<double>() != dec)
		{
			parent->setValue(mLongitude, dec);
		}
	}
	catch(...)
	{
		DebugOut(5)<<"failed to parse longitude: "<<d<<" "<<m<<" "<<ew<<endl;
	}
}

void Location::parseSpeed(string spd)
{
	try
	{
		double s = boost::lexical_cast<double>(spd);

		///to kph:
		s *= 1.852;

		uint16_t speed = static_cast<uint16_t>(s);

		if(mSpeed->value<uint16_t>() != speed)
		{
			parent->setValue(mSpeed, speed);
		}
	}
	catch(...)
	{
		DebugOut(5)<<"failed to parse speed"<<endl;
	}
}

void Location::parseDirection(string dir)
{
	try {
		uint16_t d = boost::lexical_cast<double>(dir);

		if(mDirection->value<uint16_t>() != d)
		{
			parent->setValue(mDirection, d);
		}
	}
	catch(...)
	{
		DebugOut(5) << "Failed to parse direction: " << dir << endl;
	}
}

void Location::parseAltitude(string alt)
{
	try{

		if(alt.empty()) return;

		double a = boost::lexical_cast<double>(alt);

		if(mAltitude->value<double>() != a)
		{
			parent->setValue(mAltitude, a);
		}
	}
	catch(...)
	{
		DebugOut(5)<<"failed to parse altitude"<<endl;
	}
}

double Location::degsToDecimal(double degs)
{
	double deg;
	double min = 100.0 * modf(degs / 100.0, &deg);
	return deg + (min / 60.0);
}

bool readCallback(GIOChannel *source, GIOCondition condition, gpointer data)
{
//	DebugOut(5) << "Polling..." << condition << endl;

	if(condition & G_IO_ERR)
	{
		DebugOut(DebugOut::Error)<<"GpsNmeaSource polling error."<<endl;
	}

	if (condition & G_IO_HUP)
	{
		//Hang up. Returning false closes out the GIOChannel.
		//printf("Callback on G_IO_HUP\n");
		DebugOut(DebugOut::Warning)<<"socket hangup event..."<<endl;
		return false;
	}

	GpsNmeaSource* src = static_cast<GpsNmeaSource*>(data);

	src->canHasData();

	return true;
}

extern "C" void create(AbstractRoutingEngine* routingengine, map<string, string> config)
{
	auto plugin = new AmbPlugin<GpsNmeaSource>(routingengine, config);
	plugin->init();
}

GpsNmeaSource::GpsNmeaSource(AbstractRoutingEngine *re, map<string, string> config, AbstractSource &parent)
	:AmbPluginImpl(re, config, parent), mUuid("33d86462-1708-4f78-a001-99ea8d55422b"), device(nullptr), bt(nullptr)
{
	int baudrate = 0;

	auto lat = addPropertySupport<VehicleProperty::LatitudeType>(Zone::None);
	auto lon = addPropertySupport<VehicleProperty::LongitudeType>(Zone::None);
	auto alt = addPropertySupport<VehicleProperty::AltitudeType>(Zone::None);
	auto spd = addPropertySupport(Zone::None, [](){ return new BasicPropertyType<uint16_t>(GPSSPEED, 0); });
	auto vspd = addPropertySupport<VehicleProperty::VehicleSpeedType>(Zone::None);
	auto dir = addPropertySupport<VehicleProperty::DirectionType>(Zone::None);
	auto time = addPropertySupport(Zone::None, [](){ return new BasicPropertyType<double>(GPSTIME, 0); });
	auto fix = addPropertySupport(Zone::None, []() { return new BasicPropertyType<Location::FixType>(GpsFix, Location::NoFix); });
	auto satsUsed = addPropertySupport(Zone::None, []() { return new BasicPropertyType<uint16_t>(GpsSatsUsed, 0); });
	rawNmea = addPropertySupport(Zone::None, []() { return new StringPropertyType(GpsNmea); });

	location = new Location(this, lat, lon, alt, dir, spd, time, fix, satsUsed, vspd);

	std::string btaddapter = config["bluetoothAdapter"];

	if(config.find("baudrate")!= config.end())
	{
		baudrate = boost::lexical_cast<int>( config["baudrate"] );
	}

	if(config.find("device")!= config.end())
	{
		std::string dev = config["device"];

		if(dev.find(":") != string::npos)
		{
#ifdef USE_BLUEZ5
			bt = new Bluetooth5();
			bt->getDeviceForAddress(dev, [this](int fd) {
				DebugOut() << "fd: " << fd << endl;
				device = new SerialPort(fd);
				int baudrate=0;

				if(baudrate!=0)
				{
					if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
						DebugOut(DebugOut::Error)<<"Unsupported baudrate " << configuration["baudrate"] << endl;
				}

				DebugOut()<<"read from device: "<<device->read()<<endl;

				GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
				g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR),(GIOFunc)readCallback, this);
				g_io_channel_set_close_on_unref(chan, true);
				g_io_channel_unref(chan);
			});
#else
			bt = new BluetoothDevice();
			dev = bt->getDeviceForAddress(dev, btaddapter);

			device = new SerialPort(dev);

			if(baudrate!=0)
			{
				if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
					DebugOut(DebugOut::Error)<<"Unsupported baudrate " << config["baudrate"] << endl;
			}

			if(!device->open())
			{
				DebugOut(DebugOut::Error)<<"Failed to open gps tty: "<<config["device"]<<endl;
				perror("Error");
				return;
			}

			DebugOut()<<"read from device: "<<device->read()<<endl;

			GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
			g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR),(GIOFunc)readCallback, this);
			g_io_channel_set_close_on_unref(chan, true);
			g_io_channel_unref(chan);
#endif
		}
		else
		{
			device = new SerialPort(dev);

			if(baudrate!=0)
			{
				if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
					DebugOut(DebugOut::Error)<<"Unsupported baudrate " << config["baudrate"] << endl;
			}

			if(!device->open())
			{
				DebugOut(DebugOut::Error) << "Failed to open gps tty: " << config["device"] << endl;
				perror("Error");
				return;
			}

			DebugOut()<<"read from device: "<<device->read()<<endl;

			GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
			g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR), (GIOFunc)readCallback, this);
			g_io_channel_set_close_on_unref(chan, true);
			g_io_channel_unref(chan);
		}
	}
}

GpsNmeaSource::~GpsNmeaSource()
{
	if(device && device->isOpen())
		device->close();
	if(bt)
		delete bt;
}

const string GpsNmeaSource::uuid() const
{
	return mUuid;
}

int GpsNmeaSource::supportedOperations() const
{
	return AbstractSource::Get;
}

void GpsNmeaSource::init()
{
	if(configuration.find("test") != configuration.end())
	{
		test();
	}

	routingEngine->subscribeToProperty(DBusConnected,[this](AbstractPropertyType* value)
	{
		if(value->name == DBusConnected)
		{
			if(value->value<bool>())
			{
				amb::Exporter::instance()->exportProperty<GpsInfo>(routingEngine);
			}
		}
	});
}

void GpsNmeaSource::canHasData()
{
	std::string data = device->read();

	tryParse(data);
}

void GpsNmeaSource::test()
{
	location->parse("GPRMC,061211,A,2351.9605,S,15112.5239,E,000.0,053.4,170303,009.9,E*6E");

	DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
	DebugOut(0)<<"lat: "<<location->gpsTime()->toString()<<endl;

	g_assert(location->latitude()->toString() == "-23.86600833");
	g_assert(location->gpsTime()->toString() == "1050585131");

	location->parse("GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47");

	DebugOut(0)<<"alt: "<<location->altitude()->toString()<<endl;
	DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
	g_assert(location->altitude()->toString() == "545.4");
	g_assert(location->latitude()->toString() == "48.1173");

	location->parse("GPRMC,060136.00,A,3101.40475,N,12126.87095,E,0.760,,160114,,,A*74");
	DebugOut(0)<<"lon: "<<location->longitude()->toString()<<endl;
	DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;

	///test gpgsa
	location->parse("GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39");

	//Test incomplete message:
	location->parse("GPRMC,023633.00,V,,,,,,,180314,,,N*75");
	DebugOut(0)<<"lon: "<<location->longitude()->toString()<<endl;
	DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;

	std::string testChecksuming = "GPRMC,195617.00,V,,,,,,,310314,,,N*74";

	g_assert(checksum(testChecksuming));

	std::string multimessage1 = "GA,235320.00,4532.48633,N,12257.";
	std::string multimessage2 = "57383,W,";
	std::string multimessage3 = "1,03,7.53,51.6,M,-21.3,M,,*55";
	std::string multimessage4 = "GPGSA,A,";
	std::string multimessage5 = "2,27,23,19,,,,,,,,,,7.60";
	std::string multimessage6 = ",7.53,1.00*";
	std::string multimessage7 = "0E";

	bool multimessageParse = false;

	multimessageParse |= tryParse(multimessage1);
	multimessageParse |= tryParse(multimessage2);
	multimessageParse |= tryParse(multimessage3);
	multimessageParse |= tryParse(multimessage4);
	multimessageParse |= tryParse(multimessage5);
	multimessageParse |= tryParse(multimessage6);
	multimessageParse |= tryParse(multimessage7);

	g_assert(multimessageParse);

	//Test meaningingless message:
	location->parse("GPRMC,,V,,,,,,,,,,N*53");

	//test false message:

	g_assert(!checksum("GPRMC,172758.296,V"));
}

bool GpsNmeaSource::tryParse(string data)
{
	std::vector<std::string> lines;

	boost::split(lines, data, boost::is_any_of("$"));

	bool weFoundAMessage = false;

	for(auto line : lines)
	{
		if(checksum(line))
		{
			buffer = line;
		}
		else
		{
			buffer += line;
		}

		std::string::size_type pos = buffer.find('G');

		if(pos != std::string::npos && pos != 0)
		{
			///Throw the incomplete stuff away.  if it doesn't begin with "G" it'll never be complete
			buffer = buffer.substr(pos);
		}

		if(checksum(buffer))
		{
			/// we have a complete message.  parse it!
			DebugOut(7)<<"Complete message: "<<buffer<<endl;
			location->parse(buffer);
			boost::algorithm::erase_all(buffer, "\n");
			boost::algorithm::erase_all(buffer, "\r");
			setValue(rawNmea, buffer);
			weFoundAMessage = true;
			buffer = "";
		}
		else
		{
			if(pos == 0 )
			{
				std::string::size_type cs = buffer.find('*');
				if (cs != std::string::npos && cs != buffer.length()-1)
				{
					buffer = buffer.substr(cs+(buffer.length() - cs));
				}
			}
		}

		DebugOut(7)<<"buffer: "<<buffer<<endl;
	}

	return weFoundAMessage;
}

bool GpsNmeaSource::checksum(std::string sentence)
{
	if(sentence.empty() || sentence.length() < 4 || sentence.find("*") == string::npos || sentence.find("*") >= sentence.length()-2)
	{
		return false;
	}

	int checksum = 0;

	for(auto i : sentence)
	{
		if(i == '*')
			break;
		if(i != '\n' || i != '\r')
			checksum ^= i;
	}

	std::string sentenceCheckStr = sentence.substr(sentence.find('*')+1,2);

	try
	{
		int sentenceCheck = lexical_cast<int>(sentenceCheckStr);

		return sentenceCheck == checksum;
	}
	catch(...)

	{
		return false;
	}

	return false;
}