2 Copyright (C) 2012 Intel Corporation
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 #include "timestamp.h"
21 #include "serialport.hpp"
22 #include "bluetooth.hpp"
23 #include "bluetooth5.h"
24 #include <listplusplus.h>
25 #include <superptr.hpp>
26 #include <ambplugin.h>
28 #include <dbusplugin.h>
29 #include <dbusexport.h>
32 #include <boost/assert.hpp>
33 #include <boost/algorithm/string.hpp>
40 #include "abstractpropertytype.h"
42 #define GPSTIME "GpsTime"
43 #define GPSSPEED "GpsSpeed"
44 #define GpsFix "GpsFix"
45 #define GpsSatsUsed "GpsSatsUsed"
46 #define GpsNmea "GpsNmea"
49 inline T2 lexical_cast(const std::string &in) {
57 class GpsInfo: public DBusSink
60 GpsInfo(VehicleProperty::Property, AbstractRoutingEngine* re, GDBusConnection* connection)
61 :DBusSink("GpsInfo", re, connection, map<string, string>())
63 wantPropertyVariant(GPSTIME, "GpsTime", VariantType::Read);
64 wantPropertyVariant(GPSSPEED, "Speed", VariantType::Read);
65 wantPropertyVariant(GpsFix, "Fix", VariantType::Read);
66 wantPropertyVariant(GpsSatsUsed, "SattelitesUsed", VariantType::Read);
67 wantPropertyVariant(GpsNmea, "RawNmea", VariantType::Read);
80 Location(AmbPluginImpl *source, std::shared_ptr<AbstractPropertyType> lat,
81 std::shared_ptr<AbstractPropertyType> lon,
82 std::shared_ptr<AbstractPropertyType> alt,
83 std::shared_ptr<AbstractPropertyType> dir,
84 std::shared_ptr<AbstractPropertyType> spd,
85 std::shared_ptr<AbstractPropertyType> time,
86 std::shared_ptr<AbstractPropertyType> fix,
87 std::shared_ptr<AbstractPropertyType> satsUsed);
89 void parse(std::string gprmc);
91 AbstractPropertyType * latitude()
93 return mLatitude.get();
96 AbstractPropertyType * longitude()
98 return mLongitude.get();
101 AbstractPropertyType * altitude()
103 return mAltitude.get();
106 AbstractPropertyType * direction()
108 return mDirection.get();
111 AbstractPropertyType * speed()
116 AbstractPropertyType * gpsTime()
118 return mGpsTime.get();
121 std::list<AbstractPropertyType*> fix()
123 std::list<AbstractPropertyType*> l;
125 l.push_back(mLatitude.get());
126 l.push_back(mLongitude.get());
127 l.push_back(mAltitude.get());
128 l.push_back(mDirection.get());
129 l.push_back(mSpeed.get());
130 l.push_back(mGpsTime.get());
137 void parseGprmc(string gprmc);
138 void parseGpgga(string gpgga);
139 void parseGpgsa(string gpgsa);
141 void parseTime(std::string h, std::string m, std::string s, string dd, string mm, string yy);
142 void parseLatitude(std::string d, std::string m, std::string ns);
143 void parseLongitude(std::string d, string m, string ew);
144 void parseSpeed(std::string spd);
145 void parseDirection(std::string dir);
146 void parseAltitude(std::string alt);
148 double degsToDecimal(double degs);
152 std::shared_ptr<AbstractPropertyType> mLatitude;
153 std::shared_ptr<AbstractPropertyType> mLongitude;
154 std::shared_ptr<AbstractPropertyType> mAltitude;
155 std::shared_ptr<AbstractPropertyType> mDirection;
156 std::shared_ptr<AbstractPropertyType> mSpeed;
157 std::shared_ptr<AbstractPropertyType> mGpsTime;
158 std::shared_ptr<AbstractPropertyType> mFix;
159 std::shared_ptr<AbstractPropertyType> mSatelitesUsed;
163 AmbPluginImpl * parent;
167 Location::Location(AmbPluginImpl* source,
168 std::shared_ptr<AbstractPropertyType> lat,
169 std::shared_ptr<AbstractPropertyType> lon,
170 std::shared_ptr<AbstractPropertyType> alt,
171 std::shared_ptr<AbstractPropertyType> dir,
172 std::shared_ptr<AbstractPropertyType> spd,
173 std::shared_ptr<AbstractPropertyType> time,
174 std::shared_ptr<AbstractPropertyType> fix,
175 std::shared_ptr<AbstractPropertyType> satsUsed)
176 :parent(source), isActive(false)
185 mSatelitesUsed = satsUsed;
188 void Location::parse(string nmea)
190 if(boost::algorithm::starts_with(nmea,"GPRMC"))
194 else if(boost::algorithm::starts_with(nmea,"GPGGA"))
198 else if(boost::algorithm::starts_with(nmea, "GPGSA"))
204 DebugOut(7)<<"unknown/unhandled message: "<<nmea<<endl;
208 void Location::parseGprmc(string gprmc)
210 DebugOut(7)<<"parsing gprmc message"<<endl;
212 std::vector<std::string> tokens;
213 boost::split(tokens, gprmc, boost::is_any_of(","));
225 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())
230 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));
232 parseLatitude(tokens[3], "", tokens[4]);
233 parseLongitude(tokens[5], "", tokens[6]);
234 parseSpeed(tokens[7]);
235 parseDirection(tokens[8]);
239 void Location::parseGpgga(string gpgga)
242 std::vector<std::string> tokens;
243 boost::split(tokens, gpgga, boost::is_any_of(","));
245 if(tokens.size() != 15)
247 DebugOut()<<"Invalid GPGGA message: "<<gpgga<<endl;
251 parseLatitude(tokens[2],"",tokens[3]);
252 parseLongitude(tokens[4],"",tokens[5]);
257 else isActive = false;
259 parseAltitude(tokens[9]);
262 void Location::parseGpgsa(string gpgsa)
264 std::vector<std::string> tokens;
265 boost::split(tokens, gpgsa, boost::is_any_of(","));
267 if(tokens.size() != 18)
269 DebugOut()<<"Invalid GPGSA message: "<<gpgsa<<endl;
273 Location::FixType fix = (Location::FixType)boost::lexical_cast<int>(tokens[2]);
275 uint16_t numsats = 0;
277 for(int i=3; i<15; i++)
279 std::string sat = tokens[i];
286 if(mFix->value<Location::FixType>() != fix)
287 parent->setValue(mFix, fix);
289 if(mSatelitesUsed->value<uint16_t>() != numsats)
290 parent->setValue(mSatelitesUsed, numsats);
293 void Location::parseTime(string h, string m, string s, string dd, string mm, string yy)
298 t.tm_hour = boost::lexical_cast<int>(h);
299 t.tm_min = boost::lexical_cast<int>(m);
300 t.tm_sec = boost::lexical_cast<int>(s);
301 t.tm_mday = boost::lexical_cast<int>(dd);
302 t.tm_mon = boost::lexical_cast<int>(mm);
303 t.tm_year = boost::lexical_cast<int>(yy) + 100;
305 time_t time = mktime(&t);
307 if(mGpsTime->value<double>() != (double(time)))
309 parent->setValue(mGpsTime, double(time));
314 DebugOut(5)<<"Failed to parse time "<<endl;
318 void Location::parseLatitude(string d, string m, string ns)
325 double degs = boost::lexical_cast<double>(d + m);
326 double dec = degsToDecimal(degs);
331 if(mLatitude->value<double>() != dec)
333 parent->setValue(mLatitude, dec);
338 DebugOut(5)<<"Failed to parse latitude"<<endl;
342 void Location::parseLongitude(string d, string m, string ew)
346 if(d.empty()) return;
348 double degs = boost::lexical_cast<double>(d + m);
349 double dec = degsToDecimal(degs);
354 if(mLongitude->value<double>() != dec)
356 parent->setValue(mLongitude, dec);
361 DebugOut(5)<<"failed to parse longitude: "<<d<<" "<<m<<" "<<ew<<endl;
365 void Location::parseSpeed(string spd)
369 double s = boost::lexical_cast<double>(spd);
374 uint16_t speed = static_cast<uint16_t>(s);
376 if(mSpeed->value<uint16_t>() != speed)
378 parent->setValue(mSpeed, speed);
383 DebugOut(5)<<"failed to parse speed"<<endl;
387 void Location::parseDirection(string dir)
390 uint16_t d = boost::lexical_cast<double>(dir);
392 if(mDirection->value<uint16_t>() != d)
394 parent->setValue(mDirection, d);
399 DebugOut(5)<<"Failed to parse direction: "<<dir<<endl;
403 void Location::parseAltitude(string alt)
407 if(alt.empty()) return;
409 double a = boost::lexical_cast<double>(alt);
411 if(mAltitude->value<double>() != a)
413 parent->setValue(mAltitude, a);
418 DebugOut(5)<<"failed to parse altitude"<<endl;
422 double Location::degsToDecimal(double degs)
425 double min = 100.0 * modf(degs / 100.0, °);
426 return deg + (min / 60.0);
429 bool readCallback(GIOChannel *source, GIOCondition condition, gpointer data)
431 // DebugOut(5) << "Polling..." << condition << endl;
433 if(condition & G_IO_ERR)
435 DebugOut(DebugOut::Error)<<"GpsNmeaSource polling error."<<endl;
438 if (condition & G_IO_HUP)
440 //Hang up. Returning false closes out the GIOChannel.
441 //printf("Callback on G_IO_HUP\n");
442 DebugOut(DebugOut::Warning)<<"socket hangup event..."<<endl;
446 GpsNmeaSource* src = static_cast<GpsNmeaSource*>(data);
453 extern "C" void create(AbstractRoutingEngine* routingengine, map<string, string> config)
455 auto plugin = new AmbPlugin<GpsNmeaSource>(routingengine, config);
459 GpsNmeaSource::GpsNmeaSource(AbstractRoutingEngine *re, map<string, string> config, AbstractSource &parent)
460 :AmbPluginImpl(re, config, parent), mUuid("33d86462-1708-4f78-a001-99ea8d55422b"), device(nullptr), bt(nullptr)
464 auto lat = addPropertySupport<VehicleProperty::LatitudeType>(Zone::None);
465 auto lon = addPropertySupport<VehicleProperty::LongitudeType>(Zone::None);
466 auto alt = addPropertySupport<VehicleProperty::AltitudeType>(Zone::None);
467 auto spd = addPropertySupport(Zone::None, [](){ return new BasicPropertyType<uint16_t>(GPSSPEED, 0); });
468 auto dir = addPropertySupport<VehicleProperty::DirectionType>(Zone::None);
469 auto time = addPropertySupport(Zone::None, [](){ return new BasicPropertyType<double>(GPSTIME, 0); });
470 auto fix = addPropertySupport(Zone::None, []() { return new BasicPropertyType<Location::FixType>(GpsFix, Location::NoFix); });
471 auto satsUsed = addPropertySupport(Zone::None, []() { return new BasicPropertyType<uint16_t>(GpsSatsUsed, 0); });
472 rawNmea = addPropertySupport(Zone::None, []() { return new StringPropertyType(GpsNmea); });
474 location = new Location(this, lat, lon, alt, dir, spd, time, fix, satsUsed);
476 std::string btaddapter = config["bluetoothAdapter"];
478 if(config.find("baudrate")!= config.end())
480 baudrate = boost::lexical_cast<int>( config["baudrate"] );
483 if(config.find("device")!= config.end())
485 std::string dev = config["device"];
487 if(dev.find(":") != string::npos)
490 bt = new Bluetooth5();
491 bt->getDeviceForAddress(dev, [this](int fd) {
492 DebugOut() << "fd: " << fd << endl;
493 device = new SerialPort(fd);
498 if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
499 DebugOut(DebugOut::Error)<<"Unsupported baudrate " << configuration["baudrate"] << endl;
502 DebugOut()<<"read from device: "<<device->read()<<endl;
504 GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
505 g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR),(GIOFunc)readCallback, this);
506 g_io_channel_set_close_on_unref(chan, true);
507 g_io_channel_unref(chan);
510 bt = new BluetoothDevice();
511 dev = bt->getDeviceForAddress(dev, btaddapter);
513 device = new SerialPort(dev);
517 if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
518 DebugOut(DebugOut::Error)<<"Unsupported baudrate " << config["baudrate"] << endl;
523 DebugOut(DebugOut::Error)<<"Failed to open gps tty: "<<config["device"]<<endl;
528 DebugOut()<<"read from device: "<<device->read()<<endl;
530 GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
531 g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR),(GIOFunc)readCallback, this);
532 g_io_channel_set_close_on_unref(chan, true);
533 g_io_channel_unref(chan);
538 device = new SerialPort(dev);
542 if((static_cast<SerialPort*>(device))->setSpeed(baudrate))
543 DebugOut(DebugOut::Error)<<"Unsupported baudrate " << config["baudrate"] << endl;
548 DebugOut(DebugOut::Error) << "Failed to open gps tty: " << config["device"] << endl;
553 DebugOut()<<"read from device: "<<device->read()<<endl;
555 GIOChannel *chan = g_io_channel_unix_new(device->fileDescriptor());
556 g_io_add_watch(chan, GIOCondition(G_IO_IN | G_IO_HUP | G_IO_ERR), (GIOFunc)readCallback, this);
557 g_io_channel_set_close_on_unref(chan, true);
558 g_io_channel_unref(chan);
563 GpsNmeaSource::~GpsNmeaSource()
565 if(device && device->isOpen())
571 const string GpsNmeaSource::uuid() const
576 int GpsNmeaSource::supportedOperations() const
578 return AbstractSource::Get;
581 void GpsNmeaSource::init()
583 if(configuration.find("test") != configuration.end())
588 routingEngine->subscribeToProperty(DBusConnected,[this](AbstractPropertyType* value)
590 if(value->name == DBusConnected)
592 if(value->value<bool>())
594 amb::Exporter::instance()->exportProperty<GpsInfo>(routingEngine);
600 void GpsNmeaSource::canHasData()
602 std::string data = device->read();
607 void GpsNmeaSource::test()
609 location->parse("GPRMC,061211,A,2351.9605,S,15112.5239,E,000.0,053.4,170303,009.9,E*6E");
611 DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
612 DebugOut(0)<<"lat: "<<location->gpsTime()->toString()<<endl;
614 g_assert(location->latitude()->toString() == "-23.86600833");
615 g_assert(location->gpsTime()->toString() == "1050585131");
617 location->parse("GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47");
619 DebugOut(0)<<"alt: "<<location->altitude()->toString()<<endl;
620 DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
621 g_assert(location->altitude()->toString() == "545.4");
622 g_assert(location->latitude()->toString() == "48.1173");
624 location->parse("GPRMC,060136.00,A,3101.40475,N,12126.87095,E,0.760,,160114,,,A*74");
625 DebugOut(0)<<"lon: "<<location->longitude()->toString()<<endl;
626 DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
629 location->parse("GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39");
631 //Test incomplete message:
632 location->parse("GPRMC,023633.00,V,,,,,,,180314,,,N*75");
633 DebugOut(0)<<"lon: "<<location->longitude()->toString()<<endl;
634 DebugOut(0)<<"lat: "<<location->latitude()->toString()<<endl;
636 std::string testChecksuming = "GPRMC,195617.00,V,,,,,,,310314,,,N*74";
638 g_assert(checksum(testChecksuming));
640 std::string multimessage1 = "GA,235320.00,4532.48633,N,12257.";
641 std::string multimessage2 = "57383,W,";
642 std::string multimessage3 = "1,03,7.53,51.6,M,-21.3,M,,*55";
643 std::string multimessage4 = "GPGSA,A,";
644 std::string multimessage5 = "2,27,23,19,,,,,,,,,,7.60";
645 std::string multimessage6 = ",7.53,1.00*";
646 std::string multimessage7 = "0E";
648 bool multimessageParse = false;
650 multimessageParse |= tryParse(multimessage1);
651 multimessageParse |= tryParse(multimessage2);
652 multimessageParse |= tryParse(multimessage3);
653 multimessageParse |= tryParse(multimessage4);
654 multimessageParse |= tryParse(multimessage5);
655 multimessageParse |= tryParse(multimessage6);
656 multimessageParse |= tryParse(multimessage7);
658 g_assert(multimessageParse);
660 //Test meaningingless message:
661 location->parse("GPRMC,,V,,,,,,,,,,N*53");
663 //test false message:
665 g_assert(!checksum("GPRMC,172758.296,V"));
668 bool GpsNmeaSource::tryParse(string data)
670 std::vector<std::string> lines;
672 boost::split(lines, data, boost::is_any_of("$"));
674 bool weFoundAMessage = false;
676 for(auto line : lines)
687 std::string::size_type pos = buffer.find('G');
689 if(pos != std::string::npos && pos != 0)
691 ///Throw the incomplete stuff away. if it doesn't begin with "G" it'll never be complete
692 buffer = buffer.substr(pos);
697 /// we have a complete message. parse it!
698 DebugOut(7)<<"Complete message: "<<buffer<<endl;
699 location->parse(buffer);
700 boost::algorithm::erase_all(buffer, "\n");
701 boost::algorithm::erase_all(buffer, "\r");
702 setValue(rawNmea, buffer);
703 weFoundAMessage = true;
710 std::string::size_type cs = buffer.find('*');
711 if (cs != std::string::npos && cs != buffer.length()-1)
713 buffer = buffer.substr(cs+(buffer.length() - cs));
718 DebugOut(7)<<"buffer: "<<buffer<<endl;
721 return weFoundAMessage;
724 bool GpsNmeaSource::checksum(std::string sentence)
726 if(sentence.empty() || sentence.length() < 4 || sentence.find("*") == string::npos || sentence.find("*") >= sentence.length()-2)
733 for(auto i : sentence)
737 if(i != '\n' || i != '\r')
741 std::string sentenceCheckStr = sentence.substr(sentence.find('*')+1,2);
745 int sentenceCheck = lexical_cast<int>(sentenceCheckStr);
747 return sentenceCheck == checksum;