Dev: consistent formatting with clang-format-3.9
[marnav.git] / src / marnav / io / nmea_reader.cpp
blob3e2ccf28c2e75b07d82d4ff0e2ac050c789cbb1e
1 #include "nmea_reader.hpp"
2 #include <algorithm>
3 #include <marnav/utils/unique.hpp>
5 namespace marnav
7 namespace io
9 nmea_reader::~nmea_reader()
13 /// Initializes the reader, opens the device (if valid).
14 ///
15 /// @param[in] d The device to read data from, will be opened.
16 nmea_reader::nmea_reader(std::unique_ptr<device> && d)
17 : raw(0)
18 , dev(std::move(d))
20 sentence.reserve(nmea::sentence::max_length + 1);
21 if (dev)
22 dev->open();
25 void nmea_reader::close()
27 if (dev)
28 dev->close();
29 dev.reset();
32 /// Reads data from the device.
33 ///
34 /// @retval true Success.
35 /// @retval false End of file.
36 /// @exception std::runtime_error The device was invalid or read error.
37 bool nmea_reader::read_data()
39 if (!dev)
40 throw std::runtime_error{"device invalid"};
41 int rc = dev->read(&raw, sizeof(raw));
42 if (rc == 0)
43 return false;
44 if (rc < 0)
45 throw std::runtime_error{"read error"};
46 if (rc != sizeof(raw))
47 throw std::runtime_error{"read error"};
48 return true;
51 /// Processes the data read from the device.
52 ///
53 /// @exception std::length_error Too many characters read for the sentence.
54 /// Maybe the end of line was missed or left out.
55 void nmea_reader::process_nmea()
57 switch (raw) {
58 case '\r':
59 break;
60 case '\n': // end of sentence
61 process_sentence(sentence);
62 sentence.clear();
63 break;
64 default:
65 // ignore invalid characters. if this makes the sentence incomplete,
66 // the sentence would have been invalid anyway. the result will be
67 // an invalid sentence or a std::length_error.
68 if ((raw <= 32) || (raw >= 127))
69 return;
71 if (sentence.size() > nmea::sentence::max_length)
72 throw std::length_error{"sentence size to large. receiving NMEA data?"};
73 sentence += raw;
74 break;
78 /// Reads data from the device and processes it. If a complete NMEA
79 /// sentence was received the method process_message will be executed.
80 /// This method automatcially synchronizes with NMEA data.
81 ///
82 /// @retval true Success.
83 /// @retval false End of file.
84 /// @exception std::runtime_error Device or processing error.
85 /// @exception std::length_error Synchronization issue.
86 bool nmea_reader::read()
88 if (!read_data())
89 return false;
90 process_nmea();
91 return true;