ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
nmea.cpp
Go to the documentation of this file.
1#include "nmea.h"
3#include "esphome/core/log.h"
4#include "esphome/core/time.h"
5
6#include <cstring>
7#include <limits>
8
9namespace esphome::gps {
10
11ESPHOME_LOG_TAG(TAG, "gps.nmea");
12
13static constexpr size_t MAX_FIELDS = 20;
14static constexpr int32_t E7 = 10000000;
15
16namespace {
17
18class Fields {
19 public:
21 explicit Fields(char *line) {
22 this->fields_[0] = line;
23 for (char *p = line; *p != '\0' && this->count_ < MAX_FIELDS; p++) {
24 if (*p == ',') {
25 *p = '\0';
26 this->fields_[this->count_++] = p + 1;
27 }
28 }
29 }
31 const char *operator[](size_t i) const { return i < this->count_ ? this->fields_[i] : ""; }
32
33 protected:
34 const char *fields_[MAX_FIELDS];
35 size_t count_{1};
36};
37
38bool is_digit(char c) { return c >= '0' && c <= '9'; }
39
40bool all_digits(const char *s) {
41 for (; *s != '\0'; s++) {
42 if (!is_digit(*s))
43 return false;
44 }
45 return true;
46}
47
49bool parse_decimal(const char *s, uint8_t decimals, int32_t &out) {
50 const bool integer = decimals == 0;
51 const bool negative = *s == '-';
52 if (negative)
53 s++;
54 uint32_t value = 0;
55 bool any_digit = false;
56 bool fraction = false;
57 for (; *s != '\0'; s++) {
58 if (*s == '.' && !fraction && !integer) {
59 fraction = true;
60 continue;
61 }
62 if (!is_digit(*s))
63 return false;
64 if (fraction) {
65 if (decimals == 0)
66 continue;
67 decimals--;
68 }
69 if (value > (INT32_MAX - 9) / 10)
70 return false;
71 value = value * 10 + (*s - '0');
72 any_digit = true;
73 }
74 if (!any_digit)
75 return false;
76 for (; decimals > 0; decimals--) {
77 if (value > INT32_MAX / 10)
78 return false;
79 value *= 10;
80 }
81 out = negative ? -static_cast<int32_t>(value) : static_cast<int32_t>(value);
82 return true;
83}
84
85template<typename T> bool parse_unsigned(const char *s, uint8_t decimals, T &out) {
86 int32_t value;
87 if (!parse_decimal(s, decimals, value) || value < 0 || static_cast<uint32_t>(value) > std::numeric_limits<T>::max())
88 return false;
89 out = static_cast<T>(value);
90 return true;
91}
92
93bool parse_two_digits(const char *s, uint8_t max, uint8_t &out) {
94 if (!is_digit(s[0]) || !is_digit(s[1]))
95 return false;
96 out = (s[0] - '0') * 10 + (s[1] - '0');
97 return out <= max;
98}
99
101bool parse_coordinate(const char *s, const char *hemisphere, char positive, char negative, int32_t max_degrees,
102 int32_t &out) {
103 const char *dot = strchr(s, '.');
104 const size_t int_len = dot != nullptr ? dot - s : strlen(s);
105 if (int_len < 3 || int_len > 5)
106 return false;
107 int32_t degrees = 0;
108 for (size_t i = 0; i != int_len; i++) {
109 if (!is_digit(s[i]))
110 return false;
111 if (i < int_len - 2)
112 degrees = degrees * 10 + (s[i] - '0');
113 }
114 int32_t minutes_e7;
115 if (degrees > max_degrees || !parse_decimal(s + int_len - 2, 7, minutes_e7) || minutes_e7 >= 60 * E7)
116 return false;
117 const int32_t value = degrees * E7 + (minutes_e7 + 30) / 60;
118 if (value > max_degrees * E7 || strlen(hemisphere) != 1)
119 return false;
120 if (hemisphere[0] == positive) {
121 out = value;
122 } else if (hemisphere[0] == negative) {
123 out = -value;
124 } else {
125 return false;
126 }
127 return true;
128}
129
131bool parse_time(const char *s, GPSData &data) {
132 if (!parse_two_digits(s, 23, data.hour) || !parse_two_digits(s + 2, 59, data.minute) ||
133 !parse_two_digits(s + 4, 60, data.second))
134 return false;
135#ifdef USE_GPS_MILLISECOND
136 data.millisecond = 0;
137#endif
138 if (s[6] == '\0')
139 return true;
140 if (s[6] != '.' || s[7] == '\0' || !all_digits(s + 7))
141 return false;
142#ifdef USE_GPS_MILLISECOND
143 uint16_t scale = 100;
144 for (const char *p = s + 7; *p != '\0' && scale != 0; p++, scale /= 10)
145 data.millisecond += (*p - '0') * scale;
146#endif
147 return true;
148}
149
151bool parse_date(const char *s, GPSData &data) {
152 uint8_t year;
153 if (strlen(s) != 6 || !parse_two_digits(s, 31, data.day) || !parse_two_digits(s + 2, 12, data.month) ||
154 !parse_two_digits(s + 4, 99, year) || data.month == 0)
155 return false;
156 data.year = 2000 + year;
157 return data.day != 0 && data.day <= days_in_month(data.month, data.year);
158}
159
161bool parse_location(const Fields &f, size_t first, GPSData &data) {
162 if (*f[first] == '\0' && *f[first + 1] == '\0' && *f[first + 2] == '\0' && *f[first + 3] == '\0')
163 return true;
164 if (!parse_coordinate(f[first], f[first + 1], 'N', 'S', 90, data.latitude_e7) ||
165 !parse_coordinate(f[first + 2], f[first + 3], 'E', 'W', 180, data.longitude_e7))
166 return false;
167 data.updated |= GPS_FIELD_LOCATION;
168 return true;
169}
170
172template<typename P> bool parse_optional(const char *s, GPSField field, GPSData &data, P &&parse) {
173 if (*s == '\0')
174 return true;
175 if (!parse(s))
176 return false;
177 data.updated |= field;
178 return true;
179}
180
181// $--GGA,time,lat,N,lon,E,quality,satellites,hdop,altitude,M,geoid,M,age,station*hh
182bool parse_gga(const Fields &f, GPSData &data) {
183 uint8_t quality = 0;
184 if (*f[6] != '\0' && !parse_unsigned(f[6], 0, quality))
185 return false;
186 if (!parse_optional(f[7], GPS_FIELD_SATELLITES, data,
187 [&data](const char *s) { return parse_unsigned(s, 0, data.satellites); }) ||
188 !parse_optional(f[8], GPS_FIELD_HDOP, data,
189 [&data](const char *s) { return parse_unsigned(s, 2, data.hdop_e2); }))
190 return false;
191 // Without a fix the time can come from the receiver's own clock, which may be wrong
192 if (quality == 0)
193 return true;
194 if (!parse_optional(f[1], GPS_FIELD_TIME, data, [&data](const char *s) { return parse_time(s, data); }) ||
195 !parse_location(f, 2, data) || !parse_optional(f[9], GPS_FIELD_ALTITUDE, data, [&data](const char *s) {
196 return parse_decimal(s, 3, data.altitude_e3);
197 }))
198 return false;
199#ifdef USE_GPS_GEOID_SEPARATION
200 return parse_optional(f[11], GPS_FIELD_GEOID_SEPARATION, data,
201 [&data](const char *s) { return parse_decimal(s, 3, data.geoid_separation_e3); });
202#else
203 return true;
204#endif
205}
206
207// $--RMC,time,status,lat,N,lon,E,speed,course,date,variation,E[,mode[,nav status]]*hh
208bool parse_rmc(const Fields &f, GPSData &data) {
209 // Without a fix the time and date can come from the receiver's own clock, which may be wrong
210 if (*f[2] == '\0' || strcmp(f[2], "V") == 0)
211 return true;
212 if (strcmp(f[2], "A") != 0)
213 return false;
214 return parse_optional(f[1], GPS_FIELD_TIME, data, [&data](const char *s) { return parse_time(s, data); }) &&
215 parse_location(f, 3, data) &&
216 parse_optional(f[7], GPS_FIELD_SPEED, data,
217 [&data](const char *s) { return parse_unsigned(s, 3, data.speed_e3); }) &&
218 parse_optional(
219 f[8], GPS_FIELD_COURSE, data,
220 [&data](const char *s) { return parse_unsigned(s, 2, data.course_e2) && data.course_e2 <= 36000; }) &&
221 parse_optional(f[9], GPS_FIELD_DATE, data, [&data](const char *s) { return parse_date(s, data); });
222}
223
224} // namespace
225
226bool parse_nmea_sentence(char *line, size_t len, GPSData &data) {
227 // Noise before the sentence, NUL bytes included, is skipped
228 size_t pos = len;
229 while (pos != 0 && line[pos - 1] != '$')
230 pos--;
231 if (pos == 0 || strlen(line + pos - 1) != len - pos + 1)
232 return false;
233 char *start = line + pos - 1;
234 char *star = strchr(start, '*');
235 uint8_t checksum;
236 if (star == nullptr || strlen(star + 1) != 2 || !parse_hex(star + 1, &checksum, 1))
237 return false;
238 if (xor_bytes(reinterpret_cast<const uint8_t *>(start + 1), star - start - 1) != checksum) {
239 ESP_LOGV(TAG, "Bad checksum: %s", start);
240 return false;
241 }
242 *star = '\0';
243 const Fields fields(start + 1);
244 const char *address = fields[0];
245 // Two talker characters and the sentence type; proprietary sentences start with P
246 if (strlen(address) != 5 || address[0] == 'P')
247 return false;
248 const char *type = address + 2;
249 GPSData next = data;
250 next.updated = 0;
251 bool ok;
252 if (strcmp(type, "GGA") == 0) {
253 ok = parse_gga(fields, next);
254 } else if (strcmp(type, "RMC") == 0) {
255 ok = parse_rmc(fields, next);
256 } else {
257 return false;
258 }
259 if (!ok) {
260 ESP_LOGV(TAG, "Malformed %s sentence", address);
261 return false;
262 }
263 next.valid |= next.updated;
264 data = next;
265 return true;
266}
267
268} // namespace esphome::gps
uint8_t checksum
Definition bl0906.h:3
uint16_t year
Definition date_entity.h:0
uint8_t type
NameCopy * next
std::vector< uint8_t > & out
Definition gif.cpp:49
bool parse_nmea_sentence(char *line, size_t len, GPSData &data)
Parse one NMEA line of len bytes, which is changed in place; the sentence starts at the last '$'.
Definition nmea.cpp:226
ESPHOME_LOG_TAG(TAG, "gps")
GPSField
Bits of GPSData::updated and GPSData::valid.
Definition nmea.h:14
@ GPS_FIELD_LOCATION
Definition nmea.h:15
@ GPS_FIELD_GEOID_SEPARATION
Definition nmea.h:23
@ GPS_FIELD_COURSE
Definition nmea.h:17
@ GPS_FIELD_SPEED
Definition nmea.h:16
@ GPS_FIELD_SATELLITES
Definition nmea.h:19
@ GPS_FIELD_DATE
Definition nmea.h:22
@ GPS_FIELD_HDOP
Definition nmea.h:20
@ GPS_FIELD_ALTITUDE
Definition nmea.h:18
@ GPS_FIELD_TIME
Definition nmea.h:21
std::span< const uint8_t > data
num_t degrees(num_t rad)
Definition sun.cpp:26
constexpr uint8_t xor_bytes(const uint8_t *data, size_t len, uint8_t init=0)
XOR the bytes of data with size len, starting from init.
Definition helpers.h:1096
uint8_t days_in_month(uint8_t month, uint16_t year)
Definition time.cpp:100
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:401
void const char int line
Definition log.h:110
size_t size_t pos
Definition helpers.h:1530
const char * fields_[MAX_FIELDS]
Definition nmea.cpp:34
size_t count_
Definition nmea.cpp:35
static void uint32_t
Values from GGA and RMC sentences as scaled integers; a name ending in eN is the value times 10^N.
Definition nmea.h:29