summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: ed98cb4659d46453b75fd626c7d3e7256cb9d9f6 (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
// 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_time& time, const minmea_date& date)
{
	tm tm_utc{};
	::minmea_getdatetime(&tm_utc, &date, &time);

	auto timestamp = ::timegm(&tm_utc);

	tm tm_local{};
	(void) ::localtime_r(&timestamp, &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;
			}

			auto timestamp = get_gps_datetime(frame.time, frame.date);

			cout << format("{}: $RMC floating point degree coordinates and speed: ({},{}) {} km/h\n",
			               timestamp,
			               ::minmea_tocoord(&frame.latitude),
			               ::minmea_tocoord(&frame.longitude),
			               ::minmea_tofloat(&frame.speed) * KNOTS_TO_KMH);
		}
	}
	catch ( exception& e ) {
		cerr << "io-error: " << e.what() << '\n';
	}
}