Debian Codegraph @

src/libais/ais.cpp

raw symbols SCIP
1 // General helper functions for working with AIS and NMEA.
2
3 #include "ais.h"
4
5 extern "C" {
6 int LibAisVersionMajor() {
7 return LIBAIS_VERSION_MAJOR;
8 }
9
10 int LibAisVersionMinor() {
11 return LIBAIS_VERSION_MINOR;
12 }
13 } // extern "C"
14
15 namespace libais {
16
17 string GetNthField(const string &str, const size_t n,
18 const string &delim_str) {
19 assert(!delim_str.empty());
20 if (str.empty())
21 return "";
22
23 size_t prev = 0;
24 size_t off = str.find(delim_str);
25 size_t count = 0;
26
27 for (; off != string::npos && count != n;
28 off = str.find(delim_str, off + 1), count++) {
29 prev = off + delim_str.size();
30 }
31
32 if (count == n)
33 return str.substr(prev, off-prev);
34
35 return "";
36 }
37
38 int GetPad(const string &nmea_str) {
39 // -1 on error
40 const string chksum_block(GetNthField(nmea_str, 6, ","));
41 if (chksum_block.size() != 4 || chksum_block[1] != '*')
42 return -1;
43 const char pad = chksum_block[0];
44 if (pad < '0' || pad > '5')
45 return -1;
46 return static_cast<int>(pad - '0');
47 }
48
49 string GetBody(const string &nmea_str) {
50 return GetNthField(nmea_str, 5, ",");
51 }
52
53 // Note: Needs to be kept in sync with enum AIS_STATUS list in ais.h.
54 const char * const AIS_STATUS_STRINGS[AIS_STATUS_NUM_CODES] = {
55 "AIS_UNINITIALIZED",
56 "AIS_OK",
57 "AIS_ERR_BAD_BIT_COUNT",
58 "AIS_ERR_BAD_NMEA_CHR",
59 "AIS_ERR_BAD_PTR",
60 "AIS_ERR_UNKNOWN_MSG_TYPE",
61 "AIS_ERR_MSG_NOT_IMPLEMENTED",
62 "AIS_ERR_MSG_SUB_NOT_IMPLEMENTED",
63 "AIS_ERR_EXPECTED_STRING",
64 "AIS_ERR_BAD_MSG_CONTENT",
65 "AIS_ERR_MSG_TOO_LONG",
66 "AIS_ERR_BAD_SUB_MSG",
67 "AIS_ERR_BAD_SUB_SUB_MSG",
68 };
69
70 AisMsg::AisMsg(const char *nmea_payload, const size_t pad)
71 : message_id(0), repeat_indicator(0), mmsi(0), status(AIS_UNINITIALIZED),
72 num_chars(0), num_bits(0), bits() {
73 assert(nmea_payload);
74 assert(pad < 6);
75
76 const AIS_STATUS r = bits.ParseNmeaPayload(nmea_payload, pad);
77 if (r != AIS_OK) {
78 status = r;
79 return;
80 }
81 num_bits = bits.GetNumBits();
82 num_chars = bits.GetNumChars();
83
84 if (bits.GetNumBits() < 38) {
85 status = AIS_ERR_BAD_BIT_COUNT;
86 return;
87 }
88
89 message_id = bits.ToUnsignedInt(0, 6);
90 repeat_indicator = bits.ToUnsignedInt(6, 2);
91 mmsi = bits.ToUnsignedInt(8, 30);
92 }
93
94 bool AisMsg::CheckStatus() const {
95 if (status == AIS_OK || status == AIS_UNINITIALIZED) {
96 return true;
97 }
98 #ifdef LIBAIS_DEBUG
99 std::cerr << "AisMsg::CheckStatus failed: "
100 << AIS_STATUS_STRINGS[status]
101 << std::endl;
102 #endif
103 return false;
104 }
105
106 AisPoint::AisPoint() : lng_deg(0), lat_deg(0) {
107 }
108
109 AisPoint::AisPoint(double lng_deg_, double lat_deg_)
110 : lng_deg(lng_deg_), lat_deg(lat_deg_) {
111 }
112
113 ostream& operator<< (ostream &o, const AisPoint &position) {
114 return o << " (" << position.lng_deg << ", " << position.lat_deg << ")";
115 }
116
117 } // namespace libais