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
|
// Standard C++
#include <array>
#include <ctime>
#include <exception>
#include <format>
#include <iostream>
#include <string>
// Asio
#include <asio.hpp>
// minmea
#include "minmea.h"
using namespace std;
constexpr auto PORT = "/dev/cuaU0";
constexpr auto BAUDRATE = 9600;
constexpr auto KNOTS_TO_KMH = 1.852F;
namespace {
auto
read_line(asio::serial_port& com)
{
for ( string result;; ) {
char chr = 0;
asio::read(com, asio::buffer(&chr, 1));
switch ( chr ) {
case '\r':
break;
case '\n':
return result;
default:
result += chr;
}
}
}
string
get_gps_datetime(const minmea_date& date, const minmea_time& time)
{
tm tm_utc{};
::minmea_getdatetime(&tm_utc, &date, &time);
auto timestamp = ::timegm(&tm_utc);
tm tm_local{};
(void) ::localtime_r(×tamp, &tm_local);
static const auto buffer_size = 100;
array<char, buffer_size> buffer{};
(void) ::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", &tm_local);
return buffer.data();
}
} // namespace
int
main()
{
try {
asio::io_context io_context{};
asio::serial_port com(io_context, PORT);
com.set_option(asio::serial_port::baud_rate(BAUDRATE));
for ( ;; ) {
const auto line = read_line(com);
const auto nmea_id = ::minmea_sentence_id(line.c_str(), true);
if ( nmea_id != MINMEA_SENTENCE_RMC ) {
continue;
}
minmea_sentence_rmc frame{};
if ( !::minmea_parse_rmc(&frame, line.c_str()) || !frame.valid ) {
continue;
}
const auto latitude = ::minmea_tocoord(&frame.latitude);
const auto longitude = ::minmea_tocoord(&frame.longitude);
const auto speed = ::minmea_tofloat(&frame.speed) * KNOTS_TO_KMH;
const auto timestamp = get_gps_datetime(frame.date, frame.time);
cout << format("{}: $RMC floating point degree coordinates and speed: ({},{}) {} km/h\n",
timestamp,
latitude,
longitude,
speed);
}
}
catch ( exception& e ) {
cerr << "io-error: " << e.what() << '\n';
}
}
|